1.首先是单因子线性回归预测房价
python
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# 1.读取csa房屋数据
path = 'D:/pythonDATA/usa_housing_price.csv'
house_data = pd.read_csv(path)
print(house_data.head())
# 2.显示每个因子和房价的散点图
plt.figure(figsize=(18, 12))
fig1 = plt.subplot(231)
plt.scatter(house_data['Avg. Area Income'], house_data['Price']) # 第一个子图平均收入和房价
plt.title('Income vs Price')
fig2 = plt.subplot(232)
plt.scatter(house_data['Avg. Area House Age'], house_data['Price']) # 第二个子图房子平均年龄和房价
plt.title('House Age vs Price')
fig3 = plt.subplot(233)
plt.scatter(house_data['Avg. Area Number of Rooms'], house_data['Price']) # 第三个子图房子所居人数
plt.title('Number of Rooms vs Price')
fig4 = plt.subplot(234)
plt.scatter(house_data['Area Population'], house_data['Price']) # 第四个子图地区人口
plt.title('Area Population vs Price')
fig5 = plt.subplot(235)
plt.scatter(house_data['size'], house_data['Price']) # 第五个子图房屋大小
plt.title('size vs Price')
plt.show()
# 3.先用size这个单因子和房价进行拟合训练,进行预测房价
X = house_data.loc[:, 'size']
y = house_data.loc[:, 'Price']
print(type(X))
# 4.将变量size通过numpy转为二维数组
X = np.array(X).reshape(-1, 1)
# 5.建立线性回归模型,对X和y进行拟合(拟合可得到线性回归公式也就是得到a和b,接下来就可以对应进行预测)
lr1 = LinearRegression()
lr1.fit(X, y)
# 6.通过得到的拟合方程对X进行预测
y_predict_1 = lr1.predict(X)
print(y_predict_1)
# 7.模型评估(MSE和R2)
mse_1 = mean_squared_error(y, y_predict_1)
r2_1 = r2_score(y, y_predict_1)
print("MSE评估:" + mse_1.__str__())
print("R2评估:" + r2_1.__str__()) # 预测为0.1,效果并不好
# 8.对预测值进行可视化
plt.figure(figsize=[8, 6])
plt.scatter(X, y) # 真实标签的绘图
plt.plot(X, y_predict_1, 'r') # 预测数据线性的绘图
plt.show()
效果如下所示:
2.多因子线性回归评估
python
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# 1.读取csa房屋数据
path = 'D:/pythonDATA/usa_housing_price.csv'
house_data = pd.read_csv(path)
print(house_data.head()) # data.head()预览数据
# 2.多因子变量(本身就是二维,无需再np.array().reshape了)
X_multi = house_data.drop(['Price'], axis=1) # 去掉Price所在列,其余5个为输入变量
# X_multi = np.array(X_multi).reshape(-1, -1)
y = house_data.loc[:, 'Price']
print(X_multi)
# 3.建立模型对X和y进行拟合(得到线性回归方程)
LR_multi = LinearRegression()
LR_multi.fit(X_multi, y)
# 4.利用拟合的方程对X_multi进行模型预测
y_predict_multi = LR_multi.predict(X_multi)
print("y预测数据\n")
print(y_predict_multi)
# 5.模型评估
mse_multi = mean_squared_error(y, y_predict_multi)
r2_multi = r2_score(y, y_predict_multi)
print("MSE评估:" + mse_multi.__str__())
print("R2评估:" + r2_multi.__str__())
# 6.图形评估(多因子X_multi不能与y绘制scatter)
fig6 = plt.figure(figsize=(9, 6))
plt.scatter(y, y_predict_multi) # 接近1:1说明比较准确
plt.show()
# 7.捏造一条数据并进行预测(平均收入,房子使用年龄,房子居住人数,社区人口数,房子大小)
X_test = [66000, 3, 6, 20000, 150]
X_test = np.array(X_test).reshape(1, -1) # 将输入数据转化为数组(1,-1)1行n列
print(X_test)
y_test_predict = LR_multi.predict(X_test)
print(y_test_predict)
效果如下所示: