使用Keras Core+TensorFlow出现AttributeError报错求助
问题排查与解决方案
错误原因
在TensorFlow后端环境下,keras.ops.convert_to_tensor接收字符串格式的"int8"作为dtype参数时,内部未正确将其转换为TensorFlow的dtype对象,导致后续流程中尝试访问字符串对象的base_dtype属性,触发AttributeError。PyTorch后端对字符串格式dtype的兼容性更好,因此未出现该问题。
修复方案
方案1:使用TensorFlow原生dtype常量替换字符串
将代码中转换张量的部分修改为使用TensorFlow的dtype常量:
X = keras.ops.convert_to_tensor(X, dtype=tf.int8) y = keras.ops.convert_to_tensor(y, dtype=tf.int8)
方案2:使用Keras Core内置dtype标识
也可以直接使用Keras Core提供的dtype枚举(适配0.1.7版本):
X = keras.ops.convert_to_tensor(X, dtype=keras.int8) y = keras.ops.convert_to_tensor(y, dtype=keras.int8)
额外优化方案
如果仍有问题,可尝试将输入数据直接转换为浮点型(匹配Dense层默认的权重dtype),二进制分类任务中使用浮点型输入完全可行,且无需额外张量转换:
X = np.random.randint(0, 2, size=(2*batch_size, d_input)).astype("float32") y = np.random.randint(0, 2, size=(2*batch_size, d_output)).astype("float32") model.fit(X, y, batch_size=batch_size)
内容的提问来源于stack exchange,提问作者FraSchelle
相关产品推荐
相关产品推荐

