【问题标题】:Input 0 is incompatible with layer model_1: expected shape=(None, 244, 720, 3), found shape=(None, 720, 3)输入 0 与层 model_1 不兼容:预期 shape=(None, 244, 720, 3),发现 shape=(None, 720, 3)
【发布时间】:2021-06-02 15:55:42
【问题描述】:

我想通过上传图片来测试我的模型,但我收到了这个错误。而且我认为我在这些行中的某个地方遇到了错误,我只是不确定如何解决。

IMAGE_SIZE = [244,720]
inception = InceptionV3(input_shape=IMAGE_SIZE + [3], weights='imagenet',include_top=False)

这里也是上传我的测试图片的代码

picture =  image.load_img('/content/DSC_0365.JPG', target_size=(244,720))
img = img_to_array(picture)
prediction = model.predict(img)
print (prediction)

我还是机器学习的新手,所以我现在的知识还没有那么深。

【问题讨论】:

    标签: tensorflow machine-learning keras deep-learning conv-neural-network


    【解决方案1】:

    这主要是因为您没有为初始模型准备输入(其维度)。这是一种可能的解决方案。


    型号

    from tensorflow.keras.applications import *
    
    IMAGE_SIZE = [244,720]
    inception = InceptionV3(input_shape=IMAGE_SIZE + [3], 
                             weights='imagenet', include_top=False)
    
    # check it's input shape 
    inception.input_shape
    (None, 244, 720, 3)
    

    推理

    让我们通过将样本传递给模型来测试它。

    from PIL import Image 
    
    a = Image.open('/content/1.png').convert('RGB')
    display(a)
    

    检查它的基本属性。

    a.mode, a.size, a.format
    ('RGB', (297, 308), None)
    

    所以,它的形状已经在 (297 x 308 x 3) 中了。但是为了能够将它传递给模型,我们需要一个额外的轴,即批处理轴。为此,我们可以这样做

    import tensorflow as tf
    import numpy as np 
    
    a = tf.expand_dims(np.array(a), axis=0)
    a.shape
    TensorShape([1, 308, 297, 3])
    

    好多了。现在,我们可能想要标准化我们的数据并根据模型输入形状调整它的大小。为此,我们可以这样做:

    a = tf.divide(a, 255)       
    a = tf.image.resize(a, [244,720])  
    a.shape
    TensorShape([1, 244, 720, 3])
    

    最后,将它传递给模型。

    inception(a).shape
    TensorShape([1, 6, 21, 2048])
    
    # or, preserve the prediction to later analysis 
    y_pred = inception(a)
    

    更新

    如果你使用的是[tf.keras]图像处理函数,将图像加载为PIL格式,那么我们可以简单地做:

    image = tf.keras.preprocessing.image.load_img('/content/1.png', 
                                                 target_size=(244,720))
    input_arr = tf.keras.preprocessing.image.img_to_array(image)
    input_arr = np.array([input_arr])  # Convert single image to a batch.
    
    inception(input_arr).shape
    TensorShape([1, 6, 21, 2048])
    

    【讨论】:

    • 谢谢,先生!我会编辑我的代码,我会在得到结果后更新你。
    • 成功了。 :) 但是要补充一点,如何将调整大小的图像插入到我的代码中以预测图像(代码在我更新的帖子中说明)?
    • picture = image.load_img('/content/DSC_0365.JPG', target_size=(244,720)) img = img_to_array(picture) prediction = model.predict(img) print(预测)
    • 那是我以前的代码。如何在其中插入调整大小的图像?
    • 哇哦,我明白了。谢谢你,先生!问题解决了。我感谢你的努力,更多的力量!祝你有美好的一天!
    猜你喜欢
    • 2021-03-30
    • 2021-12-31
    • 2022-01-16
    • 2022-06-21
    • 2021-12-14
    • 1970-01-01
    • 2020-11-15
    • 2021-03-30
    • 2022-01-26
    相关资源
    最近更新 更多