我有一个numpy arrayA
:
array([[ 1.],
[ 7.],
[ 2.],
[ 9.],
[ 0.],
[ 4.],
[ 1.],
[ 4.],
[ 8.]])
现在我想创建另一个宽度为10且默认单元格值为0的numpy数组(arrayB
)。现在逐行检查arrayA
,将值作为{的行索引{1}}并将值设置为1。
arrayB应该如下所示:
arrayB
我之所以这样做:
我有一个神经网络,[[0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,1,0,0],
[0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0],
[0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0]]
保存每个输入模式的类别(真实数组有25010行)。但我想要10个输出神经元(每个类别一个),所以我需要一个数组,每个模式有9个0&1;和1个在右边的类别。
答案 0 :(得分:0)
您可以使用advanced integer indexing执行此操作。但是,您需要先将数组转换为整数,然后删除第二个维度:
>>> import numpy as np
>>> # preprocess your array
>>> arr = np.array([[1.], [7.], [2.], [9.], [0.], [4.], [1.], [4.], [8.]])
>>> arr = arr.astype(int)[:, 0]
>>> # create a result array
>>> new = np.zeros((arr.shape[0], 10), int)
>>> new[np.arange(arr.shape[0]), arr] = 1 # advanced indexing
>>> new
array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]])