简体   繁体   English

Tensorflow:在没有 .eval() 或 sess.run() 的情况下将 Tensor 转换为 numpy 数组

[英]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()?如何在不使用 eval 或 sess.run() 的情况下将张量转换为 Numpy ndarray?

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.您说“已经有一个会话正在运行”这一事实意味着对 sess.run() 实际作用的误解。

If you have a tf.Session() initiated, you should be able to use it to retrieve any tensor using sess.run().如果您启动了 tf.Session(),您应该能够使用它来检索使用 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.如果张量是占位符张量运算的结果,则需要将它们与 feed_dict 一起传递。

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

There is nothing preventing you from calling sess.run() more than once.没有什么可以阻止您多次调用 sess.run() 。

@jasekp answer helped me a lot. @jasekp 的回答对我帮助很大。 I have faced the tensor->ndarray conversion in the specific case of tensors representing (adversarial) images.在表示(对抗性)图像的张量的特定情况下,我遇到了tensor->ndarray转换。

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.我认为我的问题/答案( 此处)可能是特定案例的有用示例,或者可能有助于新手更好地理解 @jasekp 答案。

My example also covers the matplotlib image visualization part, but this is OT.我的示例还涵盖了matplotlib图像可视化部分,但这是 OT。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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