Chapter 13
第三章 模型搭建和评估
NotebookPython 379 cells
第三章 模型搭建和评估
经过前面的探索性数据分析我们可以很清楚的了解到数据集的情况
In [1]python · cell 3
python
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from IPython.display import ImageIn [2]python · cell 4
python
%matplotlib inlineIn [3]python · cell 5
python
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.rcParams['figure.figsize'] = (10, 6) # 设置输出图片大小In [4]python · cell 6
python
# 读取训练数集
train = pd.read_csv('train.csv')
train.shapeOutput
(891, 12)
In [5]python · cell 7
python
train.head()Output
PassengerId Survived Pclass \
0 1 0 3
1 2 1 1
2 3 1 3
3 4 1 1
4 5 0 3
Name Sex Age SibSp \
0 Braund, Mr. Owen Harris male 22.0 1
1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1
2 Heikkinen, Miss. Laina female 26.0 0
3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1
4 Allen, Mr. William Henry male 35.0 0
Parch Ticket Fare Cabin Embarked
0 0 A/5 21171 7.2500 NaN S
1 0 PC 17599 71.2833 C85 C
2 0 STON/O2. 3101282 7.9250 NaN S
3 0 113803 53.1000 C123 S
4 0 373450 8.0500 NaN S
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
| 1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
| 2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
| 3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S |
| 4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S |
特征工程
任务一:缺失值填充
- 对分类变量缺失值:填充某个缺失值字符(NA)、用最多类别的进行填充
- 对连续变量缺失值:填充均值、中位数、众数
In [6]python · cell 10
python
# 对分类变量进行填充
train['Cabin'] = train['Cabin'].fillna('NA')
train['Embarked'] = train['Embarked'].fillna('S')In [7]python · cell 11
python
# 对连续变量进行填充
train['Age'] = train['Age'].fillna(train['Age'].mean())In [8]python · cell 12
python
# 检查缺失值比例
train.isnull().sum().sort_values(ascending=False)Output
Embarked 0 Cabin 0 Fare 0 Ticket 0 Parch 0 SibSp 0 Age 0 Sex 0 Name 0 Pclass 0 Survived 0 PassengerId 0 dtype: int64
In [ ]python · cell 13
python
任务三:编码分类变量
In [182]python · cell 15
python
# 取出所有的输入特征
data = train[['Pclass','Sex','Age','SibSp','Parch','Fare', 'Embarked']]In [183]python · cell 16
python
# 进行虚拟变量转换
data = pd.get_dummies(data)In [184]python · cell 17
python
data.head()Output
Pclass Age SibSp Parch Fare Sex_female Sex_male Embarked_C \ 0 3 22.0 1 0 7.2500 0 1 0 1 1 38.0 1 0 71.2833 1 0 1 2 3 26.0 0 0 7.9250 1 0 0 3 1 35.0 1 0 53.1000 1 0 0 4 3 35.0 0 0 8.0500 0 1 0 Embarked_Q Embarked_S 0 0 1 1 0 0 2 0 1 3 0 1 4 0 1
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
| Pclass | Age | SibSp | Parch | Fare | Sex_female | Sex_male | Embarked_C | Embarked_Q | Embarked_S | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 3 | 22.0 | 1 | 0 | 7.2500 | 0 | 1 | 0 | 0 | 1 |
| 1 | 1 | 38.0 | 1 | 0 | 71.2833 | 1 | 0 | 1 | 0 | 0 |
| 2 | 3 | 26.0 | 0 | 0 | 7.9250 | 1 | 0 | 0 | 0 | 1 |
| 3 | 1 | 35.0 | 1 | 0 | 53.1000 | 1 | 0 | 0 | 0 | 1 |
| 4 | 3 | 35.0 | 0 | 0 | 8.0500 | 0 | 1 | 0 | 0 | 1 |
In [ ]python · cell 18
python
模型搭建
- 处理完前面的数据我们就得到建模数据,下一步是选择合适模型
- 在进行模型选择之前我们需要先知道数据集最终是进行监督学习还是无监督学习
- 除了根据我们任务来选择模型外,还可以根据数据样本量以及特征的稀疏性来决定
- 刚开始我们总是先尝试使用一个基本的模型来作为其baseline,进而再训练其他模型做对比,最终选择泛化能力或性能比较好的模型
思考0
- 数据集哪些差异会导致模型在拟合数据是发生变化
In [215]python · cell 22
python
# sklearn模型算法选择路径图
Image('20170624105439491.png')Output
<IPython.core.display.Image object>
[省略较大 image/png 输出]
In [ ]python · cell 23
python
任务一:切割训练集和测试集
- 按比例切割训练集和测试集(一般测试集的比例有30%、25%、20%、15%和10%)
- 按目标变量分层进行等比切割
- 设置随机种子以便结果能复现
提示1
- 切割数据集是为了后续能评估模型泛化能力
- sklearn中切割数据集的方法为
train_test_split - 查看函数文档可以在jupyter noteboo里面使用
train_test_split?后回车即可看到 - 分层和随机种子在参数里寻找
思考1
- 什么情况下切割数据集的时候不用进行随机选取
In [216]python · cell 27
python
from sklearn.model_selection import train_test_splitIn [217]python · cell 28
python
# 一般先取出X和y后再切割,有些情况会使用到未切割的,这时候X和y就可以用
X = data
y = train['Survived']In [218]python · cell 29
python
# 对数据集进行切割
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)In [219]python · cell 30
python
# 查看数据形状
X_train.shape, X_test.shapeOutput
((668, 10), (223, 10))
In [ ]python · cell 31
python
任务二:模型创建
- 创建基于线性模型的分类模型(逻辑回归)
- 创建基于树的分类模型(决策树、随机森林)
- 查看模型的参数,并更改参数值,观察模型变化
提示2
- 逻辑回归不是回归模型而是分类模型,不要与
LinearRegression混淆 - 随机森林其实是决策树集成为了降低决策树过拟合的情况
- 线性模型所在的模块为
sklearn.linear_model - 树模型所在的模块为
sklearn.ensemble
思考2
- 为什么线性模型可以进行分类任务,背后是怎么的数学关系
- 对于多分类问题,线性模型是怎么进行分类的
In [223]python · cell 35
python
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifierIn [224]python · cell 36
python
# 默认参数逻辑回归模型
lr = LogisticRegression()
lr.fit(X_train, y_train)Output
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
verbose=0, warm_start=False)In [225]python · cell 37
python
# 查看训练集和测试集score值
print("Training set score: {:.2f}".format(lr.score(X_train, y_train)))
print("Testing set score: {:.2f}".format(lr.score(X_test, y_test)))Output
Training set score: 0.80 Testing set score: 0.78
In [226]python · cell 38
python
# 调整参数后的逻辑回归模型
lr2 = LogisticRegression(C=100)
lr2.fit(X_train, y_train)Output
LogisticRegression(C=100, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
verbose=0, warm_start=False)In [227]python · cell 39
python
print("Training set score: {:.2f}".format(lr2.score(X_train, y_train)))
print("Testing set score: {:.2f}".format(lr2.score(X_test, y_test)))Output
Training set score: 0.80 Testing set score: 0.79
In [228]python · cell 40
python
# 默认参数的随机森林分类模型
rfc = RandomForestClassifier()
rfc.fit(X_train, y_train)Output
RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
max_depth=None, max_features='auto', max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,
oob_score=False, random_state=None, verbose=0,
warm_start=False)In [229]python · cell 41
python
print("Training set score: {:.2f}".format(rfc.score(X_train, y_train)))
print("Testing set score: {:.2f}".format(rfc.score(X_test, y_test)))Output
Training set score: 0.97 Testing set score: 0.82
In [230]python · cell 42
python
# 调整参数后的随机森林分类模型
rfc2 = RandomForestClassifier(n_estimators=100, max_depth=5)
rfc2.fit(X_train, y_train)Output
RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
max_depth=5, max_features='auto', max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=1,
oob_score=False, random_state=None, verbose=0,
warm_start=False)In [231]python · cell 43
python
print("Training set score: {:.2f}".format(rfc2.score(X_train, y_train)))
print("Testing set score: {:.2f}".format(rfc2.score(X_test, y_test)))Output
Training set score: 0.86 Testing set score: 0.83
任务三:输出模型预测结果
- 输出模型预测分类标签
- 输出不通分类标签的预测概率
提示3
- 一般监督模型在sklearn里面有个
predict能输出预测标签,predict_proba则可以输出标签概率
思考3
- 预测标签的概率对我们有什么帮助
In [234]python · cell 47
python
# 预测标签
pred = lr.predict(X_train)In [235]python · cell 48
python
# 此时我们可以看到0和1的数组
pred[:10]Output
array([0, 1, 1, 1, 0, 0, 1, 0, 1, 1], dtype=int64)
In [236]python · cell 49
python
# 预测标签概率
pred_proba = lr.predict_proba(X_train)In [237]python · cell 50
python
pred_proba[:10]Output
array([[0.62887291, 0.37112709],
[0.14897206, 0.85102794],
[0.47162003, 0.52837997],
[0.20365672, 0.79634328],
[0.86428125, 0.13571875],
[0.9033887 , 0.0966113 ],
[0.13829338, 0.86170662],
[0.89516141, 0.10483859],
[0.05735141, 0.94264859],
[0.13593291, 0.86406709]])In [ ]python · cell 51
python
模型评估
- 模型评估是为了知道模型的泛化能力。
- 交叉验证(cross-validation)是一种评估泛化性能的统计学方法,它比单次划分训练集和测试集的方法更加稳定、全面。
- 在交叉验证中,数据被多次划分,并且需要训练多个模型。
- 最常用的交叉验证是 k 折交叉验证(k-fold cross-validation),其中 k 是由用户指定的数字,通常取 5 或 10。
- 准确率(precision)度量的是被预测为正例的样本中有多少是真正的正例
- 召回率(recall)度量的是正类样本中有多少被预测为正类
- f-分数是准确率与召回率的调和平均
任务一:交叉验证
- 用10折交叉验证来评估逻辑回归模型
- 计算交叉验证精度的平均值
In [245]python · cell 55
python
Image('Snipaste_2020-01-05_16-37-56.png')Output
<IPython.core.display.Image object>
提示4
- 交叉验证在sklearn中的模块为
sklearn.model_selection
思考4
- k折越多的情况下会带来什么样的影响?
In [238]python · cell 58
python
from sklearn.model_selection import cross_val_scoreIn [200]python · cell 59
python
lr = LogisticRegression(C=100)
scores = cross_val_score(lr, X_train, y_train, cv=10)In [201]python · cell 60
python
# k折交叉验证分数
scoresOutput
array([0.82352941, 0.79411765, 0.80597015, 0.80597015, 0.8358209 ,
0.88059701, 0.72727273, 0.86363636, 0.75757576, 0.71212121])In [202]python · cell 61
python
# 平均交叉验证分数
print("Average cross-validation score: {:.2f}".format(scores.mean()))Output
Average cross-validation score: 0.80
任务二:混淆矩阵
- 计算二分类问题的混淆矩阵
- 计算精确率、召回率以及f-分数
In [246]python · cell 63
python
Image('Snipaste_2020-01-05_16-38-26.png')Output
<IPython.core.display.Image object>
In [247]python · cell 64
python
Image('Snipaste_2020-01-05_16-39-27.png')Output
<IPython.core.display.Image object>
提示5
- 混淆矩阵的方法在sklearn中的
sklearn.metrics模块 - 混淆矩阵需要输入真实标签和预测标签
思考5
- 如果自己实现混淆矩阵的时候该注意什么问题
In [147]python · cell 67
python
from sklearn.metrics import confusion_matrixIn [207]python · cell 68
python
# 训练模型
lr = LogisticRegression(C=100)
lr.fit(X_train, y_train)Output
LogisticRegression(C=100, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
verbose=0, warm_start=False)In [208]python · cell 69
python
# 模型预测结果
pred = lr.predict(X_train)In [209]python · cell 70
python
# 混淆矩阵
confusion_matrix(y_train, pred)Output
array([[350, 62],
[ 71, 185]], dtype=int64)In [210]python · cell 71
python
from sklearn.metrics import classification_reportIn [211]python · cell 72
python
# 精确率、召回率以及f1-score
print(classification_report(y_train, pred))Output
precision recall f1-score support
0 0.83 0.85 0.84 412
1 0.75 0.72 0.74 256
avg / total 0.80 0.80 0.80 668
In [ ]python · cell 73
python
任务三:ROC曲线
- 绘制ROC曲线
提示6
- ROC曲线在sklearn中的模块为
sklearn.metrics - ROC曲线下面所包围的面积越大越好
思考6
- 对于多分类问题如何绘制ROC曲线
In [212]python · cell 77
python
from sklearn.metrics import roc_curveIn [213]python · cell 78
python
fpr, tpr, thresholds = roc_curve(y_test, lr.decision_function(X_test))
plt.plot(fpr, tpr, label="ROC Curve")
plt.xlabel("FPR")
plt.ylabel("TPR (recall)")
# 找到最接近于0的阈值
close_zero = np.argmin(np.abs(thresholds))
plt.plot(fpr[close_zero], tpr[close_zero], 'o', markersize=10, label="threshold zero", fillstyle="none", c='k', mew=2)
plt.legend(loc=4)Output
<matplotlib.legend.Legend at 0x2e4ea25db00>
<Figure size 720x432 with 1 Axes>
In [ ]python · cell 79
python
