python - 当 One Hot Encoding 时,浮点的 attr 'TI' 的 Tensorflow 值不在允许值列表中
问题描述
我有这段代码,它采用形状为的张量(3, 3)
并将其重塑为 (9,)
. 之后,它应用了一个one_hot
函数,但它抛出了一个错误。
这是代码:
import tensorflow as tf
t1 = tf.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=tf.float32)
t2 = tf.constant([[1], [-1], [1]], dtype=tf.float32)
print(tf.one_hot(tf.reshape(t1, -1), depth=2))
错误是:
InvalidArgumentError: Value for attr 'TI' of float is not in the list of allowed values: uint8, int32, int64
; NodeDef: {{node OneHot}}; Op<name=OneHot; signature=indices:TI, depth:int32, on_value:T, off_value:T -> output:T; attr=axis:int,default=-1; attr=T:type; attr=TI:type,default=DT_INT64,allowed=[DT_UINT8, DT_INT32, DT_INT64]> [Op:OneHot]
我正在使用 GoogleColab 笔记本,所以我认为问题可能是 TensorFlow 的版本或张量的数据类型,但任何其他解决方案都会受到赞赏。
解决方案
您可以简单地将您的张量转换为tf.int32
或类似,因为tf.one_hot
需要 integer indices
:
import tensorflow as tf
t1 = tf.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=tf.float32)
t2 = tf.constant([[1], [-1], [1]], dtype=tf.float32)
print(tf.one_hot(tf.cast(tf.reshape(t1, -1), dtype=tf.int32), depth=3))
tf.Tensor(
[[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]
[1. 0. 0.]
[1. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]], shape=(9, 3), dtype=float32)
或与depth=2
:
tf.Tensor(
[[0. 1.]
[1. 0.]
[1. 0.]
[1. 0.]
[0. 1.]
[1. 0.]
[1. 0.]
[1. 0.]
[0. 1.]], shape=(9, 2), dtype=float32)
推荐阅读
- ios - 使用 Cordova 应用程序在 iOS 上列出附近的 wifi 网络
- html - 背景网址不显示
- python - 我有一个文本文件(12 列和 10K 行)。我想从文本文件加载数据并馈送到二维数组
- html - 提供索引文件而不是下载提示
- javascript - 项目完成后,如何停止其中一个计数计时器(例如 countup2)并显示完成前的经过时间?
- python - 从 R 和 Python 发送电子邮件:535 5.7.3 身份验证不成功
- ios - 重复 iphone 提醒应用程序中的事件
- database - 在数据库中查找类似的文件/记录
- regex - 搜索大写或小写单词并返回大写或小写
- oracle - 尝试在表中插入一行并创建触发器后出现这些错误