Val*_*tin 3 python categorical-data tensorflow
我正在配对 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
Run Code Online (Sandbox Code Playgroud)
我知道有tf.keras.utils.to_categorical函数,但它不接受张量作为输入。
您只需将标签转换为其独热表示形式(即您所描述的表示形式):
label = tf.cast(parsed_features['label'], tf.int32)
num_classes = 2
label = tf.one_hot(label, num_classes)
Run Code Online (Sandbox Code Playgroud)