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

文章目录

    • [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()

输出结果:

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

相关推荐
数字护盾(和中)几秒前
终端安全破局:银狐木马防御的 EDR 核心能力详解
网络·人工智能·安全
Promise微笑3 分钟前
AI搜索时代的流量重构:Geo优化精细化运营标准与实战路径
大数据·人工智能·重构
SmallBambooCode6 分钟前
【人工智能】【Python】离线环境下huggingface预训练权重导入流程
开发语言·人工智能·python
qiyongwork7 分钟前
智能项目管理信息系统的未来图景:AI赋能下的全链路革新与生态重构
大数据·人工智能·重构
wanhengidc10 分钟前
云手机的兼容性与稳定性
大数据·运维·服务器·网络·人工智能·智能手机
昇腾CANN12 分钟前
5月12日直播丨Ascend 950 HiF8模型量化技术的训推实践
人工智能·昇腾·cann
winlife_15 分钟前
AI 怎么验证 Unity PlayMode 行为:截图 + 输入模拟的完整闭环
人工智能·unity·游戏引擎·ai编程·claude·playmode
Harvy_没救了15 分钟前
【github 爆款】Agent Skill项目全景汇报 + 联动deepseek-TUI
人工智能·github
学术小白人17 分钟前
往届EI检索稳定!第二届可信大数据与人工智能学术会议(ICTBAI 2026)
大数据·人工智能·物联网·microsoft·数字能源
阳明山水23 分钟前
MAPE仅2%为何业务仍不满意?
人工智能·深度学习·机器学习·微信·微信开放平台