房价预测之回归预测模型(线性、梯度下降、正则岭回归、lasso)

实验背景:

基于波士顿房价数据掌握不同回归预测模型
案例背景介绍:
基于房子周边条件(衣食住行是否方便)、人文安全(教育程度、犯罪率等)、环境等因素来预测房价MEDV(单位千元)
在这里插入图片描述


实验目标:

数据处理(清洗、标准化)
数据可视化
回归模型应用(线性、梯队下降、岭回归、拉索回归模型)
模型结果对比评价分析


实验工具:

Python3.9
Aconda3、Jupyther
Pandas、matplotlib、sklearn


理论知识基础:

回归预测@TOC

代码详情

1:获取数据
from sklearn.datasets import load_boston
import pandas as pd
boston=load_boston()
type(boston)
boston.feature_names
features_x=boston.data
target_y=boston.target
type(features_x)
x=pd.DataFrame(features_x,columns=boston.feature_names)
x
x.info()
2:数据集划分
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(features_x,target_y,test_size=1/4)
3:特征工程-标准化
from sklearn.preprocessing import StandardScaler
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.fit_transform(x_test)
#对比第6个单元格结果,所有属性值全部规约
x_train_pd=pd.DataFrame(x_train,columns=boston.feature_names)
x_train_pd
4:建模-线性回归
from sklearn.linear_model import LinearRegression
estimator = LinearRegression()
estimator.fit(x_train, y_train)
5.预测数据+模型参数
y_predict = estimator.predict(x_test)
y_predict
estimator.coef_

estimator.intercept_
6 模型评价

7:使用其他模型
from sklearn.linear_model import SGDRegressor, Ridge, Lasso
line = LinearRegression()
sgd = SGDRegressor()
ridge = Ridge()
lasso = Lasso()
#分别训练数据
line.fit(x_train, y_train)
sgd.fit(x_train, y_train)
ridge.fit(x_train, y_train)
lasso.fit(x_train, y_train)
8:预测数据并可视化结果
line_y_pre=line.predict(x_test)
sgd_y_pre=sgd.predict(x_test)
ridge_y_pre=ridge.predict(x_test)
lasso_y_pre=lasso.predict(x_test)

#绘制图像对比
import matplotlib.pyplot as plt
#将图表嵌入到Notebook中
%matplotlib inline
plt.rcParams[‘font.sans-serif’]=[‘SimHei’] #用来显示中文标签
plt.rcParams[‘axes.unicode_minus’]=False #用来正常显示负号
#绘图
fig=plt.figure(figsize=(15,9))
plt.plot(y_test,label=‘True’)
plt.plot(line_y_pre,label=‘Line’)
plt.plot(sgd_y_pre,label=‘SGD’)
plt.plot(ridge_y_pre,label=‘Ridge’)
plt.plot(lasso_y_pre,label=‘Lasso’)
plt.legend() #添加图例

9:模型评价对比
#均方误差(Mean Squared Error)MSE 评价机制、R平方
from sklearn.metrics import mean_squared_error,r2_score
line_score=r2_score(y_test,line_y_pre)
sgd_score=r2_score(y_test,sgd_y_pre)
ridge_score=r2_score(y_test,ridge_y_pre)
lasso_score=r2_score(y_test,lasso_y_pre)
display(line_score,sgd_score,ridge_score,lasso_score)

line_score1=mean_squared_error(y_test,line_y_pre)
sgd_score1=mean_squared_error(y_test,sgd_y_pre)
ridge_score1=mean_squared_error(y_test,ridge_y_pre)
lasso_score1=mean_squared_error(y_test,lasso_y_pre)
display(line_score1,sgd_score1,ridge_score1,lasso_score1)
再看下模型的系数

sgd.coef_
line.coef_
sgd.intercept_
line.intercept_

  • 0
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值