首页 > 解决方案 > 一个热编码返回最后一个分类值的所有 0 向量

问题描述

tf.one_hot()[0,0,0]正在为第三类可能的分类值生成向量。

我会期待一个[1,0,0]. 我在这个功能上做错了什么?

我想对 3 个可能的分类类进行 One-Hot 编码。1,2,3 使用tf.one_hot().

例子:

# 3 possible classes
print(df['sent_score'].unique())
# array([1., 2., 3.])


#original
labels1 = np.asarray(df['sent_score'])
print("Original Labels \n", labels1[25:30])

# Original Labels 
# [2. 1. 2. 1. 3.]   

 
# one hot encoded
labels = tf.one_hot(labels1, 3)
print("\nOne Hot labels \n", labels[25:30])

# One Hot labels 
#    [[0. 0. 1.]
#    [0. 1. 0.]
#    [0. 0. 1.]
#    [0. 1. 0.]
#    [0. 0. 0.]]  ##WHY IS THIS VECTOR is [0,0,0] and not [1,0,0]

标签: pythontensorflowkerasneural-networkone-hot-encoding

解决方案


问题是因为tf.one_hot也考虑0作为一个类,所以假设你的标签是 1-3,当传递给它时,只用stf.one_hot填充3类。0

简单的例子:

indices = [0, 1, 2]
tf.one_hot(indices, 3)
# <tf.Tensor: shape=(3, 3), dtype=float32, numpy=
# array([[1., 0., 0.],
#        [0., 1., 0.],
#        [0., 0., 1.]], dtype=float32)>

indices = [0, 1, 2, 3]
tf.one_hot(indices, 3)
# array([[1., 0., 0.],
#        [0., 1., 0.],
#        [0., 0., 1.],
#        [0., 0., 0.]], dtype=float32)>

因此,您应该将类​​更改为 0-2 范围内,然后将它们传递给tf.one_hot

参考


推荐阅读