Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow: Convert Tensor to numpy array WITHOUT .eval() or sess.run()

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.

like image 664
araman Avatar asked Jul 28 '16 21:07

araman


People also ask

Can you convert a tensor to NumPy array?

To convert a tensor t to a NumPy array in TensorFlow version 2.0 and above, use the t. numpy() built-in method. The resulting object is a NumPy array of type numpy. ndarray .

How do I save a tensor as a NumPy array?

To convert back from tensor to numpy array you can simply run . eval() on the transformed tensor.

What does NumPy () do in TensorFlow?

Both in Pytorch and Tensorflow, the . numpy() method is pretty much straightforward. It converts a tensor object into an numpy. ndarray object.

Which is faster TensorFlow or NumPy?

Tensorflow is consistently much slower than Numpy in my tests.


1 Answers

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.

like image 86
jasekp Avatar answered Sep 29 '22 15:09

jasekp