且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Keras中微调ResNet50?

更新时间:2023-12-02 20:42:58

很难找出具体的问题,您除了尝试复制代码而不进行任何更改外,还尝试了其他什么吗?

It is difficult to make out a specific question, have you tried anything more than just copying the code without any changes?

也就是说,代码中存在很多问题:这是来自keras.io的简单复制/粘贴,不起作用,并且需要在完全工作之前要进行一些调整(无论使用ResNet50还是InceptionV3 ):

That said, there is an abundance of problems in the code: It is a simple copy/paste from keras.io, not functional as it is, and needs some adaption before working at all (regardless of using ResNet50 or InceptionV3):

1):加载InceptionV3时需要定义input_shape,特别是将base_model = InceptionV3(weights='imagenet', include_top=False)替换为base_model = InceptionV3(weights='imagenet', include_top=False, input_shape=(299,299,3))

1): You need to define the input_shape when loading InceptionV3, specifically replace base_model = InceptionV3(weights='imagenet', include_top=False) with base_model = InceptionV3(weights='imagenet', include_top=False, input_shape=(299,299,3))

2):此外,您需要调整最后添加的层中的类数,例如如果您只有2个课程可以:predictions = Dense(2, activation='softmax')(x)

2): Further, you need to adapt the number of the classes in the last added layer, e.g. if you have only 2 classes to: predictions = Dense(2, activation='softmax')(x)

3):将模型编译时的损失函数从categorical_crossentropy更改为sparse_categorical_crossentropy

3): Change the loss-function when compiling your model from categorical_crossentropy to sparse_categorical_crossentropy

4):最重要的是,您需要在调用model.fit_generator()并添加steps_per_epoch之前定义fit_generator.如果您将训练图像放在 ./data/train 中,并且每个类别都位于不同的子文件夹中,则可以例如像这样:

4): Most importantly, you need to define the fit_generator before calling model.fit_generator() and add steps_per_epoch. If you have your training images in ./data/train with every category in a different subfolder, this can be done e.g. like this:

from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator()
train_generator = train_datagen.flow_from_directory(
     "./data/train",
    target_size=(299, 299),
    batch_size=50,
    class_mode='binary')
model.fit_generator(train_generator, steps_per_epoch=100)

这当然仅是基本训练,例如,您需要定义保存呼叫以保持训练后的体重.仅当您获得适用于上述更改的InceptionV3的代码时,我才建议继续为ResNet50实施此代码:首先,您可以将InceptionV3()替换为ResNet50()(当然,仅在from keras.applications.resnet50 import ResNet50之后),然后进行更改input_shape(224,224,3)target_size(224,244).

This of course only does basic training, you will for example need to define save calls to hold on to the trained weights. Only if you get the code working for InceptionV3 with the changes above I suggest to proceed to work on implementing this for ResNet50: As a start you can replace InceptionV3() with ResNet50() (of course only after from keras.applications.resnet50 import ResNet50), and change the input_shape to (224,224,3) and target_size to (224,244).

上述代码更改应在 Python 3.5.3/Keras 2.0/Tensorflow 后端上起作用.

The above mentioned code-changes should work on Python 3.5.3 / Keras 2.0 / Tensorflow backend.