8

How can you convert a tensor into a Numpy ndarray, without using eval or sess.run()?

I need to pass a tensor into a feed dictionary and I already have a session running.

araman
  • 93
  • 1
  • 2
  • 7
  • Think of a Tensor as a placeholder in the computation graph, it has no value, therefore you can't just convert it to a Numpy array. You can, however, "query" the value that flows to it in the computation using eval or run. What exactly are you trying to achieve? There may be a better way to do it. – Avishkar Bhoopchand Jul 28 '16 at 22:30

3 Answers3

5

The fact that you say "already have a session running" implies a misunderstanding of what sess.run() actually does.

If you have a tf.Session() initiated, you should be able to use it to retrieve any tensor using sess.run(). If you need to retrieve a variable or constant tensor this is very straight forward.

value = sess.run(tensor_to_retrieve)

If the tensor is the result of operations on placeholder tensors, you will need to pass them in with feed_dict.

value = sess.run(tensor, feed_dict={input_placeholder: input_value})

There is nothing preventing you from calling sess.run() more than once.

jasekp
  • 990
  • 1
  • 8
  • 17
0

@jasekp answer helped me a lot. I have faced the tensor->ndarray conversion in the specific case of tensors representing (adversarial) images.

I think that my question/answer (here) may be an helpful example for the specific case or may help newbies to better understand @jasekp answer.

My example also covers the matplotlib image visualization part, but this is OT.

Fabiano Tarlao
  • 3,024
  • 33
  • 40
-3

.numpy() will convert tensor to an array.