将索引数组转换为 1-hot 编码的 numpy 数组 [英] Convert array of indices to 1-hot encoded numpy array

查看:28
本文介绍了将索引数组转换为 1-hot 编码的 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 1d numpy 数组

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

我想将其编码为二维单热数组

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

有没有快速的方法来做到这一点?比仅仅循环 a 来设置 b 的元素更快,即.

解决方案

你的数组 a 定义了输出数组中非零元素的列.您还需要定义行,然后使用花式索引:

<预><代码>>>>a = np.array([1, 0, 3])>>>b = np.zeros((a.size, a.max()+1))>>>b[np.arange(a.size),a] = 1>>>乙数组([[ 0., 1., 0., 0.],[ 1., 0., 0., 0.],[ 0., 0., 0., 1.]])

Let's say I have a 1d numpy array

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

I would like to encode this as a 2D one-hot array

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

Is there a quick way to do this? Quicker than just looping over a to set elements of b, that is.

解决方案

Your array a defines the columns of the nonzero elements in the output array. You need to also define the rows and then use fancy indexing:

>>> a = np.array([1, 0, 3])
>>> b = np.zeros((a.size, a.max()+1))
>>> b[np.arange(a.size),a] = 1
>>> b
array([[ 0.,  1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.]])

这篇关于将索引数组转换为 1-hot 编码的 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