线性回归模型预测 多因子房价预测

机器学习

机器学习是一种实现人工智能的方法,从数据中寻找规律、建立关系,根据建立的关系解决实际问题.

监督学习 Supervised Learning

​ 训练数据包括正确的结果

无监督学习 Unsupervised Learning

​ 训练数据不包括正确结果

半监督学习 Semi-supervised Learning

​ 训练数据包括少量正确的结果 (适合样本少)

强化学习 Reinforcement Learning

​ 根据每次结果收获的奖惩进行学习,实现优化

回归分析

根据数据,确定两种或两种以上变量间相互依赖的定量关系.

函数表达式 y=f(x1,x2…xn)

线性回归

变量与因变量存在线性关系

函数表达式 y=ax+b

属于机器学习中的监督学习

损失函数

在这里插入图片描述J 尽可能的小

梯度下降法

寻找极小值的一种方法,通过向函数当前点对应梯度(或者近似梯度)的反方向的规定步长距离点进行迭代搜索,直到再极小点收敛.

评估模型表现方法

y与y’的均方误差 MSE 越小越好

R方值 接近1最好

画图 看图

实战 多因子房价预测

数据 链接:https://pan.baidu.com/s/15S4LNpPlUIi90Q6hXY9_aA
提取码:nr1b

加载数据和数据预览

#加载数据
import pandas as pd
import numpy as np
data = pd.read_csv("usa_housing_price.csv")
data.head()

在这里插入图片描述

展示散点图

在这里插入图片描述

单因子预测

在这里插入图片描述

多因子预测

处理数据

X_multi = data.drop(["Price"],axis=1)

在这里插入图片描述

预测结果 多因子 单因子 对比

在这里插入图片描述

代码

#%%

#加载数据
import pandas as pd
import numpy as np
data = pd.read_csv("usa_housing_price.csv")

#%%

data.head()

#%%

#展示散点图
%matplotlib inline
from matplotlib import pyplot as plt
fig = plt.figure( figsize = (10,10))
fig1 = plt.subplot(231)
plt.scatter(data.loc[: , 'Avg. Area Income'],data.loc[: , 'Price'])
plt.title("Price VS Income")

fig1 = plt.subplot(232)
plt.scatter(data.loc[: , 'Avg. Area House Age'],data.loc[: , 'Price'])
plt.title("Price VS House Age")

fig3 =plt.subplot(233)
plt.scatter(data.loc[:,'Avg. Area Number of Rooms'],data.loc[:,'Price'])
plt.title('Price VS Number of Rooms')

fig4 =plt.subplot(234)
plt.scatter(data.loc[:,'Area Population'],data.loc[:,'Price'])
plt.title('Price VS Area Population')

fig5 =plt.subplot(235)
plt.scatter(data.loc[:,'size'],data.loc[:,'Price'])
plt.title('Price VS size')
plt.show() 

#%% md

# 预测


#%%

x = data.loc[: , 'size']
y = data.loc[: , "Price"]
y.head()

#%%

X = np.array(x).reshape(-1,1)

#%%

from sklearn.linear_model import LinearRegression
LR1 = LinearRegression()
LR1.fit(X,y)

#%%

y_predict_1 = LR1.predict(X)
print(y_predict_1)

#%% md

## 可视化 评估结果

#%%

from  sklearn.metrics import mean_squared_error,r2_score
MSE_1 = mean_squared_error(y,y_predict_1)
R2_1 = r2_score(y,y_predict_1)
print(MSE_1,R2_1)

#%%

fig_reslut = plt.figure(figsize = (8,5))
plt.scatter(X,y)
plt.plot(X,y_predict_1,"r")
plt.show()

#%% md

# 多因子预测

#%%

X_multi = data.drop(["Price"],axis=1)
X_multi

#%%

LR_multi = LinearRegression()
LR_multi.fit(X_multi,y)


#%%

y_predict_multi = LR_multi.predict(X_multi)

#%%

MSE_multi  = mean_squared_error(y,y_predict_multi )
R2_multi  = r2_score(y,y_predict_multi )
print(MSE_multi ,R2_multi )
#R2结果趋近于1

#%%

#多因子
fig_reslut_multi = plt.figure(figsize = (8,5))
plt.scatter(y,y_predict_multi)
plt.show()
#单因子
fig_reslut_multi2 = plt.figure(figsize = (8,5))
plt.scatter(y,y_predict_1)
plt.show()
#多因子效果更好

