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

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

问题描述

假设我有一个一维的numpy数组

Let's say I have a 1d numpy array

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

我想将其编码为2维1热点数组

I would like to encode this as a 2d 1-hot array

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

有没有一种快速的方法来做到这一点?比仅循环遍历a设置b的元素要快.

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

推荐答案

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

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天全站免登陆