【发布时间】:2017-09-24 17:28:09
【问题描述】:
我正在尝试使用随机梯度下降作为求解器在 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 时,算法才会以权重向量的有效值结束。
我的理解是,规范化/缩放输入特征只会有助于减少收敛时间。但是如果特征没有被归一化,算法应该不会不能作为一个整体收敛。我的理解正确吗?
【问题讨论】:
标签: python optimization machine-learning linear-regression gradient-descent