第5章 数理统计-综合实例
第5节 构建数据的曲线故事:多项式回归
在本节中,我们将介绍多项式回归(Polynomial Regression),一种用于拟合非线性数据的回归分析方法。通过多个实际的AI应用案例,我们将展示如何在不同的场景中应用多项式回归来建立精确的预测模型。每个案例不仅涵盖了算法步骤、分析和实现,还包含了详细的Python代码和注释,帮助读者更好地理解多项式回归的应用。
案例 1: 预测房价(房价与面积的非线性关系)
案例描述
在这个案例中,我们通过多项式回归来预测房价。传统的线性回归无法完全捕捉房价与房屋面积之间的关系,因为随着房屋面积的增加,房价的增长可能是非线性的。我们将使用多项式回归来拟合这种非线性关系。
案例分析
房价与房屋面积的关系可能存在某种程度的曲线效应,例如,100平方米和150平方米的房价差异可能比500平方米和550平方米的房价差异更大。为此,我们使用多项式回归来构建一个更为精准的预测模型。
案例算法步骤
- 导入所需库并加载数据集。
- 使用
PolynomialFeatures
将数据扩展为多项式特征。 - 使用线性回归模型拟合这些多项式特征。
- 绘制回归曲线并评估模型的性能。
Python代码及注释
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
# 生成模拟数据:房屋面积与房价的关系
np.random.seed(0)
X = np.random.uniform(50, 500, 100).reshape(-1, 1) # 房屋面积
y = 3 * X**2 + 100 * X + np.random.normal(0, 1000, size=(100, 1)) # 房价,包含一些噪音
# 数据可视化:房屋面积与房价的散点图
plt.scatter(X, y, color='blue')
plt.title('House Price vs Area')
plt.xlabel('Area (square meters)')
plt.ylabel('Price (USD)')
plt.show()
# 数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 1. 使用多项式特征进行扩展
poly = PolynomialFeatures(degree=4) # 创建一个4次多项式的特征转换器
X_poly_train = poly.fit_transform(X_train)
X_poly_test = poly.transform(X_test)
# 2. 训练线性回归模型
model = LinearRegression()
model.fit(X_poly_train, y_train)
# 3. 进行预测并绘制回归曲线
y_pred = model.predict(X_poly_test)
# 绘制测试集结果与预测曲线
plt.scatter(X_test, y_test, color='blue')
plt.plot(X_test, y_pred, color='red')
plt.title('Polynomial Regression: House Price Prediction')
plt.xlabel('Area (square meters)')
plt.ylabel('Price (USD)')
plt.show()
# 4. 打印模型的性能
print(f'模型的训练集得分:{model.score(X_poly_train, y_train)}')
print(f'模型的测试集得分:{model.score(X_poly_test, y_test)}')
案例 2: 预测股市趋势(股市价格波动)
案例描述
股市的价格波动常常受到多个因素的影响,其变化往往不是线性的。我们使用多项式回归来预测股票的未来走势,尤其是对于短期波动的捕捉。通过这种方式,股市的非线性关系可以被更好地模拟。
案例分析
股市的价格波动包含了多个周期性和随机性因素,直接使用线性回归往往无法捕捉股市数据的复杂非线性特征。多项式回归通过引入更高次的项,可以使模型更灵活地适应数据中的曲线变化。
案例算法步骤
- 导入数据集,并选取股市价格数据。
- 对数据进行预处理。
- 通过
PolynomialFeatures
生成多项式特征。 - 使用线性回归对多项式特征进行拟合。
- 评估模型性能并可视化结果。
Python代码及注释
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.datasets import fetch_openml
# 1. 获取股市数据:例如,模拟股票价格数据(假设来自OpenML等数据源)
# 此处使用模拟数据,真实情况可以使用`fetch_openml()`或其他API加载实际数据
days = np.arange(1, 101).reshape(-1, 1) # 100天
prices = np.sin(days * 0.1) * 100 + 50 + np.random.normal(0, 10, (100, 1)) # 模拟股市价格波动
# 2. 划分数据集为训练集和测试集
X_train, X_test = days[:80], days[80:] # 80天为训练集,20天为测试集
y_train, y_test = prices[:80], prices[80:]
# 3. 使用多项式特征扩展
poly = PolynomialFeatures(degree=5) # 使用5次多项式
X_poly_train = poly.fit_transform(X_train)
X_poly_test = poly.transform(X_test)
# 4. 训练线性回归模型
model = LinearRegression()
model.fit(X_poly_train, y_train)
# 5. 进行预测
y_pred = model.predict(X_poly_test)
# 6. 绘制股市价格预测曲线
plt.scatter(X_test, y_test, color='blue')
plt.plot(X_test, y_pred, color='red')
plt.title('Stock Market Price Prediction using Polynomial Regression')
plt.xlabel('Days')
plt.ylabel('Stock Price')
plt.show()
# 7. 打印模型得分
print(f'模型的训练集得分:{model.score(X_poly_train, y_train)}')
print(f'模型的测试集得分:{model.score(X_poly_test, y_test)}')
案例 3: 气温预测(气温与季节变化的关系)
案例描述
气温随季节变化而变化,通常表现出一定的周期性。使用多项式回归可以帮助我们拟合这一周期性关系,从而对未来的气温进行预测。
案例分析
气温的变化并非线性,特别是在季节交替时。因此,使用简单的线性回归无法准确预测气温的波动,而多项式回归能够通过更高次的项来适应季节性变化。
案例算法步骤
- 模拟生成气温数据。
- 使用
PolynomialFeatures
进行数据的多项式扩展。 - 使用多项式回归进行训练。
- 预测并评估模型。
Python代码及注释
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# 1. 模拟生成气温数据(假设以天为单位的季节性变化)
days = np.arange(1, 365).reshape(-1, 1) # 一年中的365天
temperature = 20 + 10 * np.sin(2 * np.pi * days / 365) + np.random.normal(0, 2, size=(365, 1)) # 加入噪音
# 2. 数据可视化:气温变化的图像
plt.plot(days, temperature, color='blue')
plt.title('Temperature vs Days')
plt.xlabel('Day of Year')
plt.ylabel('Temperature (°C)')
plt.show()
# 3. 划分数据集为训练集和测试集
X_train, X_test = days[:300], days[300:] # 训练集为前300天,测试集为后65天
y_train, y_test = temperature[:300], temperature[300:]
# 4. 使用多项式特征扩展
poly = PolynomialFeatures(degree=4) # 使用4次多项式
X_poly_train = poly.fit_transform(X_train)
X_poly_test = poly.transform(X_test)
# 5. 训练线性回归模型
model = LinearRegression()
model.fit(X_poly_train, y_train)
# 6. 进行预测
y_pred = model.predict(X_poly_test)
# 7. 绘制气温预测曲线
plt.plot(X_test, y_test, color='blue', label='True Temperature')
plt.plot(X_test, y_pred, color='red', label='Predicted Temperature')
plt.title('Polynomial Regression: Temperature Prediction')
plt.xlabel('Day of Year')
plt.ylabel('Temperature (°C)')
plt.legend()
plt.show()
# 8. 打印模型得分
print(f'模型的训练集得分:{model.score(X_poly_train, y_train)}')
print(f'模型的测试集得分:{model.score(X_poly_test, y_test)}')
案例 4: 预测广告效果(广告支出与销售额的非线性关系)
案例描述
在市场营销中,广告投入与销售额之间的关系往往是非线性的。过高或过低的广告支出可能不会带来预期的销售增长,因此我们使用多项式回归来模拟广告支出与销售额之间的复杂关系。
案例分析
广告效果的非线性关系通常包含了边际效应递减的特征。通过多项式回归,我们能够更好地捕捉到不同支出水平下销售额的变化趋势,特别是在广告支出过高或过低时。
案例算法步骤
- 生成广告支出与销售额的模拟数据。
- 使用多项式回归模型进行训练。
- 进行预测并可视化结果。
Python代码及注释
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# 1. 模拟广告支出与销售额的关系
np.random.seed(42)
X = np.random.uniform(1, 100, 50).reshape(-1, 1) # 广告支出(1到100单位)
y = 3 * X**2 + 20 * X + np.random.normal(0, 100, (50, 1)) # 销售额(包含噪音)
# 2. 数据可视化:广告支出与销售额的散点图
plt.scatter(X, y, color='blue')
plt.title('Ad Spend vs Sales')
plt.xlabel('Ad Spend (Units)')
plt.ylabel('Sales (Units)')
plt.show()
# 3. 划分数据集为训练集和测试集
X_train, X_test = X[:40], X[40:] # 训练集为前40个数据,测试集为后10个
y_train, y_test = y[:40], y[40:]
# 4. 使用多项式特征扩展
poly = PolynomialFeatures(degree=3) # 使用3次多项式
X_poly_train = poly.fit_transform(X_train)
X_poly_test = poly.transform(X_test)
# 5. 训练线性回归模型
model = LinearRegression()
model.fit(X_poly_train, y_train)
# 6. 进行预测
y_pred = model.predict(X_poly_test)
# 7. 绘制广告支出与销售额的预测曲线
plt.scatter(X_test, y_test, color='blue')
plt.plot(X_test, y_pred, color='red')
plt.title('Polynomial Regression: Ad Spend vs Sales')
plt.xlabel('Ad Spend (Units)')
plt.ylabel('Sales (Units)')
plt.show()
# 8. 打印模型得分
print(f'模型的训练集得分:{model.score(X_poly_train, y_train)}')
print(f'模型的测试集得分:{model.score(X_poly_test, y_test)}')
案例 5: 客户满意度预测(客户评分与服务质量的关系)
案例描述
在客户服务领域,客户的满意度评分通常与服务质量之间存在非线性关系。通过多项式回归,我们可以更准确地捕捉这种关系,从而优化客户体验。
案例分析
通常情况下,服务质量的改善会导致客户满意度的提升,但这种关系往往不是线性的。可能存在服务质量非常好时,客户满意度的提升幅度递减的现象。通过使用多项式回归,我们能够模拟这种非线性效应。
案例算法步骤
- 生成模拟数据,表示客户评分与服务质量之间的关系。
- 使用
PolynomialFeatures
将数据进行多项式扩展。 - 使用回归模型进行训练和预测。
- 可视化预测结果并评估模型性能。
Python代码及注释
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# 1. 模拟客户评分与服务质量的关系
np.random.seed(0)
X = np.random.uniform(1, 10, 100).reshape(-1, 1) # 服务质量评分(1到10)
y = -3 * X**2 + 30 * X + np.random.normal(0, 3, (100, 1)) # 客户满意度评分(包含噪音)
# 2. 数据可视化:服务质量与客户满意度评分的散点图
plt.scatter(X, y, color='blue')
plt.title('Service Quality vs Customer Satisfaction')
plt.xlabel('Service Quality (Rating)')
plt.ylabel('Customer Satisfaction (Rating)')
plt.show()
# 3. 划分数据集为训练集和测试集
X_train, X_test = X[:80], X[80:] # 训练集为前80个数据,测试集为后20个
y_train, y_test = y[:80], y[80:]
# 4. 使用多项式特征扩展
poly = PolynomialFeatures(degree=3) # 使用3次多项式
X_poly_train = poly.fit_transform(X_train)
X_poly_test = poly.transform(X_test)
# 5. 训练线性回归模型
model = LinearRegression()
model.fit(X_poly_train, y_train)
# 6. 进行预测
y_pred = model.predict(X_poly_test)
# 7. 绘制客户满意度预测曲线
plt.scatter(X_test, y_test, color='blue')
plt.plot(X_test, y_pred, color='red')
plt.title('Polynomial Regression: Service Quality vs Satisfaction')
plt.xlabel('Service Quality (Rating)')
plt.ylabel('Customer Satisfaction (Rating)')
plt.show()
# 8. 打印模型得分
print(f'模型的训练集得分:{model.score(X_poly_train, y_train)}')
print(f'模型的测试集得分:{model.score(X_poly_test, y_test)}')
总结
在本节中,我们通过多个实际案例展示了如何在不同领域中应用多项式回归。每个案例都涵盖了算法的步骤、模型的训练过程、结果的可视化以及性能评估。通过这些例子,读者可以深入理解多项式回归在实际问题中的有效应用,并学习如何通过Python实现这些模型。
多项式回归通过引入更高阶的特征,使得模型能够捕捉数据中的非线性关系。在实际应用中,选取合适的多项式阶数(degree)是关键,这通常需要通过交叉验证或模型评估来进行调优。