如何将 TF Tensor 持有值转换为 Tensor 持有分类值

How to convert TF Tensor holding value into Tensor holding categorical values

我正在对 TFRecords 进行配对,它为我提供了一个标签作为数值。但是我需要在读取原始记录时将此值转换为分类向量。我怎样才能做到这一点。这是读取原型记录的代码片段:

 def parse(example_proto):
     features={'label':: tf.FixedLenFeature([], tf.int64), ...}
     parsed_features = tf.parse_single_example(example_proto, features)
     label = tf.cast(parsed_features['label'], tf.int32)
     # at this point label is a Tensor which holds numerical value
     # but I need to return a Tensor which holds categorical vector
     # for instance, if my label is 1 and I have two classes
     # I need to return a vector [1,0] which represents categorical values

我知道有 tf.keras.utils.to_categorical 函数,但它没有将 Tensor 作为输入。

您只需将标签转换为其单热表示(即您描述的表示):

label = tf.cast(parsed_features['label'], tf.int32)
num_classes = 2
label = tf.one_hot(label, num_classes)