如何在我们自己的模型上进行转移学习? [英] How to do transfer-learning on our own models?

查看:57
本文介绍了如何在我们自己的模型上进行转移学习?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在CNN模型上应用转移学习,但出现以下错误.

I am trying to apply the transfer-learning on my CNN model, I am getting the below error.

model = model1(weights = "model1_weights", include_top=False)

-

TypeError: __call__() takes exactly 2 arguments (1 given)

谢谢

推荐答案

如果您尝试通过自定义模型使用转移学习,答案取决于保存模型体系结构(描述)和权重的方式.

If you are trying to use transfer-learning using custom model, the answer depends on the way you saved your model architecture(description) and weights.

您可以使用keras的load_model方法轻松加载模型.

You can easily load model, using keras's load_model method.

from keras.models import load_model
model = load_model("model_path.h5")

2.如果您将模型的描述和权重保存在单独的文件中(例如分别保存在json和.h5文件中).

您可以先从json文件加载模型说明,然后加载模型权重.

2. If you saved the description and weights of the model on separate file (e.g in json and .h5 files respectively).

You can first load the model description from json file and then load model weights.

form keras.models import model_from_json
with open("path_to_json_file.json") as json_file:
    model = model_from_json(json_file.read())
    model.load_weights("path_to_weights_file.h5")

在加载旧模型之后,您现在可以决定要丢弃的层(通常这些层是顶部完全连接的层)以及要冻结的层.假设您要使用模型的前五层而无需再次训练,接下来的三层需要再次训练,最后一层将被丢弃(此处假设网络层数大于八),并且在最后一层之后添加三个完全连接的层.可以按照以下步骤进行.

After the old model is loaded you can now decide which layers to discard(usually these layers are top fully connected layers) and which layers to freeze. Let's assume you want to use the first five layers of the model without training again, the next three to be trained again, the last layers to be discarded(here it is assumed that the number of the network layers is greater than eight), and add three fully connected layer after the last layer. This can be done as follows.

for i in range(5):
    model.layers[i].trainable = False

使接下来的三层可训练,如果所有层都可训练,则可以忽略这一点.

适用于范围(5,8)中的i的

Make the next three layers trainable, this can be ignored if all layers are trainable.

for i in range(5,8):
    model.layers[i].trainable = True

再添加三层

ll = model.layers[8].output
ll = Dense(32)(ll)
ll = Dense(64)(ll)
ll = Dense(num_classes,activation="softmax")(ll)

new_model = Model(inputs=model.input,outputs=ll)

这篇关于如何在我们自己的模型上进行转移学习?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