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

model.fit与model.predict报错:图像尺寸与识别异常问题

问题1:测试图像Resize后仍报输入形状不匹配

原因

PIL的resize()方法不会原地修改图像对象,而是返回一个新的调整尺寸后的图像。你当前代码中img.resize((150,150))没有将返回值赋值给img,导致后续处理的还是原始尺寸的图像,和模型要求的(150,150,3)形状不匹配。此外,测试图像未执行和训练数据一致的归一化操作(训练时用了rescale=1./255),数据分布不一致也会影响模型预测。

解决方向

  • 将resize结果重新赋值给img:img = img.resize((150,150))
  • 对测试图像执行归一化,和训练数据保持一致:img = img_to_array(img) / 255.0
问题2:训练中途因无法识别图像崩溃

原因

训练目录dog-vs-cat-classification/train中存在损坏的图像文件或非标准图像格式文件,导致ImageDataGenerator读取时无法识别,触发PIL.UnidentifiedImageError。

解决方向

  1. 批量检查并清理训练目录中的坏图:
    遍历训练目录下所有文件,用PIL尝试打开并验证完整性,无法识别的直接删除。示例代码:
    import os
    from PIL import Image
    
    train_dir = 'dog-vs-cat-classification/train'
    for root, dirs, files in os.walk(train_dir):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                with Image.open(file_path) as img:
                    img.verify()  # 验证图像完整性
            except (IOError, SyntaxError) as e:
                print(f"删除损坏文件: {file_path}")
                os.remove(file_path)
    
  2. 增强数据生成的鲁棒性:
    自定义数据生成逻辑,在读取图像时加入异常捕获,自动跳过损坏的图像。
修正后的完整代码示例
from keras.models import load_model, Sequential
from keras.layers import Conv2D, Flatten, Dense, MaxPooling2D, Dropout
from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array
from PIL import Image
import numpy as np
import os

trainRescale = ImageDataGenerator(rescale=1./255)
img_width = 150
img_height = 150

traindata = trainRescale.flow_from_directory(
    'dog-vs-cat-classification/train',
    target_size=(150,150),
    batch_size=32,
    class_mode='binary'
)

model=Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(img_width,img_height,3)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(64,(3,3),activation='relu'))         
model.add(MaxPooling2D(pool_size=(2,2)))                                                                                                         
model.add(Conv2D(64,(3,3),activation='relu')) 
model.add(MaxPooling2D(pool_size=(2,2))) 
model.add(Flatten())
model.add(Dense(64,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1,activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(traindata, steps_per_epoch=8, epochs=20) 

model.save_weights('model_weights.h5')
model.save('model_keras.h5')

testImage = os.listdir('dog-vs-cat-classification/test/')

for image in testImage:
    img_path = os.path.join('dog-vs-cat-classification/test/', image)
    img = Image.open(img_path)
    # 修正:接收resize后的新图像对象
    img = img.resize((150,150))
    img = img_to_array(img) / 255.0  # 添加归一化
    img = np.expand_dims(img, axis=0)

    result = model.predict(img, verbose=0)
    prediction = 'dog' if result[0][0] >=0.5 else 'cat'    
    print(f"image {image} is a: {prediction}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:03:12