给定一个一维下标数组:

a = array([1, 0, 3])

我想把它编码成一个2D数组:

b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])

当前回答

我最近遇到了一个类似的问题,发现只有当你的数字符合特定的形式时,答案才令人满意。例如,如果你想单热编码以下列表:

all_good_list = [0,1,2,3,4]

继续吧,上面已经提到了发布的解决方案。但如果考虑到这些数据:

problematic_list = [0,23,12,89,10]

如果使用上面提到的方法,最后可能会得到90个单一热列。这是因为所有答案都包含n = np.max(a)+1。我找到了一个更通用的解决方案,想和你们分享:

import numpy as np
import sklearn
sklb = sklearn.preprocessing.LabelBinarizer()
a = np.asarray([1,2,44,3,2])
n = np.unique(a)
sklb.fit(n)
b = sklb.transform(a)

我希望有人遇到上述解决方案的相同限制,这可能会派上用场

其他回答

对于1-hot-encoding

   one_hot_encode=pandas.get_dummies(array)

例如

享受编码

这种类型的编码通常是numpy数组的一部分。如果你使用numpy数组,像这样:

a = np.array([1,0,3])

然后有一个非常简单的方法将其转换为1-hot编码

out = (np.arange(4) == a[:,None]).astype(np.float32)

就是这样。

创建一个有足够列的零数组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.]])
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))
>>> 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.]])