python - 为什么我的 L1 正则化实现性能不佳?
问题描述
我正在关注关于神经网络的在线教程,neuralnetworksanddeeplearning.com作者 Nielsen 在代码中实现了 L2 正则化,作为本教程的一部分。现在他要求我们修改代码,使其使用 L1 正则化而不是 L2。此链接将带您直接进入我正在谈论的教程部分。
尼尔森在 python 中这样实现它:
self.weights = [(1-eta*(lmbda/n))*w-(eta/len(mini_batch))*nw
for w, nw in zip(self.weights, nabla_w)]
具有 L1 正则化的更新规则变为:
我尝试按如下方式实现它:
self.weights = [(w - eta* (lmbda/len(mini_batch)) * np.sign(w) - (eta/len(mini_batch)) * nw)
for w, nw in zip(self.weights, nabla_w)]
突然间,我的神经网络的分类准确率为 +- 机会……这怎么可能?我在实施 L1 正则化时犯了错误吗?我有一个包含 30 个隐藏神经元的神经网络,学习率为 0.5,lambda = 5.0。当我使用 L2 正则化时,一切都很好。
为了您的方便,请在此处找到完整的更新功能:
def update_mini_batch(self, mini_batch, eta, lmbda, n):
"""Update the network's weights and biases by applying gradient
descent using backpropagation to a single mini batch. The
``mini_batch`` is a list of tuples ``(x, y)``, ``eta`` is the
learning rate, ``lmbda`` is the regularization parameter, and
``n`` is the total size of the training data set.
"""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x, y in mini_batch:
delta_nabla_b, delta_nabla_w = self.backprop(x, y)
nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
self.weights = [(1-eta*(lmbda/n))*w-(eta/len(mini_batch))*nw
for w, nw in zip(self.weights, nabla_w)]
self.biases = [b-(eta/len(mini_batch))*nb
for b, nb in zip(self.biases, nabla_b)]
解决方案
你做错了数学。您要实现的公式的代码翻译是:
self.weights = [
(w - eta * (lmbda / n) * np.sign(w) - eta * nabla_b[0])
for w in self.weights]
两个必需的修改是:
- 消除对小批量大小的依赖
- 仅使用第一个nabla系数
推荐阅读
- android-studio -
尝试导航到 android studio 中的其他片段时出现 BoomMenu 错误 - python - 我有我在一本旧的 ML 书中找到的这个片段,我想问一下这个函数是否正确
- reactjs - 如何在反应中通过两个参数实现过滤
- java - Java:用于匹配引号之间的单词的正则表达式
- r - 使用 gganimate 并得到各种错误
- c# - 想填一个
从字典填充 ToggleButtons - mattermost - Mattermost API 使用 powershell 创建直接消息通道
- postgresql - 使用 terraform 创建只读 postgres 用户
- python - djangorestframework ModelSerializer 序列化模型对象但数据为空{}
- python - 为什么当python后台另一个值发生变化时输入命令不起作用