天天看点

2020研究生数模整理(1):机器学习回归+GridSearch参数调优+AutoML(TPOT)+模型评估+决策树绘制1 三种回归模型2 GridSearch参数调优3 AutoML:TPOT4 模型评估:评估指标及残差图

本文将介绍以下四点内容:

(1)三种回归模型:线性回归、随机森林(输出决策树图)、梯度提升回归;

(2)使用GridSearch对机器学习模型进行参数调优;

(3)自动机器学习包:TPOT;

(4)回归模型的评估:评估指标+残差图。

2020研究生数学建模比赛已经收尾,我们组选择的是B题,预测汽油辛烷值损失的建模。一般来讲,对分类变量进行预测使用分类器,对连续变量进行预测使用回归。本文为整理的建模中所用的回归模型,欢迎交流,指出不足。

1 三种回归模型

本部分要介绍的三种模型都是用于回归的模型,这里变量已经经过了筛选,特征工程已经结束,主要作为数模所使用的方法的整理汇总。其中线性回归原理比较简单,随机森林和梯度提升回归都是基于树的决策,随机森林是多棵树,相对于

1.1 线性回归

线性回归的原理比较简单,不多说,直接上代码。

#载入包
import pandas as pd
import numpy as np  
from sklearn.model_selection import train_test_split #用户划分训练集和测试集
from sklearn.linear_model import LinearRegression  #线性回归包
from sklearn import metrics  #模型评估包
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
#以下为后续绘图用包
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

#数据读取
data= pd.read_csv("D:/course/other/shumo_code_2020/data/data_for_q3.csv")
del data["index"]
#训练集和测试集的划分
data_train, data_test= train_test_split(data,test_size=0.3, random_state=0) #参数test_size表示测试集的比例
train_y = data_train.RON_loss
columns = data_train.columns.tolist()
train_X = data_train.drop(["RON_loss"],axis = 1)
test_X = data_test.drop(["RON_loss"],axis = 1)
test_y = data_test.RON_loss
#构建模型
model = LinearRegression()
model = model.fit(train_X, train_y)

#模型应用:进行值的预测,训练集和测试集都要预测是为了评估模型的能力以及有没有过拟合的问题,关于模型评估请见第四部分
#预测训练集的Y值
train_y_predict = model.predict(train_X)
#预测测试集的Y值
predicted_values = model.predict(test_X)
           

1.2 随机森林

随机森林是基于树的回归,这里会介绍如何使用随机森林进行建模以及如何输出决策过程,即决策树的构建过程:根节点是哪个,以及各个节点的属性值等。

1.2.1 模型

数据集的划分过程将不再展示,直接展示建模部分。在随机森林的建模过程中,不仅仅要挑选样本,还要挑选变量,所以这里有一个max_features参数,在设置时要注意不能超过变量总数,有关其他参数的调优,可以参考第三部分配合GridSearch使用。

from sklearn.ensemble import RandomForestRegressor  #随机森林回归包,注意和随机森林分类器的包区分
#数据集划分和前面线性回归一致
RFmodel = RandomForestRegressor(n_estimators= 500, bootstrap=True, max_features= 19, min_samples_leaf=5, random_state=42)
RFmodel.fit(train_X,train_y)

train_y_predict = RFmodel.predict(train_X)
predicted_values = RFmodel.predict(test_X)
           

1.2.2 决策树输出

决策树的输出需要安装一个外部库,export_graphviz,官网下载链接:http://www.graphviz.org/download/,下载后双击安装,找到安装目录,将bin文件路径加入系统环境变量,比如我的是:D:\programesfilefolder\Graphviz\bin。配置完成后,打开命令行,输入dot -version,如果出现版本信息,则配置成功。

from sklearn.tree import export_graphviz  #载入包

rf_small = RandomForestRegressor(n_estimators = 500,bootstrap=False,max_features = 19, min_samples_leaf= 5 , random_state=42)
rf_small.fit(train_X, train_y)
tree_small = rf_small.estimators_[5]
export_graphviz(tree_small, out_file ='D:/course/other/shumo_code_2020/result/q2/tree2.dot', feature_names = train_X.columns.tolist() , rounded = True, precision = 1)
           

到这里,决策树的dot文件已经生成了,接下来需要将命令行切换至当前目录,执行dot -Tpdf tree2.dot -o tree2.pdf,一定要先切换目录,不然找不到tree文件的,也可以存成png图片格式,建议存成pdf,更加清晰。

1.3 梯度提升回归

GradientBoostingRegressor方法强调一群弱的决策方法实力可以和一个强的方法媲美,所以也是树决策,这里不再赘述,建模过程和线性回顾以及随机森林的方法一致。

2 GridSearch参数调优

GridSearch的调优方法可以说是简单粗暴,我对Gridsearch的理解就是遍历,如果需要可视化结果的时候可以考虑自行遍历,以下结合随机森林对应用进行举例。

from sklearn.model_selection  import GridSearchCV #载入包

param_grid = [
{'n_estimators': [100,200,300,400,500], 'max_features': [20,21,22,23,24,25,26]},
{'bootstrap': [False], 'n_estimators': [100,200,300,400,500], 'max_features': [20,21,22,23,24,25,26]},
]
 
forest_reg = RandomForestRegressor()
grid_search = GridSearchCV(forest_reg, param_grid, cv=5,
                          scoring='neg_mean_squared_error') 
