   博主昵称：跳楼梯企鹅   

博主主页面链接：https://blog.csdn.net/weixin_50481708?spm=1000.2115.3001.5343

 创作初心：本博客的初心为与技术朋友们相互交流，每个人的技术都存在短板，博主也是一样，虚心求教，希望各位技术友给予指导

 博主座右铭：发现光，追随光，成为光，散发光

 博主研究方向：渗透测试、机器学习

 博主寄语：感谢各位技术友的支持，您的支持就是我前进的动力

## 2.测试代码

```#%%1.读入数据并划分训练集和测试集
import pandas as pd
from sklearn.model_selection import train_test_split
X = data.iloc[:,0:13]
y = data.iloc[:,13]
Xtrain,Xtest,ytrain,ytest = train_test_split(
X,y,test_size=0.2,random_state=520)
#%%2.在训练集上，对线性回归、岭回归、Lasso回归、弹性网回归四种算法进行交叉验证评估，指标是MSE和R2。
from sklearn.linear_model import LinearRegression as LR
from sklearn.linear_model import Ridge,Lasso,ElasticNet
models={}
models['LR'] = LR()
models['Ridge'] = Ridge()
models['Lasso'] = Lasso()
models['EN'] = ElasticNet()
results = {}
from sklearn.model_selection import cross_val_score
for key in models:
mse_cv = cross_val_score(models[key],
Xtrain,ytrain,cv=5,scoring="neg_mean_squared_error").mean()
r2_cv = cross_val_score(models[key],
Xtrain,ytrain,cv=5,scoring="r2").mean()
results[key] = [-1*mse_cv,r2_cv]
print(pd.DataFrame(results,index=["mse_cv","r2_cv"]))
#%%在训练集上建模并在测试集上比较多元线性回归和多项式回归的R2评分，然后进行预测结果可视化。
from sklearn.preprocessing import PolynomialFeatures as PF
from sklearn.metrics import r2_score
reg = LR()
reg.fit(Xtrain,ytrain)
yhat = reg.predict(Xtest)
r2 = r2_score(ytest,yhat)
##多项式回归建模
poly = PF(degree = 2,include_bias=False)
Xtrain_ = poly.fit_transform(Xtrain)
Xtest_ = poly.fit_transform(Xtest)
reg_ = LR().fit(Xtrain_,ytrain)
yhat_ = reg_.predict(Xtest_)
r2_ = r2_score(ytest,yhat_)
print("二次多项式回归模型在测试集上的R2的评分",r2)
#%%4.进行预测可视化
import matplotlib.pyplot as plt
plt.plot(range(len(ytest)),sorted(yhat),linewidth=2,color='green'
,label = "ploy regression")
plt.plot(range(len(ytest)),sorted(yhat_),linewidth=2,color='red'
,label = "ploy regression")
plt.plot(range(len(ytest)),sorted(ytest),linewidth=2,color='blue'
,label = "ploy regression")
plt.legend()
plt.show()```