加载预先训练的Keras模型,并与分支模型合并以创建多输入

加载预先训练的Keras模型,并与分支模型合并以创建多输入,keras,lstm,Keras,Lstm,我已经使用Keras功能API预先训练了一个序列模型 现在,我需要加载模型,移除顶部并将其与分支侧模型连接,然后训练新的完整模型 我对保留主模型的第一个预训练层感兴趣 我认为问题在于设置正确的输入和输出,以便模型正确连接和编译。我认为当前主模型的新输入层与主模型的其余部分之间存在脱节 预训练模型中的层数是动态的。这就是加载并更改模型的动机,而不是使用配置和权重在完整模型中重新配置预先训练的层。我还没有找到一种使用配置和权重对整个模型的配置进行硬编码的工作方式,这种配置和权重可以用于改变预训练层的

我已经使用Keras功能API预先训练了一个序列模型

现在,我需要加载模型,移除顶部并将其与分支侧模型连接,然后训练新的完整模型

我对保留主模型的第一个预训练层感兴趣

我认为问题在于设置正确的输入和输出,以便模型正确连接和编译。我认为当前主模型的新输入层与主模型的其余部分之间存在脱节

预训练模型中的层数是动态的。这就是加载并更改模型的动机,而不是使用配置和权重在完整模型中重新配置预先训练的层。我还没有找到一种使用配置和权重对整个模型的配置进行硬编码的工作方式,这种配置和权重可以用于改变预训练层的数量

更新:为了更清楚地说明问题所在,我需要设置一个连接图。错误消息是“ValueError:Graph disconnected:无法获取层“Pretrain\u input”处的张量张量值(“Pretrain\u input:0”,shape=(?,4,105),dtype=float32”)。访问以下以前的层时没有问题:[]'

##### MAIN MODEL #####

# loading pretrained model
main_model = load_model('models/main_model.h5')


# saving the output layer for reconstruction later
config_output_layer = main_model.layers[-1].get_config()
weights_output_layer = main_model.layers[-1].get_weights()


# removing the first and last layer (not sure if I need to remove the first layer, but I do this as I need an explicit 'entry point' for later concatenation with branching model later and re-compiling )
main_model.layers.pop(0)
main_model.layers.pop(-1)


# new first layer, for input later
main_input = Input(
    shape=(x_train_main.shape[1], x_train_main.shape[2]),
    name='Main_input')


# reconstructing last layer
main_output = Dense.from_config(config_last_layer)(main_model.output)


# re-defining the main model
new_main_model = Model(inputs=main_input, outputs=main_output)


 ##### BRANCHING MODEL #####   


branch_visible = Input(
    shape=(x_train_branch.shape[1], x_train_branch.shape[2]),
    name='Branch_input')


branch_hidden_0 = LSTM(
    units=units_lstm_layer,
    return_sequences=True,
    name='Branch_hidden_0'
)(branch_visible)


branch_dense = Dense(
    units=units_dense_layer,
    name='Branch_dense'
)(branch_hidden_0)


##### CONCAT THE MAIN AND THE BRANCH #####

concatenated_output = Concatenate(axis=-1)([main_output, branch_dense])


activation_layer = Dense(
    units=units_activation_layer,
    activation=activation,
    name='Activation'
)(concatenated_output)


final_model = Model(inputs=[main_visible, branch_visible], outputs=activation_layer)

您是否正在尝试修复特定问题?是的,当前图形已断开连接。我需要设置一个完整的连接图。
main\u output=densite。from\u config(config\u last\u layer)(main\u model.output)
仍然指向模型的旧输出。传递
main\u model.layers[-1]
或类似感谢,但返回
ValueError:Layer density\u main是用非符号张量的输入调用的。收到的类型:。完整输入:[]。该层的所有输入都应该是张量。
这似乎与您清除输入有关。试着把它留在那里。