用pandas划分数据集——训练集和测试集

1、使用model_select子模块中的train_test_split函数进行划分

数据:使用kaggle上Titanic数据集

划分方法:随机划分

# 导入pandas模块,sklearn中model_select模块
import pandas as pd
from sklearn.model_selection import train_test_split
# 读取数据
data = pd.read_csv('.../titanic_dataset/train.csv')
# 将特征划分到 X 中,标签划分到 Y 中
x = data.iloc[:, 2:]
y = data.loc['Survived']
# 使用train_test_split函数划分数据集(训练集占75%,测试集占25%)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, randon_state=0)

缺点:1、数据浪费严重,只对部分数据进行了验证

            2、容易过拟合

2、k折交叉验证(kfold)

原理:将数据集划分成n个不相交的子集,每次选择其中一个作为测试集,剩余n-1个子集作为            训练集,共生成 n 组数据

使用方法:sklearn.model_select.KFold(n_splits=5,shuffle=False,random_state=0)

参数说明:n_splits:数据集划分的份数,

                  shuffle:每次划分前是否重新洗牌 ,False表示划分前不洗牌,每次划分结果一样,True表示划分前洗牌,每次划分结果                                  不同

                 random_state:随机种子数

(1)shuffle=False 情况下数据划分情况

# 不洗牌模式下数据划分情况
import numpy as np
from sklearn.model_selection import KFold
x = np.arange(46).reshape(23,2)
kf = KFold(n_splits=5,shuffle=False)
for train_index, test_index in kf.split(x):
    print(train_index,test_index)
[ 5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22] [0 1 2 3 4]
[ 0  1  2  3  4 10 11 12 13 14 15 16 17 18 19 20 21 22] [5 6 7 8 9]
[ 0  1  2  3  4  5  6  7  8  9 15 16 17 18 19 20 21 22] [10 11 12 13 14]
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 19 20 21 22] [15 16 17 18]
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18] [19 20 21 22]

(2)shuffle=True 情况下数据划分情况

import numpy as np
from sklearn.model_selection import KFold
x = np.arange(46).reshape(23,2)
kf = KFold(n_splits=5,shuffle=True)
for train_index, test_index in kf.split(x):
    print(train_index,test_index)
[ 0  3  4  5  6  7  8  9 10 11 12 14 15 16 17 19 20 21] [ 1  2 13 18 22]
[ 0  1  2  3  5  6  7 10 11 13 15 16 17 18 19 20 21 22] [ 4  8  9 12 14]
[ 0  1  2  3  4  7  8  9 10 12 13 14 15 16 17 18 19 22] [ 5  6 11 20 21]
[ 1  2  3  4  5  6  8  9 10 11 12 13 14 15 18 19 20 21 22] [ 0  7 16 17]
[ 0  1  2  4  5  6  7  8  9 11 12 13 14 16 17 18 20 21 22] [ 3 10 15 19]

总结:从数据中可以看出shuffle=True情况下数据的划分是打乱的,而shuffle=False情况下数据的划分是有序的

  • 24
    点赞
  • 87
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值