#%% md

# 预测

#%%

X_test = [65000,5,5,30000,200]
X_test = np.array(X_test).reshape(1,-1)
print(X_test)

#%%

y_test = LR_multi.predict(X_test)
print(y_test)

#%%



  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
首先,导入必要的库和读取数据集: ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score df = pd.read_csv('housing_price.csv') ``` 接着,对数据进行简单的探索性分析: ```python print(df.head()) print(df.describe()) print(df.info()) sns.pairplot(df[['price', 'area', 'income', 'age', 'rooms']]) plt.show() ``` 可以发现,数据集中共有5个变量:`price`(房价)、`area`(房屋面积)、`income`(周围家庭收入)、`age`(房龄)和`rooms`(房间数)。并且,没有缺失值。 接下来,我们分别建立单因子模型和多因子模型。 ## 单因子模型 我们首先以面积为输入量,建立单因子模型。为了可视化模型,我们将训练数据中的面积和房价画出来: ```python plt.scatter(df['area'], df['price']) plt.xlabel('Area') plt.ylabel('Price') plt.show() ``` ![image-20211102225556123](https://i.loli.net/2021/11/02/1q5KvzB2WlLj6Yw.png) 可以看出,面积与房价呈正相关关系。 接下来,我们将数据集分为训练集和测试集,并建立线性回归模型: ```python X = df[['area']] y = df['price'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) lr = LinearRegression() lr.fit(X_train, y_train) ``` 我们可以输出回归模型的系数和截距: ```python print(lr.coef_) print(lr.intercept_) ``` 输出结果为: ``` [174.97017715] 15153.555288121032 ``` 因此,我们的单因子模型为: $$ \text{Price} = 174.97 \times \text{Area} + 15153.56 $$ 接下来,我们对模型进行评估。首先,我们可以输出模型在测试集上的R平方值: ```python y_pred = lr.predict(X_test) print(r2_score(y_test, y_pred)) ``` 输出结果为: ``` 0.6346974057775175 ``` 这说明模型可以解释测试集上63.5%的方差。 接下来,我们可视化模型: ```python plt.scatter(X_test, y_test) plt.plot(X_test, y_pred, color='red') plt.xlabel('Area') plt.ylabel('Price') plt.show() ``` ![image-20211102225707470](https://i.loli.net/2021/11/02/1jz4sGJ7e8y6hmp.png) 可以看出,模型的拟合效果还不错。 ## 多因子模型 我们接下来以收入、房龄、房间数和面积为输入变量,建立多因子模型。 首先,我们将数据集分为训练集和测试集: ```python X = df[['area', 'income', 'age', 'rooms']] y = df['price'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 然后,我们建立线性回归模型: ```python lr = LinearRegression() lr.fit(X_train, y_train) ``` 我们可以输出回归模型的系数和截距: ```python print(lr.coef_) print(lr.intercept_) ``` 输出结果为: ``` [ 166.08167552 -1609.20087802 -66.55952222 8106.34349669] 35524.1816835563 ``` 因此,我们的多因子模型为: $$ \text{Price} = 166.08 \times \text{Area} - 1609.20 \times \text{Income} - 66.56 \times \text{Age} + 8106.34 \times \text{Rooms} + 35524.18 $$ 接下来,我们对模型进行评估。首先,我们可以输出模型在测试集上的R平方值: ```python y_pred = lr.predict(X_test) print(r2_score(y_test, y_pred)) ``` 输出结果为: ``` 0.7474287482409482 ``` 这说明模型可以解释测试集上74.7%的方差。 接下来,我们可视化模型: ```python sns.pairplot(df[['price', 'area', 'income', 'age', 'rooms']]) plt.show() plt.scatter(y_test, y_pred) plt.xlabel('True Values') plt.ylabel('Predictions') plt.show() ``` 第一张图是变量之间的散点图,第二张图是真实值与预测值之间的图,应该接近于一条直线。 ![image-20211102225815851](https://i.loli.net/2021/11/02/9R6MgHvzLJ7fC8b.png) ![image-20211102225843125](https://i.loli.net/2021/11/02/3fW8gkTMGt7HnbL.png) 可以看出,模型的拟合效果还不错。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nickdlk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值