You need to enable JavaScript to run this app. AutoKeras图像分类运行异常:生成器报错、plt.show()输出空图
优惠活动
大模型
产品
解决方案
定价
更多

AutoKeras图像分类运行异常:生成器报错、plt.show()输出空图

报错根因与修正方案

初始化tf.data.Dataset时形状不匹配

  • 存在三处逻辑错误:
    1. 自定义迭代器my_iterator返回值完全错位:遍历生成器时拿到的图像批次img_batch没有被返回,反而错误将test_generator.batch_size(数值为16的标量)作为图像输入返回
    2. from_generator声明的输出形状存在笔误与维度错配:原代码写的(224, 244)将图像宽度错写为244,且完全遗漏批维度、图像通道维度,和真实生成器输出的张量形状不匹配
    3. 未传递实际生成器实例给自定义迭代函数,数据链路断裂
  • 修正写法:
    def my_iterator(generator):
        # 直接返回生成器输出的图像批次、标签批次
        for img_batch, targets_batch in generator:
            yield img_batch, targets_batch
    
    # 用output_signature匹配真实张量形状,兼容新版TensorFlow
    train_set = tf.data.Dataset.from_generator(
        lambda: my_iterator(train_generator),
        output_signature=(
            tf.TensorSpec(shape=(16, 224, 224, 3), dtype=tf.float32),
            tf.TensorSpec(shape=(16,), dtype=tf.float32)
        )
    )
    
    val_set = tf.data.Dataset.from_generator(
        lambda: my_iterator(validation_generator),
        output_signature=(
            tf.TensorSpec(shape=(16, 224, 224, 3), dtype=tf.float32),
            tf.TensorSpec(shape=(16,), dtype=tf.float32)
        )
    )
    

squeeze操作维度不匹配报错

  • 核心错误:输入图像是3通道RGB图,单张图像形状为(224, 224, 3),索引为2的轴维度大小是3,并非可压缩的1,强行指定axis=2压缩自然会触发报错。
  • 修正逻辑:取批次内的单张样本即可,3通道图像可直接被matplotlib识别,无需额外压缩维度。

plt渲染图像空白

  • 存在两处代码错误:
    1. 原代码调用image.numpy.shape()是错误写法,numpy数组的shape是类属性,不需要加括号执行,这行本身就会触发报错
    2. 图像已被rescale=1./255缩放到0-1的浮点范围,乘255后未转换为uint8类型,matplotlib对不符合取值规范的浮点图像会渲染为空白
  • 修正后的图像验证代码:
    for image_batch, label_batch in train_set.take(1):
        print("Image batch shape: ", image_batch.shape)
        print("Label batch shape: ", label_batch.shape)
        # 乘255后转uint8,符合matplotlib的图像输入规范
        sample_image = (image_batch[0].numpy() * 255).astype("uint8")
        plt.imshow(sample_image)
        plt.show()
    

AutoKeras适配优化

AutoKeras支持直接传入Keras ImageDataGenerator的实例,不需要手动转换为tf.data结构,可大幅降低自定义迭代器的出错概率,训练代码可直接简化为:

clf = ak.ImageClassifier(overwrite=True, max_trials=1, seed=5)
clf.fit(train_generator, epochs=20, validation_data=validation_generator)
print(clf.evaluate(validation_generator))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 19:54:04