【问题标题】:Keras : Error when checking input: expected input_1 to have shape (299, 299, 3) but got array with shape (229, 229, 3)Keras:检查输入时出错:预期 input_1 的形状为 (299, 299, 3) 但数组的形状为 (229, 229, 3)
【发布时间】:2020-02-12 13:50:42
【问题描述】:

我正在尝试在 keras 中训练一个 inceptionv3 模型。

我的数据集被预处理成229, 229, 3 形状。

print(data.shape)
print(type(data))
print(type(data[0]))

输出

(1458, 229, 229, 3)

<class 'numpy.ndarray'>

<class 'numpy.ndarray'>

我这样初始化我的模型

import os, sys
from keras.optimizers import SGD
from keras.applications import InceptionV3

model = InceptionV3()

# copile model
opt = SGD(lr=0.05)
model.compile(loss="categorical_crossentropy", optimizer=opt,
              metrics=["accuracy"])

调用model.fit

# train the network
print("[INFO] training network...")
H = model.fit(train_x, train_y, validation_data=(test_x, test_y),
              batch_size=batch_size, epochs=num_of_epochs, verbose=1)

然后我得到这个错误。我不明白,因为尺寸是正确的。

[INFO] training network...
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
 in 
      2 print("[INFO] training network...")
      3 H = model.fit(train_x, train_y, validation_data=(test_x, test_y),
----> 4               batch_size=batch_size, epochs=num_of_epochs, verbose=1)
      5 
      6 model.save(model_save_path)

~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
    950             sample_weight=sample_weight,
    951             class_weight=class_weight,
--> 952             batch_size=batch_size)
    953         # Prepare validation data.
    954         do_validation = False

~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    749             feed_input_shapes,
    750             check_batch_axis=False,  # Don't enforce the batch size.
--> 751             exception_prefix='input')
    752 
    753         if y is not None:

~/anaconda3/lib/python3.7/site-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    136                             ': expected ' + names[i] + ' to have shape ' +
    137                             str(shape) + ' but got array with shape ' +
--> 138                             str(data_shape))
    139     return data
    140 

ValueError: Error when checking input: expected input_1 to have shape (299, 299, 3) but got array with shape (229, 229, 3)

编辑

batch_size = 32

如何调整图像大小

import imutils
import cv2

class AspectAwarePreprocessor:
    """
    CONTRUCTOR
    witdh : desired width
    height : desired height
    inter : interpolation method used when resizing the image
    """
    def __init__(self,width,height,inter=cv2.INTER_AREA):
        self.width = width
        self.height = height
        self.inter = inter

    """
    image : image to be preprocessed
    """
    def preprocess(self,image):
        # Get wdith and height of image
        (h, w) = image.shape[:2]
        dW = 0
        dH = 0

        # if width is the shorter dimension, resize image by width and crop height
        if w < h:
            image = imutils.resize(image, width=self.width,
                                   inter=self.inter)
            dH = int((image.shape[0] - self.height) / 2.0)

        # if height is the shorter dimension, resize image by height and crop width
        else:
            image = imutils.resize(image, height=self.height,
                               inter=self.inter)
            dW = int((image.shape[1] - self.width) / 2.0)

        # re-grab the width and height and use the deltas to crop the center of the image:
        (h, w) = image.shape[:2]
        image = image[dH:h - dH, dW:w - dW]

        # our image target image dimensions may be off by ± one pixel; therefore, we make a call to cv2.resize to 
        # ensure our output image has the desired width and height.
        return cv2.resize(image, (self.width, self.height),
                          interpolation=self.inter)

【问题讨论】:

  • 你能说明你是如何定义你的批量大小的吗?问题似乎与此有关。
  • @AdamB。我在上面更新了它。 batch_size 为 32。

标签: python keras


【解决方案1】:

您正在为您的网络提供一个形状错误的数组。
您的模型需要一个形状数组(299, 299, 3),但您给它一个形状数组(229, 229, 3)

(299, 299, 3) 不是 (229, 229, 3)

所以要么你需要用(299, 299, 3)的形状重塑你的数据,要么你需要改变InceptionV3的预期形状:

model = InceptionV3(include_top=False, input_shape=(229, 229, 3))

如果您想指定输入形状不是默认形状,您必须使用include_top=False

https://keras.io/applications/#inceptionv3

希望我能帮到你!

【讨论】:

  • 嗨,你能解释一下尺寸是怎么错的吗?因为它们看起来完全一样。另外 include_top=False,我只是在学习 keras,在这个特定的示例中,我并没有尝试使用迁移学习。只需在我的数据集上从新训练 inceptionv3 并进行分类。
  • @Enzio 299229 不同。我的意思是它们有点相似,但仍然不一样......
  • 这个答案是错误的include_top是改变输出类的数量,而不是图像形状。
  • 正如 sxeros 所说,仔细看,这不是同一个数字。 Include_top = False 意味着您将没有最后一个分类器,因此您需要创建自己的分类器。如果您只想对数据进行训练,最简单的方法是将数据重塑为 (299, 299, 3)
【解决方案2】:

预训练模型只能接受特定形状。您需要调整图片的大小。我建议你使用PIL

from PIL import Image
import numpy as np

X_train = Image.fromarray(X_train).resize((299, 299))
X_train = np.array(X_train)

这是一个如何进行的示例。

【讨论】:

  • 我更新了代码,显示了我调整图像大小的部分。我的图像大小调整为(299, 299, 3),如上所示。我不明白。
  • 如果您的图片真的是(299, 299, 3),那么您没有理由收到此错误消息。
  • 如果是这样的形状,则说明您没有正确调整它们的大小。在preprocess 函数的return 语句之前,写上assert np.array(image).shape == (299, 299, 3), 'Error, the picture shape is {}'.format(np.array(image).shape) 并确保它通过了断言测试
猜你喜欢
  • 2020-04-23
  • 2021-12-31
  • 2021-02-12
  • 2020-02-10
  • 2018-10-06
  • 1970-01-01
  • 2019-12-01
  • 2021-10-14
  • 1970-01-01
相关资源
最近更新 更多