使用MultiLabelBinarizer遇'numpy.int32'不可迭代错误求解决方案
解决MultiLabelBinarizer报错
'numpy.int32' object is not iterable的问题 问题根源
你当前的标签数组是一维结构,每个元素是单个整数标签——相当于把所有样本的标签平铺成了一列。但MultiLabelBinarizer要求输入必须是每个样本对应一个可迭代的标签集合(比如列表、元组),比如[[0,2], [1], [3,4]]这种格式,每个子列表对应一个样本的所有标签。你现在传入的单个int32元素无法被迭代,因此触发报错。
解决方案:修正标签收集逻辑
核心是按**样本(每个XML文件)**分组收集标签,而不是把所有标签平铺。修改后的代码如下:
# Create a dictionary to map unique label names to label indices class_to_label = {label_name: label_index for label_index, label_name in enumerate(unique_label_names)} # Process each XML annotation file again and extract the labels labels = [] for filename in annotation_filenames: annotation_path = os.path.join(annotation_folder, filename) tree = ET.parse(annotation_path) root = tree.getroot() # 为当前样本创建专属标签列表 sample_labels = [] for obj in root.findall('object'): class_name = obj.find('name').text label = class_to_label[class_name] sample_labels.append(label) # 将当前样本的标签列表加入总集合 labels.append(sample_labels) # 用object类型保存,适配不同样本标签数量不一致的情况 labels = np.array(labels, dtype=object) np.save('labels.npy', labels)
之后的标签转换代码即可正常运行:
import numpy as np import os from sklearn.model_selection import train_test_split from sklearn.preprocessing import MultiLabelBinarizer from skmultilearn.problem_transform import BinaryRelevance from sklearn.svm import SVC # Load the features and labels features = np.load('features.npy') labels = np.load('labels.npy') # Transform the labels using MultiLabelBinarizer mlb = MultiLabelBinarizer() labels_bin = mlb.fit_transform(labels)
额外说明
- 保存标签时指定
dtype=object,是因为不同样本的标签数量可能不一致,普通numpy数组无法容纳长度不一的子列表; - 转换后的二进制标签矩阵,可以直接作为你代码中
BinaryRelevance等多标签模型的输入使用。
内容的提问来源于stack exchange,提问作者Arghya Bhattacharya
相关产品推荐
相关产品推荐

