机器学习(三)-多项式线性回归

文章目录

    • [1. 多项式回归理论](#1. 多项式回归理论)
    • [2. python通过多项式线性回归预测房价](#2. python通过多项式线性回归预测房价)
      • [2.1 预测数据](#2.1 预测数据)
      • 2.2导入标准库
      • [2.3 导入数据](#2.3 导入数据)
      • [2.4 划分数据集](#2.4 划分数据集)
      • [2.5 构建二次多项式特征(1, x, x^2)](#2.5 构建二次多项式特征(1, x, x^2))
      • [2.6 导入线性回归模块](#2.6 导入线性回归模块)
      • [2.7 对测试集进行预测](#2.7 对测试集进行预测)
      • [2.8 计算均方误差 J](#2.8 计算均方误差 J)
      • [2.9 计算参数 w0、w1、w2](#2.9 计算参数 w0、w1、w2)
      • [2.10 可视化训练集拟合结果](#2.10 可视化训练集拟合结果)
      • [2.11 可视化测试集拟合结果](#2.11 可视化测试集拟合结果)

1. 多项式回归理论

我来看一个例子,在这个二维平面上,横坐标是人口数量,纵坐标是房价。红色的点表示每个地区的实际人口与房价的对应关系。

我们发现如果把人口数量当成自变量X,把房价当成因变量Y,此时,y与 X 并不是呈现简单线性关系,我们无法用一条直线来拟合真实的数据。但是我们发现 y 与 x 呈现一种二次函数的关系,那我们就可以使用一个二次多项式函数的关系表达人口与房价的关系。如下图:

其损失函数表达式如下:

均方误差的表达式如下:

2. python通过多项式线性回归预测房价

2.1 预测数据

数据如下:

tex 复制代码
polulation,median_house_value
961,3.89
234,0.68
1074,3.32
1547,10.32
805,2.54
597,1.64
784,2.68
498,1.31
1602,11.43
292,0.54
1499,9.43
718,1.85
180,0.43
1202,5.23
1258,5.67
453,1.34
845,2.31
1032,3.46
384,0.68
896,3.02
425,1.02
928,2.95
1324,6.45
1435,8.54
543,1.98
1132,4.67
328,0.76
638,1.69
1389,7.23
692,2.23

x 轴是人口数量,y轴是房价

2.2导入标准库

python 复制代码
# 导入标准库
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import pandas as pd
matplotlib.use('TkAgg')

2.3 导入数据

python 复制代码
# 导入数据集
dataset = pd.read_csv('polynomial_regression_data.csv')
x = dataset.iloc[:, :-1]
y = dataset.iloc[:, 1]

2.4 划分数据集

python 复制代码
# 数据集划分 训练集/测试集
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=0)

2.5 构建二次多项式特征(1, x, x^2)

python 复制代码
# 构建二次多项式特征(1, x, x^2)
from sklearn.preprocessing import  PolynomialFeatures
poly_reg = PolynomialFeatures(degree=2)  # degree的值来调节多项式的特征
# 特征处理
X_train_poly = poly_reg.fit_transform(X_train)
X_test_poly = poly_reg.fit_transform(X_test)

2.6 导入线性回归模块

python 复制代码
# 简单线性回归算法
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train_poly, y_train)

2.7 对测试集进行预测

python 复制代码
# 对测试集进行预测
y_pred = regressor.predict(X_test_poly)

2.8 计算均方误差 J

python 复制代码
# 计算J
J = 1/X_train.shape[0] * np.sum((regressor.predict(X_train_poly) - y_train)**2)
print("J = {}".format(J))

输出结果:

tex 复制代码
J = 0.17920535084272343

2.9 计算参数 w0、w1、w2

python 复制代码
# 计算参数 w0、w1、w2
w0 = regressor.intercept_
w1 = regressor.coef_[1]
w2 = regressor.coef_[2]
print("w0 = {}, w1 = {}, w2 = {}".format(w0, w1, w2))

输出结果:

tex 复制代码
w0 = 1.1946328664527774, w1 = -0.003051980565396715, w2 = 5.5739253088970104e-06

2.10 可视化训练集拟合结果

python 复制代码
# 可视化训练集拟合结果
sorted_indices = np.argsort(X_train[:,0])
sorted_X_train = X_train[sorted_indices]
sorted_X_train_poly = poly_reg.fit_transform(sorted_X_train)
plt.figure(1)
plt.scatter(X_train, y_train, color = 'red')
plt.plot(sorted_X_train, regressor.predict(sorted_X_train_poly), "bs:")
plt.title('population VS median_house_value (training set)')
plt.xlabel('population')
plt.ylabel('median_house_value')
plt.show()

输出结果:

可以很好的看到拟合的二次多项式可以很好的表示原始数据的人口和房价的走势

2.11 可视化测试集拟合结果

python 复制代码
# 可视化测试集拟合结果
sorted_indices = np.argsort(X_test[:,0])
sorted_X_test = X_test[sorted_indices]
sorted_X_test_poly = poly_reg.fit_transform(sorted_X_test)
plt.figure(2)
plt.scatter(X_test, y_test, color = 'red')
plt.plot(sorted_X_test, regressor.predict(sorted_X_test_poly), "bs:")
plt.title('population VS median_house_value (test set)')
plt.xlabel('population')
plt.ylabel('median_house_value')
plt.show()

输出结果:

可以看到,拟合的二次多项式在测试集上的表现是相当不错了,说明我们训练的线性模型有很好的应用效果。

相关推荐
Rubin智造社15 小时前
04月17日AI每日参考:Claude Opus 4.7正式发布,智元机器人大会今日开幕
大数据·人工智能·机器学习·claude code·智元机器人·deepseek v4·claude opus 4.7
Raink老师1 天前
【AI面试临阵磨枪】详细解释 Transformer 架构的核心组件与工作流程。
人工智能·深度学习·transformer·ai 面试·ai 应用开发
qcx231 天前
【AI Agent实战】OpenClaw 安全加固完全指南:安全攻击手段与五步防护实践(2026最新)
人工智能·安全
码农小白AI1 天前
AI报告审核进入技术驱动时代:IACheck如何从规则引擎走向深度学习,构建检测报告审核“技术矩阵”
人工智能·深度学习
song150265372981 天前
视觉检测设备:自动识别缺陷、尺寸、瑕疵、装配错误,一键全检
人工智能·计算机视觉·视觉检测
智能化咨询1 天前
(163页PPT)某著名企业K3生产制造售前营销指导方案P164(附下载方式)
大数据·人工智能
Zzj_tju1 天前
大语言模型技术指南:SFT、RLHF、DPO 怎么串起来?对齐训练与关键参数详解
人工智能·深度学习·语言模型
金智维科技官方1 天前
RPA技术赋能电信运营商话单稽核:金智维如何驱动高精度自动化转型
人工智能·自动化·数字化·rpa·智能体·电信
2501_948114241 天前
2026模型能力分化加剧:多模型聚合架构的技术解析与工程落地思考
人工智能·ai·chatgpt·架构
新知图书1 天前
LangGraph中的记忆存储
人工智能·langgraph·智能体设计·多智能体设计