Python 广播:如何在填充 One-Hot 向量时释放 NumPy 的速度?

Python Broadcasting: how to unleash NumPy speed when filling in a One-Hot vector?

为了使用 tensorflow,我的 类 需要一个 one hot vector。

我有以下代码来创建一个单热向量,但它似乎应该适合 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.]])