不平衡学习的FunctionSampler引发ValueError

时间:2019-06-30 13:42:10

标签: python pandas scikit-learn imblearn

我想使用FunctionSampler中的类imblearn创建自己的自定义类以对数据集进行重采样。

我有一个一维要素系列,其中包含用于每个主题和一个标签系列,其中包含每个主题的标签。两者都来自pd.DataFrame。我知道我必须首先重塑特征数组,因为它是一维的。

当我使用类RandomUnderSampler时,一切正常,但是,如果我先将特征和标签都传递给fit_resample的{​​{1}}方法,然后创建一个FunctionSampler的实例,然后在此类上调用RandomUnderSampler时,出现以下错误:

  

ValueError:无法将字符串转换为float:'path_1'

这是产生错误的最小示例:

fit_resample

第一种方法(有效)

import pandas as pd
from imblearn.under_sampling import RandomUnderSampler
from imblearn import FunctionSampler

# create one dimensional feature and label arrays X and y
# X has to be converted to numpy array and then reshaped. 
X = pd.Series(['path_1','path_2','path_3'])
X = X.values.reshape(-1,1)
y = pd.Series([1,0,0])

第二种方法(无效)

rus = RandomUnderSampler()
X_res, y_res = rus.fit_resample(X,y)

有人知道这里出了什么问题吗?似乎def resample(X, y): return RandomUnderSampler().fit_resample(X, y) sampler = FunctionSampler(func=resample) X_res, y_res = sampler.fit_resample(X, y) 的{​​{1}}方法不等于fit_resample的{​​{1}}方法...

1 个答案:

答案 0 :(得分:1)

您对FunctionSampler的实现是正确的。问题出在您的数据集上。

RandomUnderSampler似乎也适用于文本数据。没有使用check_X_y进行检查。

但是FunctionSampler()有此检查,请参见here

from sklearn.utils import check_X_y

X = pd.Series(['path_1','path_2','path_2'])
X = X.values.reshape(-1,1)
y = pd.Series([1,0,0])

check_X_y(X, y)

这将引发错误

  

ValueError:无法将字符串转换为float:'path_1'

以下示例将起作用!

X = pd.Series(['1','2','2'])
X = X.values.reshape(-1,1)
y = pd.Series([1,0,0])

def resample(X, y):
    return RandomUnderSampler().fit_resample(X, y)

sampler = FunctionSampler(func=resample)
X_res, y_res = sampler.fit_resample(X, y)

X_res, y_res 
# (array([[2.],
#        [1.]]), array([0, 1], dtype=int64))