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

标签 python numpy array-broadcasting

为了使用 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/

相关文章:

python - Django + PostgreSQL - 1000 次插入/秒,如何加速?

python - 如何为 Windows 制作 python 模块安装程序?

python - 问题拟合曲线:

python - 未知维度张量的逐元素乘法

python - 游戏图形数组的快速操作

python - 在 Python 中以编程方式创建变量

python - 成对组合来自两个数组的元素

python - 如何将 OpenNI VideoFrame 转换为 OpenCV Mat 数据结构?

python - numpy 索引 : add vector to parts of rows, 从不同位置开始

python - 广播在这个 numpy 的例子中是如何应用的?