机器学习实战:这里没有艰深晦涩的数学理论,我们将用简单的案例和大量的示例代码,向大家介绍机器学习的核心概念。我们的目标是教会大家用Python构建机器学习模型,解决现实世界的难题。
1. 训练集和检验集
在应用机器学习算法前,一般将数据集划分为训练集(training set)和检验集(test set),训练集用于拟合模型,检验集用于评估预测能力。
机器学习模型往往包含很多参数,如果不使用检验集而是直接评估样本内的预测精度,会受到过度拟合的影响。所谓过度拟合,就是模型找到了本来不存在的规律,利用检验集来校验模型能规避这一点。
sklearn实现:train_test_split(X, y, test_size, random_state)
- X: 特征矩阵
- y: 目标向量
- test_size: 检验集大小(比例),通常选择0.3,0.25,0.2等
- random_state: Numpy RandomState对象或代表随机数种子的整数,由于划分是随机的,为了重复实验过程,应该使用统一的随机数种子。
使用IRIS数据集。
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
X, y = iris.data, iris.target
iris_df = pd.DataFrame(X, columns=iris["feature_names"])
iris_df["target"] = y
iris_df.head()
sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | target | |
---|---|---|---|---|---|
0 | 5.1 | 3.5 | 1.4 | 0.2 | 0 |
1 | 4.9 | 3.0 | 1.4 | 0.2 | 0 |
2 | 4.7 | 3.2 | 1.3 | 0.2 | 0 |
3 | 4.6 | 3.1 | 1.5 | 0.2 | 0 |
4 | 5.0 | 3.6 | 1.4 | 0.2 | 0 |
# 先设置随机数种子,目标是复现试验结果
rs = 123
# 调用train_test_split,随机划分训练集和检验集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=rs)
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
# 创建模型,这里使用KNN作为说明
model = KNeighborsClassifier(n_neighbors=5)
# 训练集
model.fit(X_train, y_train)
# 评估训练集和检验集的预测精度
score_in_sample = model.score(X_train, y_train)
score_out