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

文章目录

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

输出结果:

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

相关推荐
Nexmoe几秒前
关于 Serverless 的思考:为什么国内外差距如此之大?
人工智能
magic 2453 分钟前
第一章:认识AI
人工智能
算AI7 分钟前
当无人机遇上Agentic AI:新的应用场景及挑战
人工智能·算法
玩转AGI7 分钟前
Coze篇-搭建情感陪聊智能体
人工智能·llm·coze
硬核隔壁老王7 分钟前
MCP篇-一文讲透 MCP原理
人工智能·llm·mcp
MarkGosling8 分钟前
【开源项目】解放小爱音箱!用XiaoMusic打造你的私人无限曲库
人工智能·python·音视频开发
LLM大模型9 分钟前
LangGraph篇-检查点与Send机制
人工智能·程序员·llm
DeepSeek忠实粉丝11 分钟前
微调篇--Stable Diffusion模型微调
人工智能·程序员·llm
moton201733 分钟前
计算机视觉(Computer Vision, CV)
机器学习·cv
belldeep1 小时前
AI 生成 短视频 全流程指南
人工智能·短视频