【问题标题】:TypeError: Image data cannot be converted to float after tf.image.per_image_standardization(x)TypeError:图像数据在 tf.image.per_image_standardization(x) 之后无法转换为浮点数
【发布时间】:2019-02-11 17:21:49
【问题描述】:

我在plt.imshow 收到以下错误

TypeError: Image data cannot be converted to float

对于此代码:

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()

任何想法为什么会发生这种情况?谢谢!

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    在您的脚本中,train_images 不包含实际数据,而只是占位符张量:

    train_images[1]
    <tf.Tensor 'strided_slice_2:0' shape=(28, 28) dtype=float32>
    

    最简单的解决方案是在脚本顶部启用即时执行:

    tf.enable_eager_execution()
    

    这意味着在运行时,张量实际上将包含您尝试绘制的数据:

    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
    

    这应该可以解决您的错误。您可以在 TF 的 website 上阅读更多关于 Eager Execution 的信息。

    或者,您也可以通过实际评估会话中的图像张量来制作绘图:

    with tf.Session() as sess:
        img = sess.run(train_images[1])
        plt.figure()
        plt.imshow(img)
        plt.colorbar()
        plt.grid(False)
        plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-24
      • 1970-01-01
      • 2017-11-12
      • 2023-03-30
      • 2020-07-24
      • 2018-05-22
      • 1970-01-01
      相关资源
      最近更新 更多