You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 03:18:14