机器学习-多因子线性回归

以Income、House age、Numbers Of Rooms、Population、Area为输入变量,建立多因子模型,预测合理房价price,评估模型表现。

代码如下:

python 复制代码
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import  mean_squared_error,r2_score
from matplotlib import pyplot as plt

data=pd.read_csv('usa_housing_price.csv')
fig = plt.figure(figsize=[10,10])

fig1=plt.subplot(2,3,1)  # 表示2行3列,第1个图
plt.scatter(data.loc[:,'Avg.Area Income'],data.loc[:,'Price'])
plt.title('Price vs Area Income')

fig2=plt.subplot(2,3,2)  # 表示2行3列,第2个图
plt.scatter(data.loc[:,'Avg.Area House Age'],data.loc[:,'Price'])
plt.title('Price vs House Age')

fig3=plt.subplot(2,3,3)  # 表示2行3列,第3个图
plt.scatter(data.loc[:,'Avg.Area Number of Rooms'],data.loc[:,'Price'])
plt.title('Price vs Avg.Area Number of Rooms')

# fig4=plt.subplot(2,3,4)  # 表示2行3列,第4个图
# plt.scatter(data.loc[:,'Area Population'],data.loc[:,'Price'])
# plt.title('Price vs Area Population')

fig5=plt.subplot(2,3,5)  # 表示2行3列,第5个图
plt.scatter(data.loc[:,'size'],data.loc[:,'Price'])
plt.title('Price vs size')
plt.show()

Y=data.loc[:,'Price']
# define X_multi
X_multi =data.drop(['Price'],axis=1) # 除了Price的变量都放入X_multi,不需要reshape
# set up 2nd linear model
LR_multi=LinearRegression()

LR_multi.fit(X_multi,Y)
# make prediction
y_predict_multi=LR_multi.predict(X_multi)
print(y_predict_multi)

# 模型评估
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)

fig6=plt.figure(figsize=[8,5])
plt.scatter(Y,y_predict_multi) # 拟合真实Y和预测Y关系图像
plt.show()

# 使用模型进行预测Price
x_test=[65000,5,5,30000,200]
x_test=np.array(x_test).reshape(1,-1)
y_test_predict=LR_multi.predict(x_test)
print("预测房价",y_test_predict)

数据如图:


输出结果:

单因子与价格(Price)关系图:

真实Y和预测Y关系图:

相关推荐
波动几何26 分钟前
CAD制图编辑器cad-editor
人工智能
耿雨飞6 小时前
第三章:LangChain Classic vs. 新版 LangChain —— 架构演进与迁移指南
人工智能·架构·langchain
BizViewStudio7 小时前
甄选 2026:AI 重构新媒体代运营行业的三大核心变革与落地路径
大数据·人工智能·新媒体运营·媒体
俊哥V7 小时前
AI一周事件 · 2026年4月8日至4月14日
人工智能·ai
GitCode官方7 小时前
G-Star Gathering Day 杭州站回顾
人工智能·开源·atomgit
宇擎智脑科技8 小时前
开源 AI Agent 架构设计对比:Python 单体 vs TypeScript 插件化
人工智能·openclaw·hermes agent
冷色系里的一抹暖调9 小时前
OpenClaw Docker部署避坑指南:服务启动成功但网页打不开?
人工智能·docker·容器·openclaw
曹牧9 小时前
自动编程AI落地方案‌
人工智能
天云数据9 小时前
Harness革命:企业级AI从“失控野马”到“价值引擎”的跃迁
人工智能
汽车仪器仪表相关领域9 小时前
NHVOC-70系列固定污染源挥发性有机物监测系统:精准破局工业VOCs监测痛点,赋能环保合规升级
大数据·人工智能·安全性测试