向前逐步回归

向前逐步回归

我们在进行拟合的时候,没有必要将所有变量都引入到我们的函数之中,这种操作往往会导致过拟合,而过拟合带来的致命影响就是泛化能力差,最小二乘法估计参数的时候无法终止学习的过程。向前逐步回归的引入则可以控制学习过程中出现的过拟合,它是对最小二乘法的一种优化改进。其基本思想就是由少到多地向模型中引入变量,每次增加一个,直到没有可以引入变量为止,最后通过比较在预留样本上计算出的错误进行模型的选择。
参考连接:https://www.csdn.net/tags/NtzaUg3sNTc4NjktYmxvZwO0O0OO0O0O.html

这里我们用到的是葡萄酒测试集:下载链接如下https://archive.ics.uci.edu/ml/datasets/Wine+Quality

#导入要用到的各种包和函数
import numpy as np
import pandas as pd
from sklearn import datasets,linear_model
from math import sqrt
import matplotlib.pyplot as plt
#读入要用到的红酒数据集
wine_data = pd.read_csv('winequality-red.csv',sep=';',header=0,encoding='utf-8')
wine_data.head()
fixed acidityvolatile aciditycitric acidresidual sugarchloridesfree sulfur dioxidetotal sulfur dioxidedensitypHsulphatesalcoholquality
07.40.700.001.90.07611.034.00.99783.510.569.45
17.80.880.002.60.09825.067.00.99683.200.689.85
27.80.760.042.30.09215.054.00.99703.260.659.85
311.20.280.561.90.07517.060.00.99803.160.589.86
47.40.700.001.90.07611.034.00.99783.510.569.45
#查看红酒数据集的统计信息
wine_data.describe()
fixed acidityvolatile aciditycitric acidresidual sugarchloridesfree sulfur dioxidetotal sulfur dioxidedensitypHsulphatesalcoholquality
count1599.0000001599.0000001599.0000001599.0000001599.0000001599.0000001599.0000001599.0000001599.0000001599.0000001599.0000001599.000000
mean8.3196370.5278210.2709762.5388060.08746715.87492246.4677920.9967473.3111130.65814910.4229835.636023
std1.7410960.1790600.1948011.4099280.04706510.46015732.8953240.0018870.1543860.1695071.0656680.807569
min4.6000000.1200000.0000000.9000000.0120001.0000006.0000000.9900702.7400000.3300008.4000003.000000
25%7.1000000.3900000.0900001.9000000.0700007.00000022.0000000.9956003.2100000.5500009.5000005.000000
50%7.9000000.5200000.2600002.2000000.07900014.00000038.0000000.9967503.3100000.62000010.2000006.000000
75%9.2000000.6400000.4200002.6000000.09000021.00000062.0000000.9978353.4000000.73000011.1000006.000000
max15.9000001.5800001.00000015.5000000.61100072.000000289.0000001.0036904.0100002.00000014.9000008.000000
#定义从输入数据集中区指定列作为训练集和测试集的函数(从取1列一直到取11列)
def xattrSelect(x,idxSet):
    xOut = []
    for row in x:
        xOut.append([row[i] for i in idxSet])
    return(xOut)

xList = [] #构造用于存放属性集的列表
labels = [float(label)for label in wine_data.iloc[:,-1].tolist()]#提取wine_data中的标签值放入列表中
names = wine_data.columns.tolist() #提取出wine_data中所有属性的名称并放入列表中
for i in range (len(wine_data)):
    xList.append(wine_data.iloc[i,0:-1])#列表xList中的每个元素对应着wine_data中除去标签的每一行
    
#将原始数据集划分成训练集占(2/3),测试集占(1/3);
indices = range(len(xList))

xListTest = [xList[i] for i in indices if i%3 == 0]
xListTrain = [xList[i] for i in indices if i%3 != 0]
labelsTest = [labels[i] for i in indices if i%3 == 0]
labelsTrain = [labels[i] for i in indices if i%3 != 0]

