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

使用TensorFlow ImageDataGenerator构建CNN时遇tf.float32类型错误

解决TypeError: Cannot interpret 'tf.float32' as a data type问题

问题根源

在TensorFlow 2.10版本中,ImageDataGenerator的dtype参数无法直接识别tf.float32对象,该参数要求传入字符串格式的 dtype 标识或NumPy的dtype对象,而非TensorFlow的dtype对象。

解决方案

将datagen定义中的dtype=tf.float32替换为以下任一形式:

  • 使用字符串:dtype='float32'
  • 使用NumPy dtype:dtype=np.float32(需提前导入numpy)

修正后的完整代码示例

from keras.preprocessing.image import ImageDataGenerator
import numpy as np  # 若使用np.float32需导入

img_height, img_width = 224

datagen = ImageDataGenerator(
    rescale=1./255,
    data_format='channels_last',
    validation_split=0.1,
    dtype='float32',  # 改为字符串格式的dtype标识
)

train_generator = datagen.flow_from_directory(
    filepath,
    target_size=(img_height, img_width),
    batch_size=batch_size
)

nonsense = train_generator[0][0]
print(nonsense.dtype)  # 正常输出float32

额外说明

如果代码中混用了独立Keras库和TensorFlow内置的Keras,建议统一使用tf.keras.preprocessing.image.ImageDataGenerator,避免不同库之间的参数处理逻辑差异。

内容的提问来源于stack exchange,提问作者machine_learning_noob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:57:09