Keras 2.1.5中“InputLayer无activity_regularizer属性”错误求助
解决Keras 2.1.5中
'InputLayer' object has no attribute 'activity_regularizer'错误 这个错误是Keras 2.x早期版本(比如你用的2.1.5)在合并模型时的常见兼容性问题——InputLayer本身并没有activity_regularizer属性,而你的合并操作意外尝试访问了这个不存在的属性,大概率是因为直接使用Sequential模型的output属性时,底层输入层的张量被错误暴露了。
问题根源
你当前用Sequential定义子模型,在某些场景下(比如模型结构简单、版本特性限制),直接调用fe.output或seq_model.output可能不会返回模型最后一层的输出,反而指向了初始的InputLayer张量,导致合并逻辑出错。
具体解决方案
推荐改用Keras函数式API来构建和合并模型,它在处理多模型组合的场景时比Sequential更灵活稳定,能从根源避免这类问题。下面是适配你的需求的代码示例:
1. 用函数式API重构特征提取器
from keras.layers import Input, Dense, Dropout, add from keras.models import Model # 定义特征提取器的输入张量 fe_input = Input(shape=(4096,)) # 堆叠你的层逻辑 x = Dense(256, activation='relu')(fe_input) x = Dropout(0.5)(x) # 继续添加你原本的其他层... fe_output = x # 标记特征提取器的最终输出 fe_model = Model(inputs=fe_input, outputs=fe_output)
2. 同样用函数式API定义序列模型(示例)
# 替换成你实际的序列模型输入形状 seq_input = Input(shape=(你的输入维度,)) y = Dense(256, activation='relu')(seq_input) # 添加你原本的序列模型层... seq_output = y seq_model = Model(inputs=seq_input, outputs=seq_output)
3. 合并输出并构建最终模型
# 合并两个子模型的输出 merged_out = add([fe_model.output, seq_model.output]) # 添加最终的分类层 final_output = Dense(256, activation='softmax')(merged_out) # 构建包含双输入的最终模型 final_model = Model(inputs=[fe_model.input, seq_model.input], outputs=final_output)
额外小技巧
如果你坚持要用Sequential模型,可以在合并前先触发一次模型构建(比如用一个空输入调用predict),确保output属性正确指向最后一层:
import numpy as np # 触发特征提取器构建 fe.predict(np.zeros((1, 4096))) # 触发序列模型构建 seq_model.predict(np.zeros((1, 你的输入维度))) # 再执行合并操作 Merged_out=add([fe.output,seq_model.output])
另外,建议升级Keras到2.2.x及以上版本,这些版本修复了大量早期的兼容性bug,能减少这类奇怪的报错。
内容的提问来源于stack exchange,提问作者عبدالله رمزي
相关产品推荐
相关产品推荐

