经过前面的两章的知识点的学习,我可以对数数据的本身进行处理,比如数据本身的增删查补,还可以做必要的清洗工作。那么下面我们就要开始使用我们前面处理好的数据了。这一章我们要做的就是使用数据,我们做数据分析的目的也就是,运用我们的数据以及结合我的业务来得到某些我们需要知道的结果。那么分析的第一步就是建模,搭建一个预测模型或者其他模型;我们从这个模型的到结果之后,我们要分析我的模型是不是足够的可靠,那我就需要评估这个模型。今天我们学习建模,下一节我们学习评估。
我们拥有的泰坦尼克号的数据集,那么我们这次的目的就是,完成泰坦尼克号存活预测这个任务。
# 导入库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns # 基于matolotlib的可视化库
from IPython.display import Image # 展示图片
from IPython.display import display_html as dis_h # 使用html展示数据
载入这些库,如果缺少某些库,请安装他们
【思考】这些库的作用是什么呢?你需要查一查
载入我们提供清洗之后的数据(clear_data.csv),大家也将原始数据载入(train.csv),说说他们有什么不同
ans:清洗数据中 没有姓名列和存活列 文字数据都转换为了数字(方便快速运算)
# 导入数据
data = pd.read_csv('clear_data.csv') # 清洗后的数据
train = pd.read_csv('train.csv') # 原始数据
data.shape,train.shape
((891, 11), (891, 12))
# 观察清洗后的数据和原始数据
print(dis_h(data.head(3))) # 没有姓名和存活列 文字数据都转换为了数字
print(dis_h(train.head(3)))
PassengerId | Pclass | Age | SibSp | Parch | Fare | Sex_female | Sex_male | Embarked_C | Embarked_Q | Embarked_S | |
---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 3 | 22.0 | 1 | 0 | 7.2500 | 0 | 1 | 0 | 0 | 1 |
1 | 1 | 1 | 38.0 | 1 | 0 | 71.2833 | 1 | 0 | 1 | 0 | 0 |
2 | 2 | 3 | 26.0 | 0 | 0 | 7.9250 | 1 | 0 | 0 | 0 | 1 |
None
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 |
None
这里我的建模,并不是从零开始,自己一个人完成完成所有代码的编译。我们这里使用一个机器学习最常用的一个库(sklearn)来完成我们的模型的搭建
下面给出sklearn的算法选择路径,供大家参考
# sklearn模型算法选择路径图
Image('sklearn.png')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kUzwpzoS-1648140848631)(output_13_0.png)]
【思考】数据集哪些差异会导致模型在拟合数据时发生变化
ans:数据拟合(曲线拟合)根据已知数据,得到与数据拟合的曲线,可以根据曲线的方程对其他未知数进行预测,需要避免曲线过拟合(完全拟合,容错率太低)和欠拟合(容错率太高)造成预测错误
会发生变化的情况:
分情况讨论
Image('fitting.png')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VH72KFdV-1648140848631)(output_15_0.png)]
这里使用留出法划分数据集
训练集用于训练模型,测试集用于评估模型
【思考】
详细:https://www.cnblogs.com/jyroy/p/13547118.html
train_test_split
train_test_split?
后回车即可看到from sklearn.model_selection import train_test_split
# 一般先取出X和y后再切割,有些情况会使用到未切割的,这时候X和y就可以用,x是清洗好的数据,y是我们要预测的存活数据'Survived'
X = data # 用于训练的数据
y = train['Survived'] # 用于预测的数据
# 导入切割数据集的包
from sklearn.model_selection import train_test_split
train_test_split?
# 要求切割因变量和自变量数据size长度相同
# 浮点数则百分比,整型则数量,默认25%
# 随机种子
# 打乱后划分
# 按某一列分层
# 对数据集进行切割
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
# 查看数据形状
X_train.shape, X_test.shape
((668, 11), (223, 11))
【思考】
ans:需要复现的时候
LinearRegression
混淆sklearn.linear_model
sklearn.ensemble
# 导入所需库
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
# 默认参数逻辑回归模型
lr = LogisticRegression().fit(X_train, y_train)
lr
# fit训练
# predict 预测
# predict_proba 概率估计
# score 返回平均准确度
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
LogisticRegression()
# 查看训练集和测试集score值
print("训练集得分: {:.2f}".format(lr.score(X_train, y_train)))
print("测试集得分: {:.2f}".format(lr.score(X_test, y_test)))
训练集得分: 0.80
测试集得分: 0.78
# 调整参数后的逻辑回归模型
# 通过添加正则化项可以限制模型的复杂度,使得模型在复杂度和性能达到平衡,约束敏感度。
# 默认L2正则化
# C越小越能约束
lr2 = LogisticRegression(C=1000).fit(X_train, y_train)
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
解决过拟合和欠拟合的几个办法
print("Training set score: {:.2f}".format(lr2.score(X_train, y_train)))
print("Testing set score: {:.2f}".format(lr2.score(X_test, y_test)))
Training set score: 0.80
Testing set score: 0.77
# 随机森林分类模型
# 包含多个决策树分类器
# 数的数量,深度,
rfc = RandomForestClassifier(n_estimators=600).fit(X_train, y_train)
print("Training set score: {:.2f}".format(rfc.score(X_train, y_train)))
print("Testing set score: {:.2f}".format(rfc.score(X_test, y_test)))
Training set score: 1.00
Testing set score: 0.79
# 调整参数后的随机森林分类模型
rfc2 = RandomForestClassifier(n_estimators=100, max_depth=5)
rfc2.fit(X_train, y_train)
print("Training set score: {:.2f}".format(rfc2.score(X_train, y_train)))
print("Testing set score: {:.2f}".format(rfc2.score(X_test, y_test)))
Training set score: 0.87
Testing set score: 0.78
【思考】
predict
能输出预测标签,predict_proba
则可以输出标签概率# 预测标签
pred = lr.predict(X_train)
# 此时我们可以看到0和1的数组
pred[:10]
array([1, 0, 0, 1, 1, 0, 0, 0, 1, 0], dtype=int64)
# 预测标签概率
pred_proba = lr.predict_proba(X_train)
pred_proba[:10]
array([[0.08552386, 0.91447614],
[0.78976583, 0.21023417],
[0.80014197, 0.19985803],
[0.35361092, 0.64638908],
[0.23281758, 0.76718242],
[0.51150187, 0.48849813],
[0.59644512, 0.40355488],
[0.90821332, 0.09178668],
[0.45088222, 0.54911778],
[0.87122833, 0.12877167]])
【思考】
ans:帮助我们预测标签emm
根据之前的模型的建模,我们知道如何运用sklearn这个库来完成建模,以及我们知道了的数据集的划分等等操作。那么一个模型我们怎么知道它好不好用呢?以至于我们能不能放心的使用模型给我的结果呢?那么今天的学习的评估,就会很有帮助。
加载下面的库
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from IPython.display import Image
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score # 交叉验证函数
%matplotlib inline
任务:加载数据并分割测试集和训练集
# 一般先取出X和y后再切割,有些情况会使用到未切割的,这时候X和y就可以用,x是清洗好的数据,y是我们要预测的存活数据'Survived'
data = pd.read_csv('clear_data.csv')
train = pd.read_csv('train.csv')
X = data
y = train['Survived']
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=42)
# 为了避免切割时的偶然性,使用交叉验证
【思考】:将上面的概念进一步的理解,大家可以做一下总结
# 默认参数逻辑回归模型
lr = LogisticRegression()
# 采用10折交叉
score = cross_val_score(lr,X_train,y_train,cv=10)
score.mean()
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
0.7964043419267299
【思考】什么是二分类问题的混淆矩阵,理解这个概念,知道它主要是运算到什么任务中的
#思考回答
#提示:混淆矩阵
Image('Snipaste_2020-01-05_16-38-26.png')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aDRizWZr-1648140848632)(output_60_0.png)]
#提示:准确率 (Accuracy),精确度(Precision),Recall,f-分数计算方法
Image('Snipaste_2020-01-05_16-39-27.png')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rgyNJwdQ-1648140848632)(output_61_0.png)]
sklearn.metrics
模块classification_report
模块from sklearn.metrics import confusion_matrix
# 训练模型
lr = LogisticRegression(C=100)
lr.fit(X_train, y_train)
C:\Tool\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
n_iter_i = _check_optimize_result(
LogisticRegression(C=100)
# 模型预测结果
pred = lr.predict(X_train)
# 混淆矩阵
confusion_matrix(y_train, pred,labels=[0,1])
array([[357, 55],
[ 78, 178]], dtype=int64)
from sklearn.metrics import classification_report
# 精确率、召回率以及f1-score
print(classification_report(y_train, pred))
precision recall f1-score support
0 0.82 0.87 0.84 412
1 0.76 0.70 0.73 256
accuracy 0.80 668
macro avg 0.79 0.78 0.79 668
weighted avg 0.80 0.80 0.80 668
【思考】什么是ROC曲线,OCR曲线的存在是为了解决什么问题?
sklearn.metrics
from sklearn.metrics import roc_curve
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)
[]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XQKhEpkR-1648140848633)(output_73_1.png)]
from sklearn.metrics import plot_roc_curve
# 直接画ROC曲线
【思考】你能从这条OCR曲线的到什么信息?这些信息可以做什么?
可以通过多个模型画出ROC曲线,看所占面积,面积越大,效果越好,从而选择更好的模型