给定一个一维下标数组:
a = array([1, 0, 3])
我想把它编码成一个2D数组:
b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
给定一个一维下标数组:
a = array([1, 0, 3])
我想把它编码成一个2D数组:
b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
当前回答
def one_hot(n, class_num, col_wise=True):
a = np.eye(class_num)[n.reshape(-1)]
return a.T if col_wise else a
# Column for different hot
print(one_hot(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 8, 7]), 10))
# Row for different hot
print(one_hot(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 8, 7]), 10, col_wise=False))
其他回答
创建一个有足够列的零数组b,即a.max() + 1。 然后,对于每一行i,设置第a[i]列为1。
>>> a = np.array([1, 0, 3])
>>> b = np.zeros((a.size, a.max() + 1))
>>> b[np.arange(a.size), a] = 1
>>> b
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
你也可以使用numpy的eye函数:
numpy。眼(类数)[包含标签的向量]
P是一个2d ndarray。 我们想知道哪一个值在一行中是最大的,在这里是1,其他地方是0。
干净简单的解决方案:
max_elements_i = np.expand_dims(np.argmax(p, axis=1), axis=1)
one_hot = np.zeros(p.shape)
np.put_along_axis(one_hot, max_elements_i, 1, axis=1)
>>> values = [1, 0, 3]
>>> n_values = np.max(values) + 1
>>> np.eye(n_values)[values]
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
使用下面的代码。这样效果最好。
def one_hot_encode(x):
"""
argument
- x: a list of labels
return
- one hot encoding matrix (number of labels, number of class)
"""
encoded = np.zeros((len(x), 10))
for idx, val in enumerate(x):
encoded[idx][val] = 1
return encoded
在这里找到了p.s.你不需要进入链接。