python - 一个热编码返回最后一个分类值的所有 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]
解决方案
问题是因为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
推荐阅读
- c - 信号量何时初始化为 0?
- node.js - 什么是“cookie-parser”中间件?
- c# - MySql.Data.MySqlClient.MySqlException:'当阅读器关闭时尝试读取无效。'
- vuejs2 - 在调整大小事件上更新 Vue 模板
- outlook - 我们想知道为什么 Microsoft Graph API 需要超过 24 小时才能更新数据才能访问以进行查询
- javascript - 如何传递包含单引号和双引号的字符串?
- javascript - 在javascript中使用函数获取实时值
- javascript - 尽管状态发生了变化,但自定义钩子不会触发组件重新渲染
- python - 使用请求时 Python 超级强制 HTTP/2
- python - 如何将 CSV 文件中的行存储在字典中?