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

文章目录

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

输出结果:

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

相关推荐
代码AI弗森21 小时前
从 IDE 到 CLI:AI 编程代理工具全景与落地指南(附对比矩阵与脚本化示例)
ide·人工智能·矩阵
xchenhao1 天前
SciKit-Learn 全面分析分类任务 breast_cancer 数据集
python·机器学习·分类·数据集·scikit-learn·svm
007tg1 天前
从ChatGPT家长控制功能看AI合规与技术应对策略
人工智能·chatgpt·企业数据安全
Memene摸鱼日报1 天前
「Memene 摸鱼日报 2025.9.11」腾讯推出命令行编程工具 CodeBuddy Code, ChatGPT 开发者模式迎来 MCP 全面支持
人工智能·chatgpt·agi
linjoe991 天前
【Deep Learning】Ubuntu配置深度学习环境
人工智能·深度学习·ubuntu
先做个垃圾出来………1 天前
残差连接的概念与作用
人工智能·算法·机器学习·语言模型·自然语言处理
AI小书房1 天前
【人工智能通识专栏】第十三讲:图像处理
人工智能
fanstuck1 天前
基于大模型的个性化推荐系统实现探索与应用
大数据·人工智能·语言模型·数据挖掘
多看书少吃饭1 天前
基于 OpenCV 的眼球识别算法以及青光眼算法识别
人工智能·opencv·计算机视觉