grid_search.fit(train_X,train_y)
best_estimator = grid_search.best_estimator_
print(best_estimator)

           

其实如果想做个模型表现随参数变化的图,可以使用交叉验证自行遍历,以下为自行遍历生成图的过程。

from sklearn.model_selection import cross_val_score

score_lst = []
best_score = -1

for min_samples_leaf in [1,3,5,7,9,11,13]:
    for max_features in [19,20,21,22,23,24,25]:
        forest_reg = RandomForestRegressor(n_estimators = 500,bootstrap=False,max_features = max_features, min_samples_leaf=min_samples_leaf, random_state=42)
        score = cross_val_score(forest_reg,train_X,train_y,cv=5,scoring='neg_mean_squared_error')
        score_lst.append(score.mean())
        if score.mean() > best_score:
            best_score = score.mean()
            best_parameters = {'min_samples_leaf':min_samples_leaf,"max_features":max_features}
            print(min_samples_leaf,max_features,score.mean())
        else:
            pass
            
print('Best socre:{:.2f}'.format(best_score))
print('Best parameters:{}'.format(best_parameters))
print(score_lst)

#绘制三维图
#导入库
import numpy as np  
import matplotlib.pyplot as plt  
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D  #三维图绘制包
import pandas as pd  
import seaborn as sns     


min_samples_leaf_lst = np.array([1,3,5,7,9,11,13])
max_features_lst = np.array([19,20,21,22,23,24,25])
xx1, yy1 = np.meshgrid(min_samples_leaf_lst, max_features_lst)

newshape = (xx1.shape[0])*(xx1.shape[0])
y_input = yy1.reshape(newshape)
x_input = xx1.reshape(newshape)
z_input = np.array(score_lst).reshape(newshape)
sns.set(style='white')
sns.set(font_scale=0.8)
plt.figure(figsize=(25,10))
fig = plt.figure()

ax = fig.gca(projection='3d')
ax.plot_trisurf(x_input,y_input,z_input,cmap='rainbow')  

ax.set_ylabel('max_features',fontsize  = 8) 
ax.set_xlabel('min_samples_leaf',fontsize  = 8) 
ax.set_zlabel('score',fontsize  = 8) 
fig.tight_layout()
plt.savefig('RF_parameter_3D.png', dpi= 300)
plt.show()
           

结果图:

2020研究生数模整理(1):机器学习回归+GridSearch参数调优+AutoML(TPOT)+模型评估+决策树绘制1 三种回归模型2 GridSearch参数调优3 AutoML:TPOT4 模型评估:评估指标及残差图

3 AutoML:TPOT

自动机器学习是自动建立机器学习模型的工具,只要输入数据即可,只是运行过程比较缓慢。具体过程和机器学习一样,也需要划分训练集和测试集,建模如下,输出的py文件为最优模型及对应的最优参数。

from tpot import TPOTRegressor #载入包
#数据集划分同前
tpot = TPOTRegressor(generations=40, verbosity=2) #迭代20次
tpot.fit(train_X, train_y)
print(tpot.score(test_X, test_y))
tpot.export('pipeline2.py')
           

4 模型评估:评估指标及残差图

回归模型的评估常用的两个指标为均方误差MSE,MAE和R2,都包含在sklearn.metrics中,可以参考官方文档,也可以参考:https://www.cnblogs.com/harvey888/p/6964741.html,下面只举了MAE的使用方法,这里将不再赘述。

#以MAE为例
from sklearn.metrics import median_absolute_error
print(median_absolute_error(train_y, train_y_predict))
print(median_absolute_error(test_y, predicted_values))

           

另外,回归常见的可视化评估为绘制残差图。

data_train["ron_loss_predict"] = train_y_predict
data_test["ron_loss_predict"] = predicted_values
RF_predict = pd.concat([data_train,data_test],axis = 0)
#RF_predict
#作差
def cancha_func(lst):
    cancha_lst = []
    for item in lst:
        y1 = item[0]
        y2 = item[1]
        cancha_lst.append(y1-y2)
    return cancha_lst

loss1 = RF_predict["RON_loss"].tolist()
loss2 = RF_predict["ron_loss_predict"].tolist()
loss_all = list(zip(loss1,loss2))
RF_can = cancha_func(loss_all)
RF_predict["residual"] = RF_can
#sns.set(style="white")
sns.set(font_scale=1)
plt.figure(figsize=(6,4.5))
sns.set(style="dark")
ax = sns.residplot(RF_predict.index, RF_predict.residual, color="#821A7D")
ax.set_title("RF_residual")
ax.set(xlabel='sample_id', ylabel='RF_residual')
plt.savefig('./RF_residual.png',dpi = 300)
plt.show()
           

残差图:

2020研究生数模整理(1):机器学习回归+GridSearch参数调优+AutoML(TPOT)+模型评估+决策树绘制1 三种回归模型2 GridSearch参数调优3 AutoML:TPOT4 模型评估:评估指标及残差图

TPOT参考链接:https://www.toutiao.com/i6873417340151824904/?tt_from=weixin_moments&utm_campaign=client_share&wxshare_count=2&timestamp=1600392869&app=news_article&utm_source=weixin_moments&utm_medium=toutiao_android&use_new_style=1&req_id=2020091809342901014708310411115455&group_id=6873417340151824904