【问题标题】:Tensorflow Value for attr 'TI' of float is not in the list of allowed values when One Hot Encoding当 One Hot Encoding 时,浮点的 attr 'TI' 的 Tensorflow 值不在允许值列表中
【发布时间】:2021-12-25 11:19:35
【问题描述】:

我有这段代码,它采用形状为(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 的版本或张量的数据类型上,但任何其他解决方案都会受到赞赏。

【问题讨论】:

    标签: python tensorflow machine-learning math google-colaboratory


    【解决方案1】:

    您可以简单地将您的张量转换为 tf.int32 或类似的,因为 tf.one_hot 需要整数 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)
    

    【讨论】:

    • 解决了您的问题吗?
    • 是的,它成功了,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2021-08-30
    • 2023-03-17
    相关资源
    最近更新 更多