Python中使用随机梯度下降的岭回归
我试图用Python实现一个岭回归的解决方案,使用随机梯度下降作为解算器。我的新加坡元代码如下:Python中使用随机梯度下降的岭回归,python,optimization,machine-learning,linear-regression,gradient-descent,Python,Optimization,Machine Learning,Linear Regression,Gradient Descent,我试图用Python实现一个岭回归的解决方案,使用随机梯度下降作为解算器。我的新加坡元代码如下: 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,
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
def配合(自身、X、Y):
#X为numpy矩阵时转换为数据帧
X=pd.DataFrame(X)
定义一个函数,计算权重向量β和训练实例席,
#在截取数据前加一列1
X.insert(0,'intercept',np.array([1.0]*X.shape[0]))
#查找列车的尺寸
m、 d=X.形状
#将权重初始化为随机
beta=自初始化器权重(d)
beta_prev=无
纪元=0
上一个错误=无
而(beta_prev为无或epochs
我正在测试的数据没有标准化,我的实现总是以所有权重为无穷大结束,即使我将权重向量初始化为低值。只有当我将学习速率alpha设置为一个非常小的值~1e-8时,算法才会得到有效的权重向量值
我的理解是,规范化/缩放输入功能只会有助于缩短收敛时间。但是,如果特征没有被规范化,该算法不应该不能作为一个整体收敛。我的理解正确吗?你的假设不正确 很难回答这个问题,因为有太多不同的方法/环境,但我将尝试提及一些要点 规范化
- 当某些方法不是标度不变的(我认为每个线性回归都不是)时,你真的应该规范化你的数据
- 我认为您只是因为调试/分析而忽略了这一点
- 规范化数据不仅与收敛时间有关,结果也会有所不同(请考虑损失函数中的影响;大值可能会对小值造成更大的损失)李>
- 关于许多方法在规范化/非规范化数据上的收敛性,可能有很多需要说明的地方,但您的情况很特殊:
- SGD的收敛理论仅保证在某些超参数选择(学习速率和学习进度/衰减)下收敛到某个局部最小值(=凸opt问题中的全局最小值)
- 当这些参数不好时,即使使用SGD优化规范化数据也可能失败!
- 这是新加坡元最重要的缺点之一;对超参数的依赖
- 由于SGD是基于梯度和步长的,非规范化数据可能会对无法实现这种收敛产生巨大影响李>