调用layers.Dense时触发AttributeError:'tuple'对象无'rank'属性
AttributeError: 'tuple' object has no attribute 'rank'错误 问题场景
执行代码行dense = layers.Dense(4, activation=act_func)(inputs)时触发错误:AttributeError: ‘tuple’ object has no attribute ‘rank’,对应的模型定义函数如下:
def gen_model(act_func = 'relu'): inputs = keras.Input(shape=(4,)) dense = layers.Dense(4, activation=act_func)(inputs) dense = layers.Dense(4, activation=act_func)(dense) outputs = layers.Dense(1)(dense) model = keras.Model(inputs=inputs, outputs=outputs, name="NN_heat_controller") return model
打印inputs得到:<KerasTensor shape=(None, 4), dtype=float32, sparse=None, name=keras_tensor_1>,看起来符合Dense层对符号张量的要求。
可能原因及解决方案
导入方式不统一
混用独立Keras和TensorFlow内置Keras(比如同时import keras和from tensorflow.keras import layers)会导致张量类型不兼容,触发该错误。
解决:统一使用TensorFlow的Keras组件,导入代码改为:from tensorflow import keras from tensorflow.keras import layers激活函数参数错误
调用gen_model时如果传入的act_func是元组(比如误传act_func=('relu',)),会导致Dense层处理时出现类型错误。
解决:确保传入的act_func是字符串(如'relu')或者Keras激活函数对象(如keras.activations.relu)。张量被意外包装为元组
极少数情况下,keras.Input的输出可能被其他代码逻辑包装成元组(比如多输入场景的误处理)。
解决:如果inputs是元组,显式提取张量,用inputs = inputs[0]获取其中的张量后再传入Dense层。
内容的提问来源于stack exchange,提问作者Muhammad Abdullah

