如何微调 ResNet50 Keras 以仅将图像分类为 2 个类别(猫与狗)而不是所有 1000 个 imagenet 类别?我使用 Python 并且能够使用 ResNet50 和 keras 对 1000 个 ImageNet 类的随机图像进行分类。现在我想微调我的代码,使它只使用 Kaggle 图像而不是 ImageNet 对猫和狗进行分类。我该怎么做呢?
问问题
482 次
2 回答
0
有几种应用迁移学习的方法,最有效的方法是反复试验。但是,ImageNet 在其 1000 个类别中包含多种类型的猫和狗,这就是我要执行以下操作的原因:
- 使用 2 个输出向模型添加单个 Dense 层
- 仅将最后一层设置为可训练
- 仅使用猫和狗的图像重新训练网络
这将很快获得可靠的结果,因为您只训练了一层。这意味着,您不必通过整个网络进行反向传播。此外,您的模型只需学习从原始猫和狗子类到此二进制输出的相当线性的映射。
于 2017-12-08T08:10:51.433 回答
0
from tensorflow.keras.applications.resnet_v2 import ResNet50V2
import tensorflow.keras.layers as L
from tensorflow.keras.models import Model, load_model
def make_model():
base_model = ResNet50V2(weights='imagenet', include_top=False, input_shape=(512, 512, 3))
for layer in base_model.layers:
layer.trainable = False
xc1 = L.Conv2D(64, (3,3), padding="same")(base_model.output)
xc2 = L.BatchNormalization()(xc1)
xc3 = L.ReLU()(xc2)
xmp1 = L.AveragePooling2D(pool_size=(2, 2), strides=(2, 2))(xc3)
xf1 = L.Flatten()(xmp1)
xd1 = L.Dense(512, activation='relu')(xf1)
xd2 = L.Dense(128, activation='relu')(x3)
xd3 = L.Dense(256, activation='relu')(x5)
xd4 = L.Dense(32, activation='relu')(x7)
output = L.Dense(1, activation='sigmoid')(xd4)
model = Model(base_model.input, output)
return model
model = make_model()
model.summary()
您可以从 ResNet 进行迁移学习,从卷积层传输经过训练的权重,并相应地微调全连接层(用于二进制分类)。'include_top=False' 参数可以帮助您做到这一点。
在函数内部,这段代码冻结了初始权重
for layer in base_model.layers:
layer.trainable = False
于 2022-01-31T16:12:52.967 回答