attributeList = [] #构造用于存放属性索引的列表
index = range(len(xList[1]))#index用于下面代码中的外层for循环
indexSet =set(index) #构造由names中的所有属性对应的索引构成索引集合
oosError = []#构造用于存放下面代码中内层for循环每次结束后最小的RMSE(均方根误差)

for i in index:
    attSet = set(attributeList)
    attTrySet = indexSet - attSet #构造由不在attributeList中的属性索引组成的集合
    attTry = [ii for ii in attTrySet] #构造由在attTryz中的属性索引组成的列表
    errorList = []
    attTemp = []
    for iTry in attTry:
        attTemp = [] + attributeList
        attTemp.append(iTry)
        
        #调用attrSelect函数从xListTrain和xListTest中选取指定的列构成暂时的训练集与测试集
        xTrainTemp = xattrSelect(xListTrain, attTemp)
        xTestTemp = xattrSelect(xListTest,attTemp)
        
        #将需要用到的训练集进而测试集都转化成数组对象
        xTrain = np.array(xTrainTemp)
        yTrain = np.array(labelsTrain)
        xTest = np.array(xTestTemp)
        yTest = np.array(labelsTest)
        
        #使用scikit包训练线性回归模型
        wineQModel = linear_model.LinearRegression()
        wineQModel.fit(xTrain,yTrain)
        
        #计算在测试集上的RMSE
        rmsError = np.linalg.norm((yTest-wineQModel.predict(xTest)),2)/sqrt(len(yTest))
        errorList.append(rmsError)
        attTemp = []
        
        iBest = np.argmin(errorList)  #选出errorList中的最小值对应的新索引
        attributeList.append(attTry[iBest]) #利用新索引iBest将attTry中对应的属性索引添加到attributeListt
        oosError.append(errorList[iBest]) #将errorList中的最小值添加到oosError列表中

print("Out of sample error versus attribute set size")
print(oosError)
print('\n'+'Best attribute indices')
print(attributeList)
namesList = [names[i]  for i in attributeList]
print("\n"+"Best attribute names")
print(namesList)
Out of sample error versus attribute set size
[0.8162067605843373, 0.7638643857209025, 0.7638643857209025, 0.7638281646287916, 0.7570245479523805, 0.755096811807613, 0.7402464046416789, 0.7095983105997431, 0.7078841064360114, 0.673980209520692, 0.656971757677521, 0.6573909869011335]

Best attribute indices
[0, 1, 1, 3, 4, 5, 6, 7, 8, 9, 10, 2]

Best attribute names
['fixed acidity', 'volatile acidity', 'volatile acidity', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 'alcohol', 'citric acid']
# 绘制由不同数量的属性构成的线性回归模型在测试集上的RMSE与属性数量的关系图像
x = range(len(oosError))
plt.plot(x,oosError, 'k')
plt.xlabel('Number of Attributes')
plt.ylabel('Error(RMS)')
plt.show()

在这里插入图片描述

#绘制由最佳数量的属性构成的线性回归模型在测试集上的误差分布直方图
indexBest = oosError.index(min(oosError))
attributesBest = attributeList[1:(indexBest+1)]#attributesBests

#调用xattrSelect函数从xListTrain和xListTest中选取最佳数量的列暂时的训练集和测试集
xTrainTemp = xattrSelect(xListTrain,attributesBest)
xTestTemp = xattrSelect(xListTest,attributesBest)
xTrain = np.array(xTrainTemp)#将xTrain转化成数组对象
xTest = np.array(xTestTemp)#将xTrain转化成数组对象

#训练模型并绘制直方图
wineQModel = linear_model.LinearRegression()
wineQModel.fit(xTrain,yTrain)
errorVector = yTest-wineQModel.predict(xTest)
plt.hist(errorVector)
plt.xlabel('Bin Boundaries')
plt.ylabel('Counts')
plt.show()

#绘制红酒口感实际值与预测值之间的散点图
plt.scatter(wineQModel.predict(xTest),yTest,s=100,alpha=1)
plt.xlabel("Predict Taste Score")
plt.ylabel("Actual Taste Score")
plt.show()

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值