当前位置:首页 » 数据分析 » 正文

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

看: 1360次  时间:2020-08-25  分类 : 数据分析

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

数据:使用kaggle上Titanic数据集

划分方法:随机划分

# 导入pandas模块,sklearn中model_select模块
import pandas as pd
from sklearn.model_select 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, ramdon_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情况下数据的划分是有序的

到此这篇关于用pandas划分数据集实现训练集和测试集的文章就介绍到这了,更多相关pandas划分数据集 内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!

标签:pandas  numpy  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!