I am getting the following error at plt.imshow
TypeError: Image data cannot be converted to float
For this code:
import keras
import tensorflow as tf
import matplotlib.pyplot as plt
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
def preprocess(x):
x = tf.image.per_image_standardization(x)
return x
train_images = preprocess(train_images)
test_images = preprocess(test_images)
plt.figure()
plt.imshow(train_images[1])
plt.colorbar()
plt.grid(False)
plt.show()
Any ideas why this is happening? Thanks!
In your script, train_images
do not contain actual data but are merely placeholder Tensors:
train_images[1]
<tf.Tensor 'strided_slice_2:0' shape=(28, 28) dtype=float32>
The simplest solution would be to enable eager execution at the top of your script:
tf.enable_eager_execution()
This means that at runtime, the tensors will actually contain the data that you are trying to plot:
train_images[1]
<tf.Tensor: id=95, shape=(28, 28), dtype=float32, numpy=
array([[-0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 ,
-0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 ,
-0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 ,
-0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 ,
-0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 ,
-0.4250042 , -0.4250042 , -0.4250042 ], # etc
Which should solve your error. You can read more about eager execution on TF's website .
Alternatively, you can also make the plot by actually evaluating the image tensors in a session:
with tf.Session() as sess:
img = sess.run(train_images[1])
plt.figure()
plt.imshow(img)
plt.colorbar()
plt.grid(False)
plt.show()
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.