如何构造与`tf.one_hot`returns相同类型的对象?

how to construct object of the same type that `tf.one_hot` returns?

我在数据管道中使用了一个函数 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 returns 是 sequencetf.zeros returns 不是

我收到以下错误:

 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 returns 的东西?

tf.one_hot return 一个 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_preprocessreturn是一个单值如果label == 1(第一个return)和一个元组,否则(第二个return)。