导包
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
房价数据
image.png
根据各影响房价的因素画图
image.png
单因子房价预测
根据房间面积做房价的线性回归
# 面积形状转换,价格
x = np.array(df["size"]).reshape(-1, 1)
y = df["Price"]
#线性回归模型进行训练
lr1 = LinearRegression()
lr1.fit(x, y)
# 根据面积预测房价
y_predict1 = lr1.predict(x)
#计算均方误差和r2
err1 = mean_squared_error(y, y_predict1)
r1 = r2_score(y, y_predict1)
画出真实值和预测值的离散关系图
image.png
多因子房价预测
#去掉房价列
x_multy = df.drop(["Price"], axis=1)
# 模型训练
line_mul = LinearRegression()
line_mul.fit(x_multy, y)
# 模型预测
y_predict_mul = line_mul.predict(x_multy)
# 均方误差和r2
mean_mul = mean_squared_error(y, y_predict_mul)
r2_mul = r2_score(y, y_predict_mul)
画出真实值和多因子预测值
image.png
网友评论