分层拆分pandas数据框到训练、验证和测试集

以下是一个极度简化的DataFrame,代表包含医疗诊断的更大DataFrame:

medicalData = pd.DataFrame({'diagnosis':['positive','positive','negative','negative','positive','negative','negative','negative','negative','negative']})medicalData    diagnosis0   positive1   positive2   negative3   negative4   positive5   negative6   negative7   negative8   negative9   negative

问题:为了机器学习,我需要随机将这个数据框拆分为三个子数据框,如下方式:

trainingDF, validationDF, testDF = SplitData(medicalData,fractions = [0.6,0.2,0.2])

…其中拆分数组指定了完整数据中分配到每个子数据框的比例。

  • 子数据框中的数据需要是互斥的,并且拆分数组(比例)需要总和为1。
  • 此外,每个子集中的阳性诊断比例需要大致相同。
  • 这个问题的答案建议使用pandas的sample方法sklearn的train_test_split函数。但这些解决方案似乎都不能很好地泛化到n次拆分,且没有提供分层拆分的方案。

回答:

np.array_split

如果你想要泛化到n次拆分,np.array_split是你最好的朋友(它与DataFrame兼容得很好)。

fractions = np.array([0.6, 0.2, 0.2])# 打乱你的输入df = df.sample(frac=1) # 分成3部分train, val, test = np.array_split(    df, (fractions[:-1].cumsum() * len(df)).astype(int))

train_test_split

使用train_test_split进行分层拆分的复杂解决方案。

y = df.pop('diagnosis').to_frame()X = df

X_train, X_test, y_train, y_test = train_test_split(        X, y,stratify=y, test_size=0.4)X_test, X_val, y_test, y_val = train_test_split(        X_test, y_test, stratify=y_test, test_size=0.5)

其中X是你特征的DataFrame,y是你标签的单列DataFrame。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注