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

使用Keras预训练VGG16做图像二分类时遇shape属性错误求助

Keras图像二分类训练时AttributeError异常的问题分析与解决

嘿,我仔细看了你的代码和报错信息,这个问题其实很典型,咱们一步步来拆解:

问题根源

你的报错AttributeError: 'NoneType' object has no attribute 'shape',本质原因是训练和验证数据生成器没有返回标签数据。

看你代码里的这两行:

train_generator = train_datagen.flow_from_directory(train_data_dir, target_size=(224, 224), batch_size=batch_size, class_mode=None)
validation_generator = test_datagen.flow_from_directory(validation_data_dir, target_size=(224,224), batch_size=batch_size, class_mode=None)

你把class_mode设成了None,这会让flow_from_directory只返回图像数据,不返回对应的分类标签(也就是模型训练需要的y值)。而你的模型编译时指定了metrics=['accuracy'],训练过程中Keras需要用真实标签和预测值计算准确率,此时真实标签是None,自然就会触发'NoneType' object has no attribute 'shape'的错误。

解决方法

因为你做的是二分类任务,只需要把两个生成器的class_mode参数改成'binary'即可:

修改后的代码片段:

train_generator = train_datagen.flow_from_directory(
    train_data_dir, 
    target_size=(224, 224), 
    batch_size=batch_size, 
    class_mode='binary'  # 这里修改
)
validation_generator = test_datagen.flow_from_directory(
    validation_data_dir, 
    target_size=(224,224), 
    batch_size=batch_size, 
    class_mode='binary'  # 这里修改
)

class_mode='binary'会让生成器返回二元标签(0或1),刚好匹配你模型最后一层sigmoid激活的二分类输出,这样Keras就能正常计算损失和准确率了。

额外验证小提示

修改后你可以打印一下生成器的输出,确认是否返回了图像和标签:

x, y = next(train_generator)
print(x.shape, y.shape)

正常情况下会输出类似(16, 224, 224, 3) (16,)的结果,说明数据格式正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 13:47:33