Valentin
Valentin

Reputation: 1654

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

I'm paring TFRecords which provide me a label as numerical value. But I need to convert this value into categorical vector while I'm reading proto records. How can I do that. Here is code snippet for reading the proto records:

 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

I know that there is tf.keras.utils.to_categorical function but it does not take a Tensor as an input.

Upvotes: 3

Views: 1444

Answers (1)

nessuno
nessuno

Reputation: 27042

You simply need to convert the label to its one-hot representation (that's the representation you described):

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

Upvotes: 6

Related Questions