python - 无法执行 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)
我们会看到结果吗?我在做什么不同的是这个功能不想工作?
解决方案
您需要将您的重铸y
为整数数组:
y = y.astype(int)
我不太确定它是如何工作的,但我猜因为它开始是一个字符串数组,并且被一个一个(第一个y=='M'
,稍后y=='B'
)转换为一个整数数组,它只是不会将数组本身转换为一个整数数组。
推荐阅读
- javascript - 如何在 vue js 中获取 ion-radio 值 - ionic
- reactjs - Expo typscript 项目中的 Express 服务器引发错误
- java - Java - 在 Linux 中获取列表网络接口
- excel - 将单元格与单元格比较,当同一列中的所有单元格相等时,删除整列
- reactjs - React Hooks:当 location.search 改变时让 useEffect 运行
- php - mysqli 对象已经关闭
- javascript - Google Apps 脚本:尝试使用 .getAs(MimeType.PLAIN_TEXT) 从 Google Drive 读取文本文件
- java - 休眠中的日期
- python - FreeCAD 是如何从 python 类中继承的?
- machine-learning - 特征选择:粗略或精细数据