文章目录
前言
入门机器学习,记录学习日常,如有错误请多指正。
参考书目:机器学习及Python应用
数据集可在陈强教授主页下载
一、数据预处理
1.数据介绍
案例使用前列腺癌数据prostate。响应变量为lpsa(log of prostate specific antigen,前列腺特异抗原对数),特征变量为8个临床指标。
2.导入模块和数据文件
1)导入案例所需的全部模块
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.linear_model import RidgeCV
from sklearn.linear_model import Lasso
from sklearn.linear_model import lasso_path
from sklearn.linear_model import LassoCV
from sklearn.linear_model import ElasticNet
from sklearn.linear_model import ElasticNetCV
from sklearn.linear_model import enet_path
2)导入数据
prostate=pd.read_csv('D:\数据集\\MLPython_Data\\prostate.csv')
3.数据概况
print('数据集形状:',prostate.shape)
print('前五个观测值:\n',prostate.head())
print('特征变量均值:',prostate.mean())
print('特征变量标准差:',prostate.std())
数据集形状: (97, 9)
前五个观测值:
lcavol lweight age lbph svi lcp gleason pgg45 lpsa
0 -0.579818 2.769459 50 -1.386294 0 -1.386294 6 0 -0.430783
1 -0.994252 3.319626 58 -1.386294 0 -1.386294 6 0 -0.162519
2 -0.510826 2.691243 74 -1.386294 0 -1.386294 7 20 -0.162519
3 -1.203973 3.282789 58 -1.386294 0 -1.386294 6 0 -0.162519
4 0.751416 3.432373 62 -1.386294 0 -1.386294 6 0 0.371564
特征变量均值:
lcavol 1.350010
lweight 3.628943
age 63.865979
lbph 0.100356
svi 0.216495
lcp -0.179366
gleason 6.752577
pgg45 24.381443
lpsa 2.478387
dtype: float64
特征变量标准差:
lcavol 1.178625
lweight 0.428411
age 7.445117
lbph 1.450807
svi 0.413995
lcp 1.398250
gleason 0.722134
pgg45 28.204035
lpsa 1.154329
dtype: float64
4.标准化
不考虑响应变量lpsa,所以特征变量的均值和标准差有较大差异。在进行惩罚回归前,将特征变量标准化。
X_raw=prostate.iloc[:,:-1]
y=prostate.iloc[:,-1]
#提取数据矩阵和响应变量
scaler=StandardScaler()#类
X=scaler.fit_transform(X_raw)#对原始数据矩阵标准化
print(np.mean(X,axis=0))
print(np.std(X,axis=0))
[ 4.57823928e-17 2.89573634e-16 4.13186095e-16 -2.43218962e-17
-3.66259142e-17 3.66259142e-17 -2.17466366e-17 5.63695711e-17]#均值
[1. 1. 1. 1. 1. 1. 1. 1.]#标准差
标准化后数据矩阵X变量的均值几乎为0,标准差为1。
二、岭回归
1.回归系数
model=Ridge()
model.fit(X,y)#默认惩罚参数为1
print('拟合优度:',model.score(X,y))
print('截距项:',model.intercept_)
print('回归系数:',model.coef_)
print(pd.DataFrame(model.coef_,index=X_raw.columns,columns=['Coefficient']))#回归系数数据框
拟合优度: 0.6632704474129987
截距项: 2.478386878350515
回归系数: [ 0.64734891 0.26423507 -0.15178989 0.13694453 0.30825889 -0.13074243
0.03755141 0.11907848]
Coefficient
lcavol 0.647349
lweight 0.264235
age -0.151790
lbph 0.136945
svi 0.308259
lcp -0.130742
gleason 0.037551
pgg45 0.119078
2.岭迹图
#定义罚项参数alpha网格
alphas=np.logspace(-3,6,100)#对数尺度
coefs=[]
for alpha in alphas:
model=Ridge(alpha=alpha)
model.fit(X,y)
coefs.append(model.coef_)
#不同alpha取值的相应回归系数
#岭迹图
ax=plt.gca()
ax.plot(alphas,coefs)
ax.set_xscale('log')#对数尺度
plt.xlabel('alpha(log scale')
plt.ylabel('Coefficients')
plt.title('Ridge Cofficient Path')
plt.axhline(0,linestyle='--',linewidth=1,color='k')
plt.legend(X_raw.columns)
plt.show()
3.最优罚项参数
#使用RidgeCV选择最优参数,默认留1交叉验证
model=RidgeCV(alphas=alphas) #alphas=alphas表示将惩罚参数设置为前面的alphas网格
print(model.fit(X,y))
print('最优参数alpha:',model.alpha_)#默认最小均方误差
RidgeCV(alphas=array([1.00000000e-03, 1.23284674e-03, 1.51991108e-03, 1.87381742e-03,
2.31012970e-03, 2.84803587e-03, 3.51119173e-03, 4.32876128e-03,
5.33669923e-03, 6.57933225e-03, 8.11130831e-03, 1.00000000e-02,
1.23284674e-02, 1.51991108e-02, 1.87381742e-02, 2.31012970e-02,
2.84803587e-02, 3.51119173e-02, 4.32876128e-02, 5.33669923e-02,
6.57933225e-02, 8.11130831e-0...
8.11130831e+03, 1.00000000e+04, 1.23284674e+04, 1.51991108e+04,
1.87381742e+04, 2.31012970e+04, 2.84803587e+04, 3.51119173e+04,
4.32876128e+04, 5.33669923e+04, 6.57933225e+04, 8.11130831e+04,
1.00000000e+05, 1.23284674e+05, 1.51991108e+05, 1.87381742e+05,
2.31012970e+05, 2.84803587e+05, 3.51119173e+05, 4.32876128e+05,
5.33669923e+05, 6.57933225e+05, 8.11130831e+05, 1.00000000e+06]))
最优参数alpha: 6.5793322465756825
结果表明最优惩罚参数介于1与10之间。在更精细的网格上进行留一交叉验证。
alphas=np.linspace(1,10,1000)
model=RidgeCV(alphas=alphas,store_cv_values=True)
model.fit(X,y)
print(model.alpha_)
最优参数alpha: 6.018018018018018
考察最小均方误差
mse=np.mean(model.cv_values_,axis=0)
print(np.min(mse))#最小均方误差
index_min=np.argmin(mse)#最小均方误差位置索引
print(index_min)
print(alphas[index_min],mse[index_min])#最优alpha与最小均方误差
0.5363247513368606#最小均方误差
557#最小均方误差位置索引
6.018018018018018 0.5363247513368606#最优alpha与最小均方误差
画出交叉验证图
plt.plot(alphas,mse)
plt.axvline(alphas[index_min],linestyle='--',linewidth=1,color='k')
plt.xlabel('alpha')
plt.ylabel('Mean Squared Error')
plt.title('CV Error for Ridge Regression')
plt.tight_layout()
plt.show()
最佳模型回归系数
print('最佳模型的回归系数:\n',model.coef_)
print(pd.DataFrame(model.coef_,index=X_raw.columns,columns=['Coefficient']))
最佳模型的回归系数:
[ 0.5880107 0.25879333 -0.12827855 0.12594561 0.28634285 -0.06619523
0.04477184 0.09870708]
Coefficient
lcavol 0.588011
lweight 0.258793
age -0.128279
lbph 0.125946
svi 0.286343
lcp -0.066195
gleason 0.044772
pgg45 0.098707
三、Lasso回归
1.回归系数
model=Lasso(alpha=0.1)#惩罚参数为0.1
model.fit(X,y)
print('套索估计拟合优度:',model.score(X,y))
print(pd.DataFrame(model.coef_,index=X_raw.columns,columns=['Coefficient']))
print('惩罚参数为1时回归系数',Lasso().fit(X,y).coef_)
套索估计拟合优度: 0.6261113876338473
Coefficient
lcavol 0.567792
lweight 0.194827
age -0.000000
lbph 0.020717
svi 0.205665
lcp 0.000000
gleason 0.000000
pgg45 0.022085
#惩罚参数为0.1时回归系数,有三个特征变量为0的稀疏解
惩罚参数为1时回归系数
[0. 0. 0. 0. 0. 0. 0. 0.]#惩罚力度过大,回归系数均为0
2.岭迹图
alphas,coefs,_=lasso_path(X,y,eps=1e-4) #惩罚参数和相应回归系数,eps=1e-4表示最小惩罚参数值为最大惩罚参数值的10^(-4)
print(alphas.shape,coefs.shape)
(100,) (8, 100)
alphas,coefs形状第一分量不一至,画图时需将coefs转置
ax=plt.gca()
ax.plot(alphas,coefs.T)
ax.set_xscale('log')
plt.xlabel('alpha(log scale)')
plt.ylabel('Coefficients')
plt.title('Lasso Cofficient Path')
plt.axhline(0,linestyle='--',linewidth=1,color='k')
plt.legend(X_raw.columns)
plt.show()
如图,lasso估计量在收缩回归系数时使各变量回归系数依次变为0,故具备筛选变量功能。
3.最优罚项参数
1)使用Lassocv类,进行10折交叉验证选择最优惩罚参数
kfold=KFold(n_splits=10,shuffle=True,random_state=1)
alphas=np.logspace(-4,-2,100)
model=LassoCV(alphas=alphas,cv=kfold)
model.fit(X,y)
print(model.alpha_)#最优惩罚参数
print(pd.DataFrame(model.coef_,index=X_raw.columns,columns=['Coefficient']))#最优惨发参数回归系数
0.007220809018385471#最优惩罚参数
Coefficient
lcavol 0.641350
lweight 0.258524
age -0.136313
lbph 0.129053
svi 0.293228
lcp -0.099059
gleason 0.027811
pgg45 0.106840
#最优惩罚参数回归系数
2)使用for循环进行交叉验证,选择最优惩罚参数
alphas=np.logspace(-4,-2,100)
scores=[]
for alpha in alphas:
model=Lasso(alpha=alpha)
kfold=KFold(n_splits=10,shuffle=True,random_state=1)
scores_val=-cross_val_score(model,X,y,cv=kfold,scoring='neg_mean_squared_error')
score=np.mean(scores_val)
scores.append(score)
mse=np.array(scores)
index_min=np.argmin(mse)
print(index_min)
print(alphas[index_min])
92#最小均方误差位置索引
0.007220809018385471#最小均方误差
画出交叉验证图
#交叉验证图
plt.plot(alphas,mse)
plt.axvline(alphas[index_min],linestyle='--',linewidth=1,color='k')
plt.xlabel('alpha')
plt.ylabel('Mean Squared Error')
plt.title('CV Error for Ridge Regression')
plt.tight_layout()
plt.show()
四、弹性网回归
1.回归系数
model=ElasticNet(alpha=0.1,l1_ratio=0.5)#alpha=0.1表示惩罚参数为0.1,l1_ratio=0.5表示L1惩罚项和L2惩罚项的比重为0.5
model.fit(X,y)
print(model.score(X,y))#拟合优度
print(pd.DataFrame(model.coef_,index=X_raw.columns,columns=['Coefficient']))
0.641941891532626#拟合优度
Coefficient
lcavol 0.553863
lweight 0.216887
age -0.021952
lbph 0.065296
svi 0.236458
lcp 0.000000
gleason 0.001895
pgg45 0.059813
2.岭迹图
画出弹性网系数路径
alphas,coefs,_=enet_path(X,y,eps=1e-4,l1_ratio=0.5)#惩罚参数和相应回归系数,eps=1e-4表示最小惩罚参数值为最大惩罚参数值的10^(-4)
ax=plt.gca()
ax.plot(alphas,coefs.T)
ax.set_xscale('log')
plt.xlabel('alpha(log scale)')
plt.ylabel('Coefficients')
plt.title('Elastic Net Coefficient Path (l1_ratio=0.5)')
plt.axhline(0,linestyle='--',linewidth=1,color='k')
plt.legend(X_raw.columns)
plt.show()
3.最优惩罚参数
alphas=np.logspace(-4,0,100)
kfold=KFold(n_splits=10,shuffle=True,random_state=1)
model=ElasticNetCV(cv=kfold,alphas=alphas,l1_ratio=[0.0001,0.001,0.01,0.1,0.5,1])#制定alphas与l1_ratio网格
model.fit(X,y)
print('最优惩罚参数:',model.alpha_)
print('最优的L1惩罚项比重',model.l1_ratio_)
print('最佳弹性网模型R2:',model.score(X,y))
print(pd.DataFrame(model.coef_,index=X_raw.columns,columns=['Coefficient']))
最优惩罚参数: 0.07390722033525783
最优的L1惩罚项比重 0.0001
最佳弹性网模型R2: 0.6592730190729547
Coefficient
lcavol 0.576684
lweight 0.257380
age -0.123709
lbph 0.123825
svi 0.282254
lcp -0.054796
gleason 0.045857
pgg45 0.095584