Python 自定义迁移学习模型tensorflow Keras

Python 自定义迁移学习模型tensorflow Keras,python,tensorflow,keras,deep-learning,transfer-learning,Python,Tensorflow,Keras,Deep Learning,Transfer Learning,我试图在下面提到的迁移学习代码中添加conv层。但不知道如何进行。我想补充一点 conv、最大池、3x3过滤器和跨步3以及激活模式ReLU或 conv、max pooling、3x3 filter和stride 3以及激活模式LReLU下面提到的转移学习代码中的这一层。让我知道是否有可能,如果有,怎么做 CLASSES = 2 # setup model base_model = MobileNet(weights='imagenet', include_top=False) x =

我试图在下面提到的迁移学习代码中添加conv层。但不知道如何进行。我想补充一点
conv、最大池、3x3过滤器和跨步3以及激活模式ReLU
conv、max pooling、3x3 filter和stride 3以及激活模式LReLU
下面提到的转移学习代码中的这一层。让我知道是否有可能,如果有,怎么做

 CLASSES = 2
 
# setup model
base_model = MobileNet(weights='imagenet', include_top=False)
 
x = base_model.output
x = GlobalAveragePooling2D(name='avg_pool')(x)
x = Dropout(0.4)(x)
predictions = Dense(CLASSES, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions)
 
# transfer learning
for layer in base_model.layers:
 layer.trainable = False
 
model.compile(optimizer='rmsprop',
 loss='categorical_crossentropy',
 metrics=['accuracy'])
 
"""##Data augmentation"""
 
# data prep

"""
## Transfer learning
"""
 
from tensorflow.keras.callbacks import ModelCheckpoint
filepath="mobilenet/my_model.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]
 
EPOCHS = 1
BATCH_SIZE = 32
STEPS_PER_EPOCH = 5
VALIDATION_STEPS = 32
 
MODEL_FILE = 'mobilenet/filename.model'
 
history = model.fit_generator(
 train_generator,
 epochs=EPOCHS,
 steps_per_epoch=STEPS_PER_EPOCH,
 validation_data=validation_generator,
 validation_steps=VALIDATION_STEPS,
 callbacks=callbacks_list)
 
model.save(MODEL_FILE)
backup_model = model
model.summary()

您可以采用多种方法,其中之一是:

model = Sequential([
    base_model,
    GlobalAveragePooling2D(name='avg_pool'),
    Dropout(0.4),
    Conv(...), # the layers you would like to add for the base model
    MaxPool(...),
    ...
])

model.compile(...)

我想这就是你想要的

CLASSES=2
new_filters=256 # specify the number of filter you want in the added convolutional layer
img_shape=(224,224,3)
base_model=tf.keras.applications.mobilenet.MobileNet( include_top=False, input_shape=img_shape,  weights='imagenet',dropout=.4) 
x=base_model.output
x= Conv2D(new_filters, 3, padding='same', strides= (3,3), activation='relu', name='added')(x)
x= GlobalAveragePooling2D(name='avg_pool')(x)
x= Dropout(0.4)(x)
predictions= Dense(CLASSES, activation='softmax', name='output')(x)

model=Model(inputs=base_model.input, outputs=predictions)
model.summary()

这应该添加到下面提到的代码之前?``x=base_model.output x=globalaveragepoolg2d(name='avg_pool')(x)x=Dropout(0.4)(x)predictions=density(CLASSES,activation='softmax')(x)model=model(inputs=base_model.input,outputs=predictions)``否。我已经添加了原始答案,请看一看。我试过了,我能够生成模型,如果你能解释一下代码片段,那就太好了。