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

文章目录

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

输出结果:

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

相关推荐
上进小菜猪4 小时前
基于 YOLOv8 的智能车牌定位检测系统设计与实现—从模型训练到 PyQt 可视化落地的完整实战方案
人工智能
AI浩4 小时前
UNIV:红外与可见光模态的统一基础模型
人工智能·深度学习
GitCode官方4 小时前
SGLang AI 金融 π 对(杭州站)回顾:大模型推理的工程实践全景
人工智能·金融·sglang
木头左4 小时前
LSTM模型入参有效性验证基于量化交易策略回测的方法学实践
人工智能·rnn·lstm
找方案5 小时前
我的 all-in-rag 学习笔记:文本分块 ——RAG 系统的 “信息切菜术“
人工智能·笔记·all-in-rag
亚马逊云开发者5 小时前
让 AI 工作空间更智能:Amazon Quick Suite 集成博查搜索实践
人工智能
腾讯WeTest5 小时前
「低成本、高质高效」WeTest AI翻译限时免费
人工智能
Lucas555555555 小时前
现代C++四十不惑:AI时代系统软件的基石与新征程
开发语言·c++·人工智能
言之。5 小时前
Claude Code 专业教学文档
人工智能
Fuly10245 小时前
大模型架构理解与学习
人工智能·语言模型