How to implement N-hot encoding according to the index of 1 in a tf.int64 ? The input is tensor containing several tf.int64. The N-hot encoding is aimed to replace one-hot encoding in tf.slim.
The one_hot encoding is implemented as following:
def dense_to_one_hot(labels_dense, num_classes):
"""Convert class labels from scalars to one-hot vectors."""
num_labels = labels_dense.shape[0]
index_offset = numpy.arange(num_labels) * num_classes
labels_one_hot = numpy.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot
The N-not encoding means: 19=00010011, the result after encoding is [0,0,0,1,0,0,1,1].
This is one solution:
Output:
It assumes that the
N
is a regular scalar (not a TensorFlow value) and that the number of dimensions of the array to convert is known (the size of each dimension can be dynamic, buta.shape
should not be justNone
). The function can be adapted to TensorFlow-only computation like this:This should work with any input but may do a bit more of extra work on every graph run.
Find below an alternative to @jdehesa great answer. This version computes the bit length
N
itself (but works on single-valued tensors only - or tensors containing values of same bit length):Previous Answer:
Using
tf.one_hot()
: