为了使用 tensorflow ,我的类需要一个热向量。
我有以下代码来创建一个单热向量,但看起来它对于 numpy 广播来说应该已经成熟了。
def classVector2oneHot(classVector):
uniques = np.asarray(list(set(classVector)))
one_hot_array = np.zeros(shape=(classVector.shape[0],uniques.shape[0]),dtype=np.float32)
starting_index = np.min(uniques)
# where broadcasting seems like it should be possible, somehow...
for i in range(len(one_hot_array)):
one_hot_array[i,classVector[i]-starting_index] = 1
return one_hot_array
最佳答案
这是一种使用 broadcasting
的方法-
(classVector[:,None] == uniques).astype(float)
示例运行 -
In [47]: classVector
Out[47]: array([15, 16, 24, 20, 14, 12, 14, 19, 12, 21])
In [48]: uniques = np.unique(classVector)
In [49]: uniques
Out[49]: array([12, 14, 15, 16, 19, 20, 21, 24])
In [50]: (classVector[:,None] == uniques).astype(float)
Out[50]:
array([[ 0., 0., 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 1., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 1.],
[ 0., 0., 0., 0., 0., 1., 0., 0.],
[ 0., 1., 0., 0., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0.],
[ 1., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 1., 0.]])
关于Python广播: how to unleash NumPy speed when filling in a One-Hot vector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41947379/