计算张量后,如何将其显示为图像?

After calculating a tensor, how can I show it as a image?

我有一维 numpy 数组。在 TensorFlow 中执行计算后,我得到一个 tf.Tensor 作为输出。我正在尝试将其重塑为二维数组并将其显示为图像。

如果它是一个 numpy ndarray,我会知道如何将它绘制成图像。但是现在是张量了!

尽管我尝试 tensor.eval() 将其转换为 numpy 数组,但我收到一条错误消息 "No default session"。

谁能教我如何将张量显示为图像?

... ...
init = tf.initialize_all_variables()    
sess = tf.Session()
sess.run(init)

# training
for i in range(1):
    sess.run(train_step, feed_dict={x: x_data.T, y_: y_data.T})

# testing
probability = tf.argmax(y,1);
sess.run(probability, feed_dict={x: x_test.T})

#show result
img_res = tf.reshape(probability,[len_y,len_x])
fig, ax = plt.subplots(ncols = 1)

# It is the the following line that I do not know how to make it work...
ax.imshow(np.asarray(img_res.eval())) #how to plot a tensor ?#
plt.show()
... ...

您看到的直接错误是因为 Tensor.eval() 仅在存在 "default Session". This requires that either (i) you're executing in a with tf.Session(): block, (ii) you're executing in a with sess.as_default(): block, or (iii) you're using tf.InteractiveSession 时才有效。

有两个简单的解决方法可以使您的案例有效:

# Pass the session to eval().
ax.imshow(img_res.eval(session=sess))

# Use sess.run().
ax.imshow(sess.run(img_res))

请注意,作为可视化图像的重点,您可以考虑使用 tf.image_summary() op along with TensorBoard 来可视化由更大的训练管道产生的张量。