我不明白为什么我必须调用fit()/fit_generator()函数两次,以便在Keras中微调InceptionV3 (或任何其他经过预先训练的模型)(2.0.0版)。文档建议如下:
在一组新的类上微调InceptionV3
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras import backend as K
# create the base pre-trained model
base_model = InceptionV3(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(1024, activation='relu')(x)
# and a logistic layer -- let's say we have 200 classes
predictions = Dense(200, activation='softmax')(x)
# this is the model we will train
model = Model(input=base_model.input, output=predictions)
# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional InceptionV3 layers
for layer in base_model.layers:
layer.trainable = False
# compile the model (should be done *after* setting layers to non-trainable)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
# train the model on the new data for a few epochs
model.fit_generator(...)
# at this point, the top layers are well trained and we can start fine-tuning
# convolutional layers from inception V3. We will freeze the bottom N layers
# and train the remaining top layers.
# let's visualize layer names and layer indices to see how many layers
# we should freeze:
for i, layer in enumerate(base_model.layers):
print(i, layer.name)
# we chose to train the top 2 inception blocks, i.e. we will freeze
# the first 172 layers and unfreeze the rest:
for layer in model.layers[:172]:
layer.trainable = False
for layer in model.layers[172:]:
layer.trainable = True
# we need to recompile the model for these modifications to take effect
# we use SGD with a low learning rate
from keras.optimizers import SGD
model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy')
# we train our model again (this time fine-tuning the top 2 inception blocks
# alongside the top Dense layers
model.fit_generator(...)为什么我们不打一次电话给fit()/fit_generator()?一如既往,谢谢你的帮助!
E D I T :
下面是纳西姆·本和大卫·德拉·伊格莱西亚的回答都很好。我强烈推荐David de la Iglesia:转移学习提供的链接。
发布于 2017-03-17 18:07:38
InceptionV3是一个非常深而复杂的网络,它已经被训练来识别某些东西,但是您正在使用它来完成另一个分类任务。这意味着当你使用它时,它并不完全适应你所做的事情。
因此,他们在这里想要达到的目标是,利用训练过的网络已经学到的一些特征,并修改一下网络的顶端(最高级的特性,最接近你的任务)。
因此,他们移除了最上层,增加了更多的,新的和未经训练的。他们想要为他们的任务训练那个大模型,使用172层第一层的特征提取,并学习最后一层来适应你的任务。
在他们想要训练的那一部分中,有一个有已经学到的参数,另一个有新的,随机初始化的参数。问题是,已经学到的层次,你只想微调它们,而不是从头开始重新学习它们.该模型无法区分应该只需要细化的层次和应该完全学习的层次。如果您只在172层模型上做了一次匹配,那么您将失去在庞大的imagnet数据集上学到的有趣特性。你不想那样,所以你要做的是:
总之,当你想把“已经学会”的层次和新的层次结合起来时,你会更新新的层次,然后对所有的内容进行微调。
发布于 2017-03-17 18:00:10
如果你在一个已经调好的convnet上附加2层随机初始化,并且你试图在不“热身”新层的情况下细化一些卷积层,那么这个新层的高梯度会炸掉那些卷积层学到的(有用的)东西。
这就是为什么您的第一个fit只训练这两个新的层,使用预先训练的convnet,就像某种“固定的”特征提取器。
在那之后,你的2个致密层没有高梯度,你可以细化一些预先训练的卷积层。这就是你在第二个fit上要做的事情。
https://stackoverflow.com/questions/42863092
复制相似问题