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.
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 .
To convert back from tensor to numpy array you can simply run . eval() on the transformed tensor.
Both in Pytorch and Tensorflow, the . numpy() method is pretty much straightforward. It converts a tensor object into an numpy. ndarray object.
Tensorflow is consistently much slower than Numpy in my tests.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With