猿问

使用 Vgg16 输出和添加额外的自定义层时出错。

我正在尝试获取通过 Vgg16 网络传递的图像(训练和验证)的输出include_top = false,然后添加最后几层,如下面的代码所示。


我想x存储完整的模型,以便我可以从中创建一个 tflite 文件(包括 vgg 和我添加的图层)


from tensorflow.keras.models import Model

import os


x= vgg16.output

print(x.shape)

x = GlobalAveragePooling2D()(x)


x = Flatten()(x)

x = Dense(100)(x)

x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)

x = (Dropout(0.5)) (x)

x = (Dense(50)) (x) 

x = tf.keras.layers.LeakyReLU(alpha=0.3)(x)

x = Dropout(0.3)(x)

x = Dense(num_classes, activation='softmax')(x)



# this is the model we will train

model = Model(inputs=vgg16.input, outputs=x)


# first: train only the top layers (which were randomly initialized)

# i.e. freeze all convolutional InceptionV3 layers

for layer in vgg16.layers:

    layer.trainable = False


model.compile(loss='categorical_crossentropy',

   optimizer=optimizers.RMSprop(lr=1e-4),

   metrics=['acc'])


# train the model on the new data for a few epochs

history = model.fit(train_data, train_labels, 

   epochs=15,

   batch_size=batch_size,

   validation_data=(validation_data, validation_labels))


model.save(top_model_weights_path)

(eval_loss, eval_accuracy) = model.evaluate( 

    validation_data, validation_labels, batch_size=batch_size, verbose=1)

的输出x.shape是 (?, ?, ?, 512)


train_data.shape (1660, 2, 2, 512)


train_labels.shape (1660, 4)


validation_data.shape (137, 4)


validation_labels.shape (137, 2, 2, 512)


错误:


ValueError:检查输入时出错:预期 input_3 具有形状 (None, None, 3) 但得到形状为 (2, 2, 512) 的数组


此错误发生在以下行:


52 验证数据=(验证数据,验证标签))


如下所示的先前代码片段工作得非常好,并提供准确的输出。train_data存储一个 numpy 数组vgg16.predict_generator()


拉莫斯之舞
浏览 153回答 1
1回答

子衿沉夜

出色地...您定义了target_size=(img_width, img_height),如果(img_width, img_height)不是(224, 224),那么您还需要target_size在 VGG 模型中进行定义:vgg16 = applications.VGG16(  include_top=False,   weights='imagenet',  target_size=(img_width, img_height, 3))你为什么用class_mode=None在datagen.flow_from_directory?None是默认值。如果你想让它明确write class_mode='categorical',但 usingclass_mode=None根本没有意义。predict_generator返回预测。现在predict_generator已弃用,但您可以使用predict它与生成器一起工作。但predict应在训练后使用。正确使用生成器的方法是:datagen = ImageDataGenerator(rescale=1. / 255) generator = datagen.flow_from_directory(   train_data_dir,   target_size=(img_width, img_height),   batch_size=batch_size,   shuffle=False)// ...history = model.fit(  generator,  epochs=15,  steps_per_epoch=len(generator),   batch_size=batch_size,  validation_data=validation_generator,  validation_steps=len(validation_generator))稍后,如果您想进行预测,请使用:model.predict(test_generator)在这种情况下,您不需要使用Flattenafter 。将输出减少到一维数组。GlobalAveragePooling2DGlobalAveragePooling2D
随时随地看视频慕课网APP

相关分类

Python
我要回答