Abh*_*yal 34 python numpy one-hot-encoding
如果输入为零,我想创建一个如下所示的数组:
[1,0,0,0,0,0,0,0,0,0]
Run Code Online (Sandbox Code Playgroud)
如果输入为5:
[0,0,0,0,0,1,0,0,0,0]
Run Code Online (Sandbox Code Playgroud)
对于上面我写道:
np.put(np.zeros(10),5,1)
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
有什么方法可以在一行中实现吗?
Mar*_*oma 66
通常,当您想要在机器学习中获得用于分类的单热编码时,您有一个索引数组.
import numpy as np
nb_classes = 6
targets = np.array([[2, 3, 4, 0]]).reshape(-1)
one_hot_targets = np.eye(nb_classes)[targets]
Run Code Online (Sandbox Code Playgroud)
现在one_hot_targets是
array([[[ 0., 0., 1., 0., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 1., 0.],
[ 1., 0., 0., 0., 0., 0.]]])
Run Code Online (Sandbox Code Playgroud)
这.reshape(-1)是为了确保您拥有正确的标签格式(您可能也有[[2], [3], [4], [0]]).这-1是一个特殊值,意思是"将所有剩余的东西放在这个维度中".因为只有一个,它会使阵列变平.
def get_one_hot(targets, nb_classes):
res = np.eye(nb_classes)[np.array(targets).reshape(-1)]
return res.reshape(list(targets.shape)+[nb_classes])
Run Code Online (Sandbox Code Playgroud)
你可以使用mpu.ml.indices2one_hot.它经过测试且易于使用:
import mpu.ml
one_hot = mpu.ml.indices2one_hot([1, 3, 0], nb_classes=5)
Run Code Online (Sandbox Code Playgroud)
就像是 :
np.array([int(i == 5) for i in range(10)])
Run Code Online (Sandbox Code Playgroud)
应该做的伎俩.但我想存在使用numpy的其他解决方案.
编辑:你的公式不起作用的原因:np.put不返回任何内容,它只是修改第一个参数中给出的元素.使用时的好答案np.put()是:
a = np.zeros(10)
np.put(a,5,1)
Run Code Online (Sandbox Code Playgroud)
问题是它无法在一行中完成,因为您需要在将数组传递给它之前定义它 np.put()
您可以使用列表理解:
[0 if i !=5 else 1 for i in range(10)]
Run Code Online (Sandbox Code Playgroud)
转向
[0,0,0,0,0,1,0,0,0,0]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57055 次 |
| 最近记录: |