最强总结!十大回归类算法模型 !!!

1. 线性回归

线性回归是一种用于描述两个或多个变量之间线性关系的统计模型。假设  是响应变量(目标变量), 是解释变量(特征),线性回归模型通过拟合一条直线来预测目标变量。

原理

线性回归的基本假设是:

其中, 是截距, 是回归系数, 是误差项(即残差),假设其服从正态分布。

核心公式

线性回归的目标是通过最小化均方误差(MSE)来拟合参数:

其中, 是样本数量, 是实际值, 是预测值。

公式推导
梯度下降推导

最小化 MSE 的损失函数可以使用梯度下降法。损失函数  表示为:

其中, 是输入特征向量, 是参数向量。对  进行梯度计算:

更新规则为:

其中, 是学习率。

正规方程推导

对于小规模的数据集,线性回归可以直接通过求解解析解来找到最优参数。最小化均方误差时,损失函数的梯度为:

令其等于 0,解得:

其中, 是特征矩阵, 是目标向量。

Python实现

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# 生成虚拟数据集
np.random.seed(42)
X = np.random.rand(1000, 1) * 10  # 生成1000个0到10之间的随机数
y = 2.5 * X + np.random.randn(1000, 1) * 3  # 生成服从线性关系的y值,加上一定的噪声

# 创建线性回归模型并训练
model = LinearRegression()
model.fit(X, y)
y_pred = model.predict(X)

# 计算残差
residuals = y - y_pred

# 绘图
plt.figure(figsize=(12, 10))

# 子图1: 散点图与回归线
plt.subplot(2, 2, 1)
plt.scatter(X, y, color='blue', label='Actual Data', alpha=0.6)
plt.plot(X, y_pred, color='red', linewidth=2, label='Regression Line')
plt.title('Scatter Plot with Regression Line')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()

# 子图2: 残差图
plt.subplot(2, 2, 2)
plt.scatter(X, residuals, color='green', alpha=0.6)
plt.hlines(y=0, xmin=min(X), xmax=max(X), color='red', linestyle='--')
plt.title('Residual Plot')
plt.xlabel('X')
plt.ylabel('Residuals')

# 子图3: 预测值与实际值对比
plt.subplot(2, 2, 3)
plt.scatter(y, y_pred, color='purple', alpha=0.6)
plt.plot([min(y), max(y)], [min(y), max(y)], color='red', linestyle='--', label='Perfect Fit')
plt.title('Predicted vs Actual')
plt.xlabel('Actual y')
plt.ylabel('Predicted y')
plt.legend()

# 子图4: 残差直方图
plt.subplot(2, 2, 4)
plt.hist(residuals, bins=20, color='orange', edgecolor='black', alpha=0.7)
plt.title('Residuals Distribution')
plt.xlabel('Residuals')
plt.ylabel('Frequency')

plt.tight_layout()
plt.show()

  • 数据生成:使用 np.random.rand() 生成100个随机的自变量 ,通过  模拟线性回归数据,其中  为加入的噪声,模拟实际数据中的波动。
  • 回归模型训练:通过 LinearRegression 类对数据进行拟合,获得预测值 。
  • 残差计算:残差  用于评估模型的拟合效

  1. 散点图与回归线:展示数据及模型拟合的情况,红色回归线直观展示了线性拟合效果。
  2. 残差图:查看模型误差分布,残差应随机均匀分布在零上下。
  3. 预测值与实际值对比:检查预测结果与实际数据的拟合程度。
  4. 残差分布直方图:展示残差的分布特征,以确认误差分布的形态是否呈现正态分布。

2. Ridge 回归

岭回归是线性回归的一种改进,用于处理多重共线性问题。在普通线性回归中,如果特征之间存在较高的相关性,模型可能变得不稳定且参数估计不准确。为了解决这个问题,岭回归在损失函数中加入了  正则化项,从而限制参数的大小,防止过拟合。

原理

岭回归的目标是最小化带有正则化项的损失函数:

其中, 是正则化参数,用于控制模型的复杂度。如果  很大,模型的复杂度将受到严格约束,可能导致欠拟合;如果  很小,则正则化效果减弱,回归模型趋于普通的线性回归。

核心公式

岭回归的目标函数为:

其中, 控制正则化项的权重。

公式推导

岭回归可以通过修改线性回归的正规方程来解决。在线性回归中,参数估计公式为:

为了引入正则化,我们将目标修改为最小化:

对其求导并令其等于零,可以得到更新后的解析解:

其中, 是单位矩阵, 是正则化参数。

Python实现

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge, RidgeCV
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error

# 生成虚拟数据集
np.random.seed(42)
X = np.random.rand(1000, 5)  # 1000个样本,5个特征
y = 3 * X[:, 0] + 1.5 * X[:, 1] - 2 * X[:, 2] + np.random.randn(1000)  # 线性组合加噪声

# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 标准化特征
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# 设置不同的α值来训练岭回归模型
alphas = np.logspace(-4, 4, 100)
ridgecv = RidgeCV(alphas=alphas, store_cv_values=True)
ridgecv.fit(X_train_scaled, y_train)

# 预测
y_train_pred = ridgecv.predict(X_train_scaled)
y_test_pred = ridgecv.predict(X_test_scaled)

# 计算均方误差
mse_train = mean_squared_error(y_train, y_train_pred)
mse_test = mean_squared_error(y_test, y_test_pred)

# 岭回归系数路径
ridge_coefs = []
for alpha in alphas:
    ridge = Ridge(alpha=alpha)
    ridge.fit(X_train_scaled, y_train)
    ridge_coefs.append(ridge.coef_)

# 创建图形
fig, axs = plt.subplots(2, 2, figsize=(14, 10))

# 图1:散点图和回归曲线
axs[0, 0].scatter(X_test[:, 0], y_test, color='blue', label='True Values', s=40, alpha=0.6)
axs[0, 0].scatter(X_test[:, 0], y_test_pred, color='red', label='Predicted Values', s=40, alpha=0.6)
axs[0, 0].set_title('Scatter Plot with Regression Curve', fontsize=14)
axs[0, 0].set_xlabel('Feature 1', fontsize=12)
axs[0, 0].set_ylabel('Target', fontsize=12)
axs[0, 0].legend()

# 图2:残差图
axs[0, 1].scatter(y_test_pred, y_test_pred - y_test, color='green', s=40, alpha=0.6)
axs[0, 1].hlines(y=0, xmin=min(y_test_pred), xmax=max(y_test_pred), colors='red', linestyles='dashed')
axs[0, 1].set_title('Residual Plot', fontsize=14)
axs[0, 1].set_xlabel('Predicted Values', fontsize=12)
axs[0, 1].set_ylabel('Residuals', fontsize=12)

# 图3:岭回归系数路径
axs[1, 0].plot(alphas, ridge_coefs)
axs[1, 0].set_xscale('log')
axs[1, 0].set_title('Ridge Coefficients as a Function of the Regularization', fontsize=14)
axs[1, 0].set_xlabel('Alpha', fontsize=12)
axs[1, 0].set_ylabel('Coefficients', fontsize=12)

# 图4:MSE 曲线
cv_values_mean = np.mean(ridgecv.cv_values_, axis=0)
axs[1, 1].plot(alphas, cv_values_mean, color='purple', label='Mean CV Error')
axs[1, 1].set_xscale('log')
axs[1, 1].set_title('Mean Cross-Validation Error', fontsize=14)
axs[1, 1].set_xlabel('Alpha', fontsize=12)
axs[1, 1].set_ylabel('Mean Squared Error', fontsize=12)
axs[1, 1].legend()

plt.tight_layout()
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AAEllisonPang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值