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

使用SMOGN平衡图像数据集时出现TypeError/UFuncTypeError如何解决?

解决SMOGN处理图像数据集时的两类报错问题

报错原因分析

1. TypeError: unhashable type: 'numpy.ndarray'

SMOGN是为表格型数值数据设计的工具,你的DataFrame中images列存储的是numpy数组(高维图像数据),这类不可哈希的类型无法被SMOGN的内部处理逻辑兼容,导致报错。

2. UFuncTypeError: ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U2'), dtype('<U2')) -> None

当你把标签存为字符串类型后,SMOGN需要对目标变量labels执行数值运算(如插值、距离计算),但字符串不支持减法这类数值操作,因此触发类型错误。

解决方法

核心思路是不让SMOGN直接处理高维图像数组,只给它传入可处理的标签和索引数据,平衡后再通过索引提取对应图像:

修正后的代码

import os
import cv2 as cv
import numpy as np
import pandas as pd
import smogn

# 读取原始数据,记录索引、图像和标签
r_labels = []
im = []
sample_indices = []

for idx, filename in enumerate(os.listdir(folder)):
    img = cv.imread(os.path.join(folder, filename))
    if img is not None:
        aio_plant = filename.split("_")
        flowering_time = aio_plant[2].split(".")[0]
        # 标签转为整数类型,确保支持数值运算
        r_labels.append(int(flowering_time))
        im.append(np.asarray(img).astype(np.float32))
        sample_indices.append(idx)

# 创建仅包含索引和标签的DataFrame,供SMOGN处理
label_df = pd.DataFrame({'index': sample_indices, 'labels': r_labels})  

# 运行SMOGN smoter,针对标签做数据平衡
balanced_label_df = smogn.smoter(
    data=label_df,
    y='labels'
)

# 根据平衡后的索引提取对应图像和标签
balanced_indices = balanced_label_df['index'].values
balanced_images = [im[i] for i in balanced_indices]
balanced_labels = [r_labels[i] for i in balanced_indices]

# 可选:将平衡后的数据转回DataFrame
balanced_df = pd.DataFrame({'images': balanced_images, 'labels': balanced_labels})

关键说明

  • 标签类型修正:将标签转为int类型,确保SMOGN能对目标变量执行必要的数值计算。
  • 分离图像与标签处理:只给SMOGN传入索引和标签的表格数据,避开不可哈希的图像数组,解决第一个报错。
  • 索引映射提取数据:利用SMOGN返回的平衡后索引,从原始图像和标签列表中提取对应数据,最终得到平衡的图像数据集。

内容的提问来源于stack exchange,提问作者Рим

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 12:30:28