给定一个一维下标数组:

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

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

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

当前回答

如果你正在使用keras,有一个内置的实用程序:

from keras.utils.np_utils import to_categorical   

categorical_labels = to_categorical(int_labels, num_classes=3)

它与@YXD的答案几乎相同(请参阅源代码)。

其他回答

对于1-hot-encoding

   one_hot_encode=pandas.get_dummies(array)

例如

享受编码

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

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)

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

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))

如果你正在使用keras,有一个内置的实用程序:

from keras.utils.np_utils import to_categorical   

categorical_labels = to_categorical(int_labels, num_classes=3)

它与@YXD的答案几乎相同(请参阅源代码)。

你可以使用下面的代码转换成一个热向量:

设x是普通的类向量,它只有一个列,从0到某个数:

import numpy as np
np.eye(x.max()+1)[x]

如果0不是一个类;然后移除+1。