Search code examples
evaltensorflowone-hot-encoding

Tensorflow : one hot encoding


The following code works fine, but uses eval() which I think would be inefficient. Is there a better way to achieve the same ?

import tensorflow as tf
import numpy as np
sess = tf.Session()
t = tf.constant([[4,5.1,6.3,5,6.5,7.2,9.3,7,1,1.4],[4,5.1,9.3,5,6.5,7.2,1.3,7,1,1.4],[4,3.1,6.3,5,6.5,3.2,5.3,7,1,1.4]])
print t
a = tf.argmax(t,1).eval(session=sess)
z = [ k==np.arange(14) for k in a]
z1 = tf.convert_to_tensor(np.asarray(z).astype('int32'))
print z1
print sess.run(z1)

output

Tensor("Const_25:0", shape=TensorShape([Dimension(3), Dimension(10)]), dtype=float32)
Tensor("Const_26:0", shape=TensorShape([Dimension(3), Dimension(14)]), dtype=int32)
[[0 0 0 0 0 0 1 0 0 0 0 0 0 0]
 [0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 1 0 0 0 0 0 0]]

Solution

  • One way to achieve it is to compute max on each row and then compare each element to that value. I don't have tensor flow installed on this machine, so can't provide you with the exact code, but it will be along the lines of this:

    z1 = tf.equal(t, tf.reduce_max(t, reduction_indices=[1], keep_dims=True))