【正规方程对波士顿房价数据集进行预测】

数据准备

我们首先需要加载波士顿房价数据集。该数据集包含房屋特征信息和对应的房价标签。

python 复制代码
import pandas as pd
import numpy as np

data_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]

print("数据集大小:{}".format(data.shape))
print("标签大小:{}".format(target.shape))

数据划分

接下来,我们将数据集划分为训练集和测试集。

python 复制代码
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=8)

正规方程方法

正规方程是线性回归问题的闭式解,它直接计算参数的最优解而无需迭代。我们使用 LinearRegression 类来训练模型,并输出训练集和测试集上的得分、参数和截距。

python 复制代码
from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.fit(X_train, y_train)

print("正规方程训练集得分:{:.3f}".format(lr.score(X_train, y_train)))
print("正规方程测试集得分:{:.3f}".format(lr.score(X_test, y_test)))
print("正规方程参数:{}".format(lr.coef_))
print("正规方程截距:{:.3f}".format(lr.intercept_))

模型评估

我们使用均方误差和均方根误差来评估模型的性能。

python 复制代码
from sklearn.metrics import mean_squared_error

y_pred = lr.predict(X_test)

print("正规方程均方误差:{:.3f}".format(mean_squared_error(y_test, y_pred)))
print("正规方程均方根误差:{:.3f}".format(np.sqrt(mean_squared_error(y_test, y_pred))))

可视化

最后,我们将真实值和预测值进行可视化比较,以便更直观地了解模型的拟合效果。

python 复制代码
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 6))
plt.plot(range(len(y_test)), y_test, "r", label="y_test")
plt.plot(range(len(y_pred)), y_pred, "g--", label="y_pred")
plt.legend()
plt.show()
相关推荐
想你依然心痛12 小时前
ModelEngine·AI 应用开发实战:从智能体到可视化编排的全栈实践
人工智能·智能体·ai应用·modelengine
KIKIiiiiiiii12 小时前
微信个人号API二次开发中的解决经验
java·人工智能·python·微信
哈哈你是真的厉害12 小时前
解构 AIGC 的“核动力”引擎:华为 CANN 如何撑起万亿参数的大模型时代
人工智能·aigc·cann
Ekehlaft12 小时前
这款国产 AI,让 Python 小白也能玩转编程
开发语言·人工智能·python·ai·aipy
哈__13 小时前
CANN多模型并发部署方案
人工智能·pytorch
予枫的编程笔记13 小时前
【Linux入门篇】Linux运维必学:Vim核心操作详解,告别编辑器依赖
linux·人工智能·linux运维·vim操作教程·程序员工具·编辑器技巧·新手学vim
慢半拍iii13 小时前
对比分析:ops-nn与传统深度学习框架算子的差异
人工智能·深度学习·ai·cann
心疼你的一切13 小时前
解构CANN仓库:AIGC API从底层逻辑到实战落地,解锁国产化AI生成算力
数据仓库·人工智能·深度学习·aigc·cann
啊阿狸不会拉杆13 小时前
《机器学习导论》第 5 章-多元方法
人工智能·python·算法·机器学习·numpy·matplotlib·多元方法
薯一个蜂蜜牛奶味的愿13 小时前
模块化显示神经网络结构的可视化工具--BlockShow
人工智能·深度学习·神经网络