使用Adam优化器构建头盔/无头盔到骑手预测模型时遇ValueError
排查YOLO边界框预测模型的ValueError问题
以下是触发ValueError的常见原因及对应修复方案:
1. 训练数据为空数组
问题
代码仅会将标注文件中**第一个边界框为头盔/无头盔类别(class_id=0)**的数据加入训练集,若所有标注文件都不满足此条件,input_boxes或output_boxes会成为空数组,调用model.fit()时直接触发ValueError。
修复
遍历文件内所有边界框,收集所有class_id=0的头盔框,并匹配对应骑手框(需根据实际标注逻辑调整匹配规则):
# 替换原循环内的判断逻辑 for file_name in os.listdir(data_folder): if file_name.lower().endswith('.txt'): annotation_file_path = os.path.join(data_folder, file_name) all_bboxes = parse_annotation_file(annotation_file_path) # 遍历所有边界框,筛选头盔框并匹配对应骑手框 for bbox in all_bboxes: if bbox[0] == 0: # 示例:取同文件中第一个class_id=1的骑手框作为输出 rider_bbox = next((rb for rb in all_bboxes if rb[0] == 1), None) if rider_bbox is not None: input_boxes.append(bbox[1:]) output_boxes.append(rider_bbox[1:])
2. YOLO标注格式不匹配
问题
代码假设标注格式为[class_id, x_min, y_min, x_max, y_max],但原生YOLO标注格式是[class_id, x_center, y_center, width, height](坐标为图像宽高的归一化值),格式不匹配会导致数据维度或数值范围错误,触发ValueError。
修复
修改解析函数,将原生YOLO格式转换为代码预期的坐标格式(需传入对应图像的宽高):
def parse_annotation_file(annotation_file_path, img_width, img_height): with open(annotation_file_path, 'r') as file: lines = file.readlines() bounding_boxes = [] for line in lines: parts = list(map(float, line.strip().split())) class_id = parts[0] x_center, y_center, w, h = parts[1:] # 转换为绝对坐标的x_min, y_min, x_max, y_max x_min = (x_center - w/2) * img_width y_min = (y_center - h/2) * img_height x_max = (x_center + w/2) * img_width y_max = (y_center + h/2) * img_height bounding_boxes.append([class_id, x_min, y_min, x_max, y_max]) return np.array(bounding_boxes) # 调用示例:需同步读取对应图像获取尺寸 image_folder = '/content/drive/MyDrive/M_R_H_NH/images' for file_name in os.listdir(data_folder): if file_name.lower().endswith('.txt'): annotation_file_path = os.path.join(data_folder, file_name) img_path = os.path.join(image_folder, file_name.replace('.txt', '.jpg')) img = tf.keras.preprocessing.image.load_img(img_path) img_width, img_height = img.size all_bboxes = parse_annotation_file(annotation_file_path, img_width, img_height) # 后续数据收集逻辑同上
3. 批量大小大于样本数量
问题
若收集到的训练样本数小于设置的batch_size(比如仅25个样本,但batch_size=32),model.fit()会触发ValueError。
修复
训练前动态调整batch_size:
# 先检查样本数量 if len(input_boxes) == 0: raise ValueError("未收集到训练数据,请检查标注文件和类别ID设置") # 取样本数和32的最小值作为batch_size batch_size = min(32, len(input_boxes)) model.fit(input_boxes, output_boxes, epochs=epochs, batch_size=batch_size)
4. 边界框数据维度不一致
问题
若标注文件中存在字段数不等于5的无效行(比如漏写坐标),解析后生成的数组会包含不同长度的元素,转换为numpy数组时会出现维度错误,最终触发ValueError。
修复
解析时过滤无效行:
def parse_annotation_file(annotation_file_path): with open(annotation_file_path, 'r') as file: lines = file.readlines() bounding_boxes = [] for line in lines: parts = line.strip().split() # 仅保留字段数为5的有效行 if len(parts) == 5: try: bbox = list(map(float, parts)) bounding_boxes.append(bbox) except ValueError: # 跳过无法转换为浮点数的行 continue return np.array(bounding_boxes)
内容的提问来源于stack exchange,提问作者Chinmay
相关产品推荐
相关产品推荐

