python - 一次随机将 Pandas 数据框分成几组以进行 x 折交叉验证

标签 python pandas dataframe machine-learning

假设我有一个包含 500 行的数据框。我想执行 10 折交叉验证。因此,我需要将这些数据分成 10 组,每组包含 50 行。我也想同时随机将整个数据分成 10 组。

有没有办法使用 pandas、numpy 等任何库来做到这一点?

最佳答案

您可以使用 sklearn 的 KFold :

import numpy as np
import pandas as pd
from sklearn.model_selection import KFold 

# create dummy dataframe with 500 rows
features = np.random.randint(1, 100, 500)
labels = np.random.randint(1, 100, 500)
df = pd.DataFrame(data = {"X": features, "Y": labels})

kf = KFold(n_splits=10, random_state=42, shuffle=True) # Define the split - into 10 folds 
kf.get_n_splits(df) # returns the number of splitting iterations in the cross-validator
print(kf) 

for train_index, test_index in kf.split(df):
    print("TRAIN:", train_index) 
    print("TEST:", test_index)
    X_train, X_test = df.loc[train_index, "X"], df.loc[test_index, "X"]
    y_train, y_test = df.loc[train_index, "Y"], df.loc[test_index, "Y"]

示例 taken from here .

关于python - 一次随机将 Pandas 数据框分成几组以进行 x 折交叉验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52574923/

相关文章:

python - 尝试导入数据到MySQL时出现 "TypeError: not all arguments covered during string formatting"是什么原因?

python - 无法使用 astype() 转换 Timedelta 对象

python - 如何将多索引数据框列与简单数据框相匹配并相乘?

python - 使用 Pandas 和 Numpy 按 ID 索引查找比率的计算时间很长

python - 提取特定的文本行?

python - 在 pygame 中显示文本时遇到问题

python - 如何计算一个 df.column 的时间值是另一 df.column 的一部分?

pandas - 如何在 jupyter notebook 中并排渲染两个 pd.DataFrames?

python - 在2个pandas数据框之间匹配数据并在Python中提取另一列的匹配值

Python zipfile 通过 suds 发送错误 : "' ascii' codec can't decode byte 0x8c in position 10: ordinal not in range(128)"