为什么需要使用正则化技术来防止过拟合

为什么需要使用正则化技术来防止过拟合?

过拟合是指模型在训练集上表现出色,但在新数据上的预测性能较差的情况。这是由于模型过于复杂,以至于每个训练样本的细微变化都会被模型捕捉到,导致模型无法泛化到新数据。为了解决过拟合问题,我们需要采取一些方法,其中之一是正则化技术。

正则化技术通过对模型的权重进行约束,限制其值的范围,从而减小模型的复杂性。这可以防止模型对训练集中的噪声和异常值过于敏感,从而提高模型的泛化能力。

正则化技术的算法原理

正则化技术的一种常见方法是L2正则化(岭回归)算法。

L2正则化通过向损失函数添加一个正则化项,以惩罚较大的权重。这个正则化项由权重的平方和乘以一个正则化参数(lambda)决定。通过调整lambda的值,我们可以控制正则化对模型的影响程度。

公式推导

假设我们的线性模型为:
$$
y = w_1x_1 + w_2x_2 + … + w_nx_n + b
$$

损失函数为平方损失函数:
$$
L = \frac{1}{2}\sum_{i=1}^{m}(y_i – \hat{y_i})^2
$$

在L2正则化中,我们将正则化项添加到损失函数中:
$$
L_{reg} = L + \frac{\lambda}{2}\sum_{i=1}^{n}w_i^2
$$

其中,lambda是正则化参数。

为了减小损失函数,我们需要计算损失函数对权重的偏导数:
$$
\frac{\partial L_{reg}}{\partial w_i} = \frac{\partial L}{\partial w_i} + \lambda w_i
$$

计算步骤

  1. 定义线性模型的结构和参数
  2. 定义损失函数,包括正则化项
  3. 计算损失函数对权重的偏导数
  4. 使用梯度下降等优化算法来更新权重
  5. 反复迭代直至收敛

复杂Python代码示例

下面是一个使用L2正则化的线性回归的Python示例代码:

import numpy as np

# 生成虚拟数据
np.random.seed(0)
X = np.random.rand(100, 1)
y = 4 + 3 artical cgpt2md_gpt.sh cgpt2md_johngo.log cgpt2md_johngo.sh cgpt2md.sh _content1.txt _content.txt current_url.txt history_url history_urls log nohup.out online pic.txt seo test.py topic_gpt.txt topic_johngo.txt topic.txt upload-markdown-to-wordpress.py urls X + np.random.randn(100, 1)

# 添加偏置项
X_b = np.c_[np.ones((100, 1)), X]

# 定义参数和学习率
theta = np.random.randn(2, 1)
lr = 0.1
lambda_ = 0.1

# 梯度下降
for epoch in range(1000):
 gradients = 1/len(X_b) artical cgpt2md_gpt.sh cgpt2md_johngo.log cgpt2md_johngo.sh cgpt2md.sh _content1.txt _content.txt current_url.txt history_url history_urls log nohup.out online pic.txt seo test.py topic_gpt.txt topic_johngo.txt topic.txt upload-markdown-to-wordpress.py urls X_b.T.dot(X_b.dot(theta) - y) + lambda_/len(X_b) artical cgpt2md_gpt.sh cgpt2md_johngo.log cgpt2md_johngo.sh cgpt2md.sh _content1.txt _content.txt current_url.txt history_url history_urls log nohup.out online pic.txt seo test.py topic_gpt.txt topic_johngo.txt topic.txt upload-markdown-to-wordpress.py urls np.r_[[[0]], theta[1:]]
 theta = theta - lr artical cgpt2md_gpt.sh cgpt2md_johngo.log cgpt2md_johngo.sh cgpt2md.sh _content1.txt _content.txt current_url.txt history_url history_urls log nohup.out online pic.txt seo test.py topic_gpt.txt topic_johngo.txt topic.txt upload-markdown-to-wordpress.py urls gradients

# 打印最终的参数
print(theta)

首先,我们通过numpy.random生成一个虚拟数据集Xy。然后,我们添加一个全为1的偏置项到特征矩阵X中。

接下来,我们定义模型的参数theta和学习率lr,以及正则化参数lambda_。在每个迭代步骤中,我们计算梯度,并根据梯度和学习率更新参数theta

最后,打印出最终学到的参数theta

代码细节解释

  • 行1:导入必要的库。
  • 行4-6:生成一个100×1的随机数组X和对应的标签y,并添加随机噪声。
  • 行9:将全为1的列添加到特征矩阵X中。
  • 行12-15:定义模型的参数theta、学习率lr和正则化参数lambda_
  • 行18-21:使用梯度下降算法更新参数theta。其中,gradients计算了损失函数对权重的偏导数,并添加了正则化项。
  • 行24:打印最终学得的参数theta

这个示例展示了如何使用L2正则化技术来防止线性回归模型的过拟合。正则化项惩罚权重较大的模型,使其更加平滑,提高了模型泛化能力。

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/822393/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球