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

Tensorflow执行model.fit时出现unhashable type: 'numpy.ndarray'错误如何解决

错误触发原因

这个错误的核心诱因是ImageDataGenerator初始化时传入了不兼容的dtype参数值:
Keras原生ImageDataGenerator的dtype参数预期接收NumPy类型对象(如numpy.float32),你传入的是TensorFlow专属的tf.float32类型,二者在数据迭代器内部逻辑中存在适配冲突,导致迭代器生成过程中误将NumPy数组作为哈希键使用,触发「不可哈希类型」报错。

修复方案

按照以下两步修改代码即可正常运行:

  • 把所有ImageDataGenerator初始化代码中的dtype = tf.float32参数删除,或者替换为dtype = numpy.float32:
# 修改后的数据集生成器示例
train_datagen = ImageDataGenerator(
      rescale = 1.0/255,
      rotation_range = 15,
      zoom_range = (0.95, 0.95),
      horizontal_flip = True,
      vertical_flip = True,
      data_format = "channels_last"
)

validation_datagen = ImageDataGenerator(rescale = 1.0/255)
test_datagen = ImageDataGenerator(rescale = 1.0/255)
  • 给TensorFlow Hub的预训练层显式指定输入形状,避免模型形状推断出错:
model = keras.Sequential([
      hub.KerasLayer("https://tfhub.dev/google/imagenet/nasnet_mobile/feature_vector/4",
                     trainable=True,
                     input_shape=(img_height, img_width, 3)),
      layers.Dense(1, activation="sigmoid"),
])

你代码中无意义的optimizers.RMSprop()调用可以直接删除,不会影响运行效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 19:45:03