首页 > 解决方案 > 无法执行 StratifiedKFold

问题描述

我想将我的样本分别划分为 80/20 的训练/测试集,然后我想执行 StratifiedKFold。

因此,让我们获取一些数据并使用 train_test_split 将它们分成 80/20

df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning- 
databases/breast-cancer-wisconsin/wdbc.data', header=None)
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split


X=df.drop(df.columns[[1]], axis=1)
y=np.array(df[1])
y[y=='M']=0
y[y=='B']=1
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2). 

现在,如果我想查看除法的结果,我会看到错误:

 kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=8)

for train, validation in kfold.split(X, y):
        print(X[train].shape, X[validation].shape)
ValueError: Supported target types are: ('binary', 'multiclass'). Got 'unknown' instead.

我已经阅读过它,这是与此功能相关的常见错误,但我不确定如何解决该问题。

我看到我们可以对 iris 数据执行此操作:

iris = load_iris()
X = iris.data
y = iris.target
print(X.shape) # initial dataset size
# (150, 4)

kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=8)

for train, validation in kfold.split(X, y):
            print(X[train].shape, X[validation].shape) 

我们会看到结果吗?我在做什么不同的是这个功能不想工作?

标签: pythonpandasnumpy

解决方案


您需要将您的重铸y为整数数组:

y = y.astype(int)

我不太确定它是如何工作的,但我猜因为它开始是一个字符串数组,并且被一个一个(第一个y=='M',稍后y=='B')转换为一个整数数组,它只是不会将数组本身转换为一个整数数组。


推荐阅读