gpt4 book ai didi

python - Python 中使用随机梯度下降的岭回归

转载 作者:行者123 更新时间:2023-11-30 09:51:52 25 4
gpt4 key购买 nike

我正在尝试使用随机梯度下降作为求解器在 Python 中实现岭回归的解决方案。我的 SGD 代码如下:

def fit(self, X, Y):
# Convert to data frame in case X is numpy matrix
X = pd.DataFrame(X)

# Define a function to calculate the error given a weight vector beta and a training example xi, yi

# Prepend a column of 1s to the data for the intercept
X.insert(0, 'intercept', np.array([1.0]*X.shape[0]))

# Find dimensions of train
m, d = X.shape

# Initialize weights to random
beta = self.initializeRandomWeights(d)
beta_prev = None

epochs = 0
prev_error = None
while (beta_prev is None or epochs < self.nb_epochs):
print("## Epoch: " + str(epochs))
indices = range(0, m)
shuffle(indices)
for i in indices: # Pick a training example from a randomly shuffled set
beta_prev = beta
xi = X.iloc[i]
errori = sum(beta*xi) - Y[i] # Error[i] = sum(beta*x) - y = error of ith training example
gradient_vector = xi*errori + self.l*beta_prev
beta = beta_prev - self.alpha*gradient_vector
epochs += 1

我正在测试的数据没有标准化,即使我将权重向量初始化为低值,我的实现总是以所有权重为无穷大而告终。仅当我将学习率 alpha 设置为非常小的值 ~1e-8 时,算法才会得到权重向量的有效值。

我的理解是,标准化/缩放输入特征只会有助于减少收敛时间。但如果特征没有归一化,算法整体上应该不会收敛。我的理解正确吗?

最佳答案

您可以通过scikit-learn's查看随机梯度下降文档指出该算法的缺点之一是它对特征缩放敏感。一般来说,基于梯度的优化算法在标准化数据上收敛得更快。

此外,归一化对于回归方法也是有利的。

每个步骤中系数的更新将取决于每个特征的范围。此外,正则化项将受到大特征值的严重影响。

SGD可能在没有数据标准化的情况下收敛,但这取决于手头的数据。因此,你的假设是不正确的。

关于python - Python 中使用随机梯度下降的岭回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43648957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com