从numpy中的类别数组创建矩阵
我有一个长度为n的numpy数组,y,由[0…k-1]范围内的整数组成。由此,我想创建一个n×k的numpy矩阵M,其中,如果y[I]==j,则M[I,j]为1,否则为0 在numpy实现这一点的最佳方式是什么?使用广播:从numpy中的类别数组创建矩阵,numpy,Numpy,我有一个长度为n的numpy数组,y,由[0…k-1]范围内的整数组成。由此,我想创建一个n×k的numpy矩阵M,其中,如果y[I]==j,则M[I,j]为1,否则为0 在numpy实现这一点的最佳方式是什么?使用广播: a = np.array([1, 2, 3, 1, 2, 2, 3, 0]) m = a[:, None] == np.arange(max(a)+1) 结果是: array([[False, True, False, False], [False, Fal
a = np.array([1, 2, 3, 1, 2, 2, 3, 0])
m = a[:, None] == np.arange(max(a)+1)
结果是:
array([[False, True, False, False],
[False, False, True, False],
[False, False, False, True],
[False, True, False, False],
[False, False, True, False],
[False, False, True, False],
[False, False, False, True],
[ True, False, False, False]], dtype=bool)
或者创建一个零数组并填充,我认为这样更快:
m2 = np.zeros((len(a), a.max()+1), np.bool)
m2[np.arange(len(a)), a] = True
print m2
这可能有点离谱,但它是一个相当可扩展的解决方案,至少值得注意。如果您已经获得,则该类用于将数据集中的分类特征转换为按列的二进制表示,如您所述:
import numpy as np
from sklearn.feature_extraction import DictVectorizer
# starting with your numpy array
y = np.array([1, 2, 3, 1, 2, 2, 3, 0])
# transform the array to a list of dicts, with original
# int values now as strings, and a throw-away key ''
y_dict = [{'':str(x)} for x in y.tolist()]
# create the vectorizer and transform the list of dicts
vec = DictVectorizer(sparse=False, dtype=int)
M = vec.fit_transform(y_dict)
print M
[[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
[0 1 0 0]
[0 0 1 0]
[0 0 1 0]
[0 0 0 1]
[1 0 0 0]]
再说一次,可能是矫枉过正了,但它有点可爱,我想我应该把它扔出去。我想你的第二个建议很好。谢谢