Keras如何处理(?,?)输入形状?尽管input_shape小于最小值,但能够在Cifar10上训练Keras VGG16

时间:2018-03-15 04:14:42

标签: keras

我非常困惑Keras允许我训练我的模型:我能够加载预训练的vgg16模型,用GlobalAvgPool和Dense图层连接起来,最终为CIFAR10输出10个类。然后能够训练它(准确度很高)。

然而,当我在VGG16()中明确指定input_shape时,出现了ValueError,我意识到我的输入图像(批处理,32,32,3)不应该通过网络,因为有5个MaxPool具有2x2过滤器和步幅2的图层!

ValueError: Input size must be at least 48x48; got `input_shape=(32, 32, 3)`

那么,Keras如何处理前一种情况并仍允许进行培训?

我的代码:

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

batch_size = 32
num_classes = 10
epochs = 10

# Convert class vectors to binary class matrices.
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)


x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

from keras.applications.vgg16 import VGG16
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras.optimizers import Adam #rmsprop
from keras import backend as K
from keras.callbacks import ModelCheckpoint


def ourModel():
  '''
  returns a model up to the the Model(inputs=,outputs=) and freeze-layers step.
  Optimizer and compiler to be defined separately.
  '''
  # create the base pre-trained model
  base_model = VGG16(weights='imagenet', include_top=False)

  # add a global spatial average pooling layer
  x = base_model.output
  x = GlobalAveragePooling2D()(x)
  # let's add a fully-connected layer
  x = Dense(512, activation='relu')(x)
  # and a logistic layer -- let's say we have 'num_classes' of classes
  predictions = Dense(num_classes, activation='softmax')(x)

  # this is the model we will train
  model = Model(inputs=base_model.input, outputs=predictions)

  # first: train only the top layers (which were randomly initialized)
  # i.e. freeze all convolutional layers
  for layer in base_model.layers:
    layer.trainable = False

  return model

0 个答案:

没有答案