TensorFlow Keras预测无标签数据时Generator结构不匹配问题排查
解决无标签数据预测的TypeError问题
问题根源
当用flow_from_directory(推测你提到的load_unlabeled_data基于该API实现)加载无标签数据并设置class_mode=None时,生成器会直接返回单个图像张量,但Keras的model.predict()期望输入结构为(图像张量,)的元组,两者结构不匹配导致报错。
具体修复方法
方法1:包装生成器修正输出结构
给原始生成器的输出套一层元组,确保返回格式符合模型预期:
# 假设原始无标签数据生成器定义如下 test_generator = datagen.flow_from_directory( 'to_test', target_size=(img_height, img_width), batch_size=32, class_mode=None, shuffle=False ) # 用生成器表达式包装,让输出格式变为(图像张量,) wrapped_generator = ((x,) for x in test_generator) # 使用包装后的生成器执行预测 predictions = model.predict(wrapped_generator, steps=test_generator.n // test_generator.batch_size)
方法2:直接加载图像为批量张量
跳过生成器,直接将无标签图像加载为模型可接受的批量张量:
import os from PIL import Image import numpy as np # 匹配训练时的图像尺寸 img_height, img_width = 224, 224 test_dir = 'to_test' # 加载所有无标签图像并预处理 images = [] # 假设无标签图像都在to_test下的唯一子目录中 sub_dir = os.listdir(test_dir)[0] for img_name in os.listdir(os.path.join(test_dir, sub_dir)): img_path = os.path.join(test_dir, sub_dir, img_name) img = Image.open(img_path).resize((img_width, img_height)) # 执行和训练时一致的预处理(比如归一化) img_array = np.array(img) / 255.0 images.append(img_array) # 转换为批量张量 x_test = np.array(images) # 执行预测 predictions = model.predict(x_test)
关键注意事项
- 无标签数据的预处理逻辑必须和训练阶段完全一致(包括尺寸、归一化方式、通道顺序等),否则会导致预测结果失真。
- 使用
flow_from_directory时,to_test目录下需要至少一级子目录(比如所有无标签图像放在to_test/unlabeled下),否则API无法正确识别图像文件。
内容的提问来源于stack exchange,提问作者actopozipc
相关产品推荐
相关产品推荐

