【问题标题】:how to construct object of the same type that `tf.one_hot` returns?如何构造与 `tf.one_hot` 返回的相同类型的对象?
【发布时间】:2021-06-25 20:46:07
【问题描述】:

我在数据管道中使用了一个函数input_preprocess:

def input_preprocess(image, label):
    if label == 1:
        return tf.zeros(NUM_CLASSES)
    else:
        label = tf.one_hot(label, NUM_CLASSES)
    return image, label

问题是tf.one_hot 返回的是sequence,但tf.zeros 返回的不是。

我收到以下错误:

 The two structures don't have the same nested structure.
    
    First structure: type=Tensor str=Tensor("cond/zeros_like:0", shape=(28,), dtype=float32)
    
    Second structure: type=tuple str=(<tf.Tensor 'args_0:0' shape=(224, 224, 3) dtype=float32>, <tf.Tensor 'cond/one_hot:0' shape=(28,) dtype=float32>)
    
    More specifically: Substructure "type=tuple str=(<tf.Tensor 'args_0:0' shape=(224, 224, 3) dtype=float32>, <tf.Tensor 'cond/one_hot:0' shape=(28,) dtype=float32>)" is a sequence, while substructure "type=Tensor str=Tensor("cond/zeros_like:0", shape=(28,), dtype=float32)" is not
    Entire first structure:
    .
    Entire second structure:
    (., .)

我如何手动构建可以代表tf.one_hot 返回的内容?

【问题讨论】:

    标签: python tensorflow tensorflow2.0 tensorflow-datasets


    【解决方案1】:

    tf.one_hot 返回一个EagerTensor,就像tf.zeros:

    a = tf.one_hot(1,2)
    print(type(a))
    b = tf.zeros(2)
    print(type(b))
    # tensorflow.python.framework.ops.EagerTensor
    # tensorflow.python.framework.ops.EagerTensor
    

    我认为您的问题是您的 函数 input_preprocess 如果 label == 1 (第一次返回)和一个 元组 返回一个 单个值否则(第二次返回)。

    【讨论】:

    • 非常感谢@SuperCiocia,就是这样!!!不知道我是怎么错过的...感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多