作为作业的一部分,我被要求实现随机梯度下降以解决线性回归问题(即使我只有 200 个训练示例)。我的问题是随机梯度下降收敛太平滑,几乎与批量梯度下降完全一样,这让我想到了我的问题:考虑到通常它更嘈杂的事实,为什么它看起来如此平滑。是因为我只用了 200 个例子吗?
收敛图:
具有随机梯度下降权重的 MSE:2.78441258841
权重来自梯度下降的 MSE:2.78412631451(与权重来自正规方程的 MSE 相同)
我的代码:
def mserror(y, y_pred):
n = y.size
diff = y - y_pred
diff_squared = diff ** 2
av_er = float(sum(diff_squared))/n
return av_er
.
def linear_prediction(X, w):
return dot(X,np.transpose(w))
.
def gradient_descent_step(X, y, w, eta):
n = X.shape[0]
grad = (2.0/n) * sum(np.transpose(X) * (linear_prediction(X,w) - y), axis = 1)
return w - eta * grad
.
def stochastic_gradient_step(X, y, w, train_ind, eta):
n = X.shape[0]
grad = (2.0/n) * np.transpose(X[train_ind]) * (linear_prediction(X[train_ind],w) - y[train_ind])
return w - eta * grad
.
def gradient_descent(X, y, w_init, eta, max_iter):
w = w_init
errors = []
errors.append(mserror(y, linear_prediction(X,w)))
for i in range(max_iter):
w = gradient_descent_step(X, y, w, eta)
errors.append(mserror(y, linear_prediction(X,w)))
return w, errors
.
def stochastic_gradient_descent(X, y, w_init, eta, max_iter):
n = X.shape[0]
w = w_init
errors = []
errors.append(mserror(y, linear_prediction(X,w)))
for i in range(max_iter):
random_ind = np.random.randint(n)
w = stochastic_gradient_step(X, y, w, random_ind, eta)
errors.append(mserror(y, linear_prediction(X,w)))
return w, errors