python划分数据集用pandas_用pandas划分数据集实现训练集和测试集
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划分数据集用pandas_用pandas划分数据集实现训练集和测试集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode two sum pyt
- 下一篇: 里加一列为1_一素一菩提 @ 素牛排薯泥