ValueError: You are trying to load a weight file containing 12 layers into a model with 2 layers.

本文解决两个问题:

1、ValueError: You are trying to load a weight file containing 12 layers into a model with 2 layers.

2、The name "embedding_1_input" is used 3 times in the model 



第一个问题:

相当麻烦的一个问题,百度和google都没有

而且似乎有时候不能重现,有时候又莫名其妙消失了。

结果实验,不要使用下面的语句,原因是,这种语句不能针对使用Merge类建立的嵌套型神经网络,


这种报错在何种情况下会发生呢?

假定

model_left、model_right和model_3是三个神经网络

然后用以下代码让这三个子神经网络组合
merged = Merge([model_left, model_right,model_3], mode='concat') #merge
model = Sequential()
model.add(merged) # add merge

然后输入

model.save('./model/my_model_weights.h5')
model=load_model('./model/my_model_weights.h5')

就会报错

ValueError: You are trying to load a weight file containing 12 layers into a model with 2 layers.

因为这个神经网络是嵌套的,也算是这个python库的一个bug吧。

改用以下代码即可。

model.save_weights('test.h5')
model.load_weights('test.h5',by_name=True)
json_string = model.to_json()
model = model_from_json(json_string)


第二个问题:

但是,由于该神经网络存在嵌套

即使改为以上代码后,想要在加载模型后。使用plot_model绘制神经网络,也同样是不可能的,会有如下报错:

The name "embedding_1_input" is used 3 times in the model

具体报错:

RuntimeError: (u'The name "embedding_1_input" is used 3 times in the model. All layer names should be unique. Layer names: ',
[
  u'embedding_1_input',
  u'embedding_1_input',
  u'embedding_1_input',
  u'embedding_1',
  u'embedding_1',
  u'embedding_1',
  u'conv1d_1',
  u'conv1d_4',
  u'conv1d_7',
  u'max_pooling1d_1',
  u'max_pooling1d_4',
  u'max_pooling1d_7',
  u'conv1d_2',
  u'conv1d_5',
  u'conv1d_8',
  u'max_pooling1d_2',
  u'max_pooling1d_5',
  u'max_pooling1d_8',
  u'conv1d_3',
  u'conv1d_6',
  u'conv1d_9',
  u'max_pooling1d_3',
  u'max_pooling1d_6',
  u'max_pooling1d_9',
  u'flatten_1',
  u'flatten_2',
  u'flatten_3',
  u'merge_1',
  u'dense_1',
  u'dense_2'
])

所以对于这种嵌套型神经网络,想要绘制神经网络的结构图,在进行训练模型后就要立刻使用 

plot_model(model, to_file='model.png')
不要在保存模型、加载模型后再去使用上面这句代码,是会报错有layer重名的。

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值