TensorFlow项目报错:'str' object has no attribute 'base_dtype'求助
TensorFlow项目报错:'str' object has no attribute 'base_dtype'
问题详情
运行音频序列预测项目时,调用model.fit()触发如下错误:
AttributeError: 'str' object has no attribute 'base_dtype'
原始代码片段
print("train_x.shape", train_x.shape) print("train_y.shape", train_y.shape) print("Data type of train_x:", train_x.dtype) print("Data type of train_y:", train_y.dtype) print("Data type of train_y[0]:", train_y[0].dtype) model = keras.models.Sequential([ keras.Input(shape=(train_x.shape[1],), name="Input"), keras.layers.Dense(512, activation="linear", name="Entry"), keras.layers.Dense(train_y.shape[1], activation="linear", name="Output"), #keras.layers.Dense(train_y.shape[1], activation=None, name="Output"), ]) print(model.summary()) model.compile( loss='mean_squared_error', optimizer=keras.optimizers.Adam(learning_rate=0.0001), metrics=["accuracy"], ) print("Model input shape:", model.input_shape) model.fit(train_x, train_y, epochs=10, batch_size=32)
控制台输出
train_x.shape (22, 5000) train_y.shape (22, 5000) Data type of train_x: <dtype: 'float32'> Data type of train_y: <dtype: 'float32'> Data type of train_y[0]: <dtype: 'float32'> Model: "sequential_3" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓ ┃ Layer (type) ┃ Output Shape ┃ Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩ │ Entry (Dense) │ (None, 512) │ 2,560,512 │ ├────────────────────────────────────┼───────────────────────────────┼─────────────┤ │ Output (Dense) │ (None, 5000) │ 2,565,000 │ └────────────────────────────────────┴───────────────────────────────┴─────────────┘ Total params: 5,125,512 (19.55 MB) Trainable params: 5,125,512 (19.55 MB) Non-trainable params: 0 (0.00 B) None Model input shape: (None, 5000)
报错堆栈
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[11], line 1 ----> 1 model.fit(train_x, train_y, epochs=10, batch_size=32) File ~\anaconda3\envs\tf\lib\site-packages\keras\utils\traceback_utils.py:123, in filter_traceback.<locals>.error_handler(*args, **kwargs) 120 filtered_tb = _process_traceback_frames(e.__traceback__) 121 # To get the full stack trace, call: 122 # `keras.config.disable_traceback_filtering()` --> 123 raise e.with_traceback(filtered_tb) from None 124 finally: 125 del filtered_tb File ~\anaconda3\envs\tf\lib\site-packages\keras\backend\tensorflow\trainer.py:69, in TensorFlowTrainer.train_step(self, data) 67 if self.trainable_weights: 68 trainable_weights = self.trainable_weights --> 69 gradients = tape.gradient(loss, trainable_weights) 71 # Update weights 72 self.optimizer.apply_gradients(zip(gradients, trainable_weights)) AttributeError: 'str' object has no attribute 'base_dtype'
版本信息
- TensorFlow版本:2.10.1
- Keras版本:3.0.2
复现简化代码
import tensorflow as tf import keras print("Tensorflow version:", tf.__version__) print("Keras version:", keras.__version__) train_x = tf.constant([[1, 2, 3],[4, 5, 6]]) model = keras.models.Sequential([ keras.Input(shape=(train_x.shape[1],), name="Input"), keras.layers.Dense(512, activation="linear", name="Entry"), keras.layers.Dense(train_x.shape[1], activation="linear", name="Output"), ]) print(model.summary()) model.compile( loss=keras.losses.mean_squared_error, optimizer=keras.optimizers.Adam(learning_rate=0.0001), metrics=["accuracy"], ) print("Model input shape:", model.input_shape) model.fit(x=train_x, y=train_x, batch_size=2, epochs=10)
问题根源
这是TensorFlow 2.10.1与Keras 3.0.2版本不兼容导致的:
- Keras 3.x是独立于TensorFlow的全新版本,API和内部实现与旧版
tf.keras差异极大; - TensorFlow 2.10.x仅适配集成在其内部的
tf.keras(对应Keras 2.x版本),混用独立Keras 3.x会引发底层张量类型匹配错误,最终触发该报错。
解决方案
方案1:降级Keras到兼容版本
卸载当前Keras 3.x,安装适配TensorFlow 2.10的Keras 2.x版本:
pip uninstall keras -y pip install keras==2.10.0
之后代码改用tf.keras导入所有组件,避免混用独立Keras:
import tensorflow as tf train_x = tf.constant([[1, 2, 3],[4, 5, 6]], dtype=tf.float32) train_y = train_x # 替换为真实数据 model = tf.keras.models.Sequential([ tf.keras.Input(shape=(train_x.shape[1],), name="Input"), tf.keras.layers.Dense(512, activation="linear", name="Entry"), tf.keras.layers.Dense(train_y.shape[1], activation="linear", name="Output"), ]) model.compile( loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), metrics=[tf.keras.metrics.MeanAbsoluteError()], # 回归任务替换accuracy为回归指标 ) model.fit(train_x, train_y, epochs=10, batch_size=32)
方案2:升级TensorFlow到支持Keras 3.x的版本
TensorFlow 2.15及以上版本原生支持Keras 3.x,直接升级即可:
pip install tensorflow>=2.15.0
升级后无需修改原有代码,可继续使用独立keras导入。
额外优化建议
- 音频序列预测属于回归任务,使用
accuracy作为指标完全不合理,建议替换为mean_absolute_error或mean_squared_error; - 确保输入数据类型为
float32(与模型权重默认类型一致),避免不必要的类型转换开销。
内容的提问来源于stack exchange,提问作者Profs
相关产品推荐
相关产品推荐

