回归分析案例

回归分析:研究自变量x对因变量y影响的一种数据分析方法。

常用算法:

线性回归、二项式回归、对数回归、指数回归、核SVM、岭回归、Lasso等。

回归系数、判定系数、相关系数

回归系数:其绝对值的高低只能说明自变量和因变量之间的联系程度和变化量的比例。

判定系数:自变量对因变量的方差解释程度的值。

相关系数(解释系数):衡量变量间的相关程度或密切程度的值。

选择:

入门——简单线性回归

自变量数量少——最佳回归方法

自变量间优较强的共线性关系——岭回归

数据集噪音较多——主成分回归

高纬度变量——正则化回归

具体案例:大型促销活动前的销售预测

基本场景:

在做大型促销活动前一天上午,业务方得到了一些数据,想要基于现有的数据做回归预测。限制条件:一小时内给出结果。

思路:

选择一些常见的效果好的算法和模型,由于在特征的预处理工作投入时间短,希望通过模型自身的能力去尽量解决特征存在的隐形问题。

代码:

part 1 导入库

import pandas as pd
import numpy as np
from sklearn.linear_model import BayesianRidge, ElasticNet #批量导入要实现的回归算法
from sklearn.svm import SVR #SVM中的回归算法
from xgboost import XGBRegressor
from sklearn.ensemble import GradientBoostingRegressor #集成算法
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import explained_variance_score, mean_absolute_error, mean_squared_error, r2_score #批量导入指标算法
import matplotlib.pyplot as plt #画图

导入多种回归算法,目的是检验在没有先验经验的条件下,通过多个模型的训练,从中找到最佳拟合算法做后续应用。

part 2 数据准备

raw_data = np.loadtxt('regression.txt')
x_raw, y = raw_data[:,:-1],raw_data[:,-1]
model_ss = StandardScaler()
x = model_ss.fit_transform(x_raw)

对数据做标准化处理,直接使用fit_transform方法

part 3 拆分数据集

num = int(x.shape[0]*0.7)
x_train, x_test = x[:num,:],x[num:,:]
y_train, y_test = y[:num],y[num:]

自变量拥有506个样本,13个特征变量。

part 4 初选回归模型

n_folds = 5 #交叉检验次数
model_names = ['BayesianRidge', 'XGBR', 'ElasticNet', 'SVR', 'GBR']
model_br = BayesianRidge() #贝叶斯岭回归模型
model_xgbr = XGBRegressor(random_state = 0) #XGBR
model_etc = ElasticNet(random_state= 0) #弹性网络回归模型
model_svr = SVR(gamma= 'scale') #支持向量机回归模型
model_gbr = GradientBoostingRegressor(random_state= 0) #梯度增强回归模型
model_list = [model_br, model_xgbr, model_etc, model_svr, model_gbr]
pre_y_list = [model.fit(x_train, y_train).predict(x_test) for model in model_list]

part 5 模型效果评估

n_samples, n_features = x.shape
model_metrics_functions = [explained_variance_score, mean_absolute_error, mean_squared_error, r2_score]
model_metrics_list = [[m(y_test, pre_y_list[i]) for m in model_metrics_functions] for i in range(len(model_list))] #回归评估指标列表
regresstion_score = pd.DataFrame(model_metrics_list, index= model_names, columns=['explained_variance_score', 'mae', 'mse', 'r2'])
print('all samples: %d \t features: %d' % (n_samples, n_features),'\n','-'*60)
print('\n','regression metrics:' , '\n','-'*60)
print(regresstion_score)

每个回归模型对每个回归指标的评估矩阵。

all samples: 506 	 features: 13 
 ------------------------------------------------------------

 regression metrics: 
 ------------------------------------------------------------
               explained_variance_score       mae         mse        r2
BayesianRidge                 -0.687361  7.659193  121.319137 -0.828575
XGBR                           0.247656  5.057255   53.652032  0.191333
ElasticNet                     0.071882  6.291600   70.266387 -0.059086
SVR                           -0.000399  8.283070  104.300648 -0.572065
GBR                            0.230326  4.929874   53.346174  0.195943

根据结果可知,集成类算法XGBoost和GrantBoosting的效果最好,贝叶斯和SVR在默认参数下是比较差的,ElasticNet效果还可以。

part 6 模型效果指标评估

plt.figure(figsize=(10,10))
for i, pre_y in enumerate(pre_y_list):
    plt.subplot(len(pre_y_list)+1,1,i+1)
    plt.plot(np.arange(len(y_test)), y_test, color='k', label= 'true y')
    plt.plot(np.arange(len(y_test)), pre_y_list[i], 'g--', label = model_names[i])
    plt.title('True and {} result comparison'.format(model_names[i]))
    plt.legend(loc='upper right')
    plt.tight_layout()

 part 7 模型应用

选择XGBR来预测数据。

print('regression prediction', '\n', '-'*40)
new_point_set = [[1.05393, 0., 8.14, 0., 0.538, 5.935, 29.3, 4.4986, 4., 307., 21., 386.85, 6.58],
                 [0.7842, 0., 8.14, 0., 0.538, 5.99, 81.7, 4.2579, 4., 307., 21., 386.75, 14.67],
                 [0.80271, 0., 8.14, 0., 0.538, 5.456, 36.6, 3.7965, 4., 307., 21., 288.99, 11.69],
                 [0.7258, 0., 8.14, 0., 0.538, 5.727, 69.5, 3.7965, 4., 307., 21., 390.95,
                  11.28]]
for i , new_point in enumerate(new_point_set):
    x_matrix = np.array(new_point).reshape(1,-1)
    x_scaled = model_ss.transform(x_matrix)
    new_pre_y = model_xgbr.predict(x_scaled)
    print('predict for new point %d is: %.2f' %(i+1,new_pre_y))

结果如下:

regression prediction 
 ----------------------------------------
predict for new point 1 is: 23.11
predict for new point 2 is: 17.50
predict for new point 3 is: 20.20
predict for new point 4 is: 18.21

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值