多因子房价预测

一:影响房屋价格因素

  • 地区平均收入
  • 房屋平均年龄
  • 房屋房间数量
  • 地区人口数量
  • 房屋尺寸大小

二:实现目标

基于 housing_price.csv 数据,建立线性回归模型,预测合理房价:

  1. 以面积为输入变量,建立单因子模型,评估模型表现,可视化线性回归预测结果
  2. 以收入、房屋年龄、房间数量、人口数量、房屋尺寸为输入变量,建立多因子模型,评估表现
  3. 预测 收入=65000,房屋年龄=5,房间数量=5,人口数量=30000,房间尺寸=200的合理房价

三:代码实现

1. 加载数据

1
2
3
4
5
# load the data
import pandas as pd
import numpy as np
data = pd.read_csv('housing_price.csv')
data.head()

2. 可视化数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# visualizing data
# 内嵌绘图,可省略 plt.show() 这一步
%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')

fig2 = 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() # 可以省略

3. 建立单因子模型(面积)

(1)定义 X、Y

X:影响因素;Y:结果值

1
2
3
4
# define x and y
X = data.loc[:,'size']
y = data.loc[:,'Price']
y.head()

(2)建立回归模型

1
2
3
4
5
6
7
8
# set up the linear regression model
from sklearn.linear_model import LinearRegression
LR1 = LinearRegression()
# reshape data
X = np.array(X).reshape(-1,1)
print(X.shape)
# train the model
LR1.fit(X,y)

(3)模型预测

1
2
3
# calulate the price vs size 
y_predict_1 = LR1.predict(X)
print(y_predict_1)

(4)模型评估

1
2
3
4
5
# evaluate the model
from sklearn.metrics import mean_squared_error,r2_score
mean_squared_error_1 = mean_squared_error(y,y_predict_1)
r2_score_1 = r2_score(y,y_predict_1)
print(mean_squared_error_1,r2_score_1)

(5)可视化预测结果

1
2
3
4
5
# visualizing predict result
fig_res = plt.figure(figsize=(8,5))
plt.scatter(X,y)
plt.plot(X,y_predict_1,'r') # 红线表示
plt.show()

4. 建立多因子模型

(1)定义多因子 X

1
2
3
# define X_multi
X_multi = data.drop(['Price'],axis=1) # 排除Price列,axis=1 表示横轴从左往右
X_multi

(2)建立多因子回归模型

1
2
3
4
# set up 2nd linear regression model
LR_multi = LinearRegression()
# train the model
LR_multi.fit(X_multi,y)

(3)模型预测

1
2
3
# make prediction
y_predict_multi = LR_multi.predict(X_multi)
print(y_predict_multi)

(4)模型评估

1
2
3
4
# evaluate the model
mean_squared_error_multi = mean_squared_error(y,y_predict_multi)
r2_score_multi = r2_score(y,y_predict_multi)
print(mean_squared_error_multi,r2_score_multi)

(5)可视化预测结果

1
2
3
4
# visualizing predict result
fig_multi = plt.figure(figsize=(8,5))
plt.scatter(y,y_predict_multi)
plt.show()

5. 规定因素值预测

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

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