简体   繁体   English

如何使用预训练的 model 进行双输入迁移学习

[英]how to use pre-trained model for dual input transfer learning

I am going to use a pretrained model (which was previously saved using save_best_only argument of ModelCheckpoint ) for dual input transfer learning.我将使用预训练的 model(之前使用save_best_onlyModelCheckpoint参数保存)进行双输入迁移学习。 I have the following:我有以下内容:

pretrained_model = load_model('best_weight.h5')

def combined_net(): 
    
    u_model = pretrained_model
    u_output = u_model.layers[-1].output
    
    v_model = pretrained_model
    v_output = v_model.layers[-1].output


    concat = concatenate([u_output, v_output])
    #hidden1 = Dense(64, activation=activation)(concat) #was 128
    main_output = Dense(1, activation='sigmoid', name='main_output')(concat) # pretrained_model.get_layer("input_1").input

    model = Model(inputs=[u_model.input, v_model.input], outputs=main_output)
    opt = SGD(lr=0.001, nesterov=True)
    model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
    return model

And when I try to fit using:当我尝试使用时:

best_weights_file="weights_best_of_pretrained_dual.hdf5"
checkpoint = ModelCheckpoint(best_weights_file, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
callbacks = [checkpoint]

base_model = combined_net()
print(base_model.summary)

history = base_model.fit([x_train_u, x_train_v], y_train,
                         batch_size=batch_size,
                         epochs=epochs,
                         callbacks=callbacks, 
                         verbose=1,
                         validation_data=([x_test_u, x_test_v], y_test), 
                         shuffle=True)

I have the the following error:我有以下错误:

ValueError: The list of inputs passed to the model is redundant. All inputs should only appear once. Found: [<tf.Tensor 'input_1_5:0' shape=(None, None, None, 3) dtype=float32>, <tf.Tensor 'input_1_5:0' shape=(None, None, None, 3) dtype=float32>]

Apparently, model = Model(inputs=[u_model.input, v_model.input], outputs=main_output) line seems to cause an error.显然, model = Model(inputs=[u_model.input, v_model.input], outputs=main_output)行似乎会导致错误。

All I want to do is to use a pretrained model ("best_weight.h5") for dual input to single output model.我想要做的就是使用预训练的 model(“best_weight.h5”)双输入到单 output model。 Both inputs are the same as previously initialized and the concatenate layer should concatenate the layers before the last layer of each model constructed by loaded model.两个输入都与之前初始化的相同,并且concatenate层应该连接由加载的 model 构建的每个 model 的最后一层之前的层。

I have tried several ways I found online but was not able to properly set the model.我尝试了几种在网上找到的方法,但无法正确设置 model。

I hope one can help me我希望有人能帮助我

EDIT:编辑:

The pretrained model is shown below:预训练的 model 如下图所示:

def vgg_16():
    b_model = VGG16(weights='imagenet', include_top=False)
    x = b_model.output
    x = GlobalAveragePooling2D()(x)
    x = Dense(256, activation=activation)(x)
    predictions = Dense(1, activation='sigmoid')(x)
    model = Model(inputs=b_model.input, outputs=predictions)
    for layer in model.layers[:15]:  #
        layer.trainable = False
    opt = SGD(lr=init_lr, nesterov=True)
    model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
    return model

main_model = vgg_16()
history = main_model.fit(X_train, y_train, batch_size=batch_size, 
          epochs=EPOCHS, validation_data=(X_test, y_test), verbose=1, 
          callbacks=[es, mc, l_r])

here the correct way to do it.这里是正确的方法。 when I define the combined_net I define 2 new inputs which are used to feed the pre_trained model in the same way当我定义combined_net时,我定义了 2 个新输入,它们用于以相同的方式为预训练的pre_trained提供数据

def vgg_16():
    
    b_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False)
    x = b_model.output
    x = GlobalAveragePooling2D()(x)
    x = Dense(256, activation='relu')(x)
    predictions = Dense(1, activation='sigmoid')(x)
    model = Model(inputs=b_model.input, outputs=predictions)
    
    for layer in model.layers[:15]:
        layer.trainable = False
        
    opt = SGD(lr=0.003, nesterov=True)
    model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
    
    return model

main_model = vgg_16()
# main_model.fit(...)

pretrained_model = Model(main_model.input, main_model.layers[-2].output)

def combined_net(): 
    
    inp_u = Input((224,224,3)) # the same input dim of pretrained_model
    inp_v = Input((224,224,3)) # the same input dim of pretrained_model
    
    u_output = pretrained_model(inp_u)
    v_output = pretrained_model(inp_v)


    concat = concatenate([u_output, v_output])
    main_output = Dense(1, activation='sigmoid', name='main_output')(concat)

    model = Model(inputs=[inp_u, inp_v], outputs=main_output)
    opt = SGD(lr=0.001, nesterov=True)
    model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
    return model

base_model = combined_net()
base_model.summary()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用现有CNN模型中的预训练权重在Keras中进行迁移学习? - How can I use pre-trained weights from an existing CNN model for transfer learning in Keras? 在迁移学习预训练模型上训练新数据集 - Train new dataset on transfer learning pre-trained model 使用预先训练的ImageNet模型进行PyTorch传输学习 - PyTorch transfer learning with pre-trained ImageNet model 如何使用来自一个预先训练的MLP的最后一个隐藏层权重作为Keras的新MLP(转移学习)的输入? - How to use the last hidden layer weights from one pre-trained MLP as input to a new MLP (transfer learning) with Keras? 如何在TensorFlow中使用预训练模型 - How to use pre-trained model in TensorFlow 从预训练的 model 中移除顶层,迁移学习,tensorflow (load_model) - Remove top layer from pre-trained model, transfer learning, tensorflow (load_model) 无法使用 VGG16 预训练模型实现多类迁移学习 - Unable to implement the multi class transfer learning using VGG16 pre-trained model 如何正确使用预训练语言 model? - How to use a pre-trained language model correctly? 如何在具有不同图像尺寸的预训练ResNet50上进行转学习 - How to do transfer learning on a pre-trained ResNet50 with different image size 在迁移学习中使用预训练模型 - 我该怎么做? - Using pre-trained models in transfer learning - how do I do this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM