pandas训练集测试集划分_用pandas划分数据集实现训练集和测试集
用pandas劃分數據集實現訓練集和測試集,數據,情況下,子集,模塊,情況
用pandas劃分數據集實現訓練集和測試集
易采站長站,站長之家為您整理了用pandas劃分數據集實現訓練集和測試集的相關內容。
1、使用model_select子模塊中的train_test_split函數進行劃分
數據:使用kaggle上Titanic數據集
劃分方法:隨機劃分# 導入pandas模塊,sklearn中model_select模塊import pandas as pdfrom 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 npfrom sklearn.model_selection import KFoldx = 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 npfrom sklearn.model_selection import KFoldx = 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劃分數據集實現訓練集和測試集內容提出寶貴意見
總結
以上是生活随笔為你收集整理的pandas训练集测试集划分_用pandas划分数据集实现训练集和测试集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据库迁移工具-kettle下载
- 下一篇: Lammps:Python上Ovito模