Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have one dimensional numpy array. After performing a calculation in TensorFlow, I get a tf.Tensor as output. I am trying to reshape it into a 2-dimensional array and show it as an image.

If it were a numpy ndarray, I would know how to plot it as an image. But it is a tensor now!

Although I tried tensor.eval() to convert it into numpy array, I got an error saying "No default session".

Can anyone teach me how to show a tensor as an image?

... ...
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()
... ...
like image 745
Yee Liu Avatar asked Feb 18 '16 22:02

Yee Liu


People also ask

What is an image tensor?

The size of each dimension in a Tensor we call its shape. For example, a Tensor to represent a black and white image would have the shape [ width , height , colors ]. For a 640 x 480 pixel black and white image, the shape would be [640,480, 1].

How do I print tf tensor values?

[A]: To print the value of a tensor without returning it to your Python program, you can use the tf. print() operator, as Andrzej suggests in another answer. According to the official documentation: To make sure the operator runs, users need to pass the produced op to tf.

How do you represent a tensor in Python?

Tensors in Python Like vectors and matrices, tensors can be represented in Python using the N-dimensional array (ndarray). A tensor can be defined in-line to the constructor of array() as a list of lists. The example below defines a 3x3x3 tensor as a NumPy ndarray. Three dimensions is easier to wrap your head around.


1 Answers

The immediate error you're seeing is because Tensor.eval() only works when there is a "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.

There are two simple workarounds to make your case work:

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

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

Note that, as a large point about visualizing your image, you might consider using the tf.image_summary() op along with TensorBoard to visualize tensors produced by a larger training pipeline.

like image 181
mrry Avatar answered Nov 15 '22 11:11

mrry