【问题标题】:image preprocessing is not working in vgg16图像预处理在 vgg16 中不起作用
【发布时间】:2019-09-12 06:33:25
【问题描述】:

我正在使用迁移学习 (vgg16) 学习图像分类,并且我正在使用 keras 的内置时尚 mnist 数据集。

(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

为了预处理 vgg16 的数据,我通过从 keras.applications.vgg16 导入 preprocess_input 使用以下命令

X_train = preprocess_input(x_train)
X_test = preprocess_input(x_test)

train_features = vgg16.predict(np.array(X_train), batch_size=256, verbose=1)
test_features = vgg16.predict(np.array(X_test), batch_size=256, verbose=1)

但我收到以下错误

ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (60000, 28, 28)

我用的是keras2.2.4,pip 19.0.3

【问题讨论】:

    标签: python-3.x keras vgg-net imagenet


    【解决方案1】:

    Fashion mnist 数据集包含灰度图像,这意味着它只有单通道深度,VGG16 使用 3 通道深度的 RGB 图像进行训练。根据您的错误,您不能将 VGG16 与单通道输入一起使用。要将 VGG16 用于时尚 mnist 数据集,您必须将图像读取为三个通道。您可以使用np.stack 进一步处理您的X_trainX_test,如下所示:

    import numpy as np
    X_train = np.stack((X_train,)*3, axis=-1)
    X_test = np.stack((X_test,)*3, axis=-1)
    

    【讨论】:

      【解决方案2】:

      VGG接受最小32,最大224,可以看here,要reshape这个,我们可以做

      x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) # converting it to (,28x28x1)
      x_train = np.pad(x_train, ((0,0),(2,2),(2,2),(0,0)), 'constant',constant_values=(0, 0)) # converting it to min (,32x32x1)
      x_train = np.stack((x_train,)*3, axis=-1) # (,32,32,1,3)
      x_train = x_train[:,:,:,0,:] # (,32,32,1)
      y_train = keras.utils.to_categorical(y_train, num_classes)
      

      这可以很容易地用于 keras 中的 .fit()、.evaluate() 和 .predict(),而无需将其转换为张量数据并编写生成器。

      【讨论】:

        猜你喜欢
        • 2020-10-03
        • 2022-06-10
        • 2021-06-27
        • 2020-10-28
        • 1970-01-01
        • 2020-08-04
        • 2013-03-18
        • 2013-12-24
        • 1970-01-01
        相关资源
        最近更新 更多