简体   繁体   中英

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.

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 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.

.nu​​mpy() 将张量转换为数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM