训练集与测试集

Python 中的机器学习预处理

James Chapman

Curriculum Manager, DataCamp

为何要划分?

 

  1. 降低过拟合
  2. 在留出集上评估性能
Python 中的机器学习预处理

划分数据集

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
   X_train y_train            
0      1.0       n
1      4.0       n
       ...
5      5.0       n
6      6.0       n

   X_test y_test
0     9.0      y
1     1.0      n
2     4.0      n
Python 中的机器学习预处理

分层采样

 

  • 数据集共 $100$ 个样本:$80$ 个 类别 1,$20$ 个 类别 2
  • 训练集 $75$ 个样本:$60$ 个 类别 1,$15$ 个 类别 2
  • 测试集 $25$ 个样本:$20$ 个 类别 1,$5$ 个 类别 2
Python 中的机器学习预处理

分层采样

X_train,X_test,y_train,y_test = train_test_split(X, y, stratify=y, random_state=42)
y["labels"].value_counts()
class1    80
class2    20
Name: labels, dtype: int64
Python 中的机器学习预处理

分层采样

y_train["labels"].value_counts()
class1    60
class2    15
Name: labels, dtype: int64
y_test["labels"].value_counts()
class1    20
class2    5
Name: labels, dtype: int64
Python 中的机器学习预处理

开始练习吧!

Python 中的机器学习预处理

Preparing Video For Download...