我正在尝试实现一个带有两个约束条件的随机梯度下降法,因此无法使用scikit-learn。不幸的是,即使没有这两个约束条件,我在实现常规的SGD时也遇到了困难。训练集上的损失(平方损失)在几次迭代后下降,但一段时间后开始增加,如图所示。这些是我使用的函数:
def loss_prime_simple(w,node,feature,data): x = data[3] y = data[2] x_f = x[node][feature] y_node = y[node] ret = (y_node - w[feature] * x_f) * (-x_f) return retdef update_weights(w,data,predecs,children,node, learning_rate): len_features = len(data[3][0]) w_new = np.zeros(len_features) for feature_ in range(len_features): w_new[feature_] = loss_prime_simple(w,node,feature_,data) return w - learning_rate * w_newdef loss_simple(w,data): y_p = data[2] x = data[3] return ((y_p - np.dot(w,np.array(x).T)) ** 2).sum()
这显示了训练集上使用两种不同学习率(0.001, 0.0001)的损失情况 http://postimg.org/image/43nbmh8x5/
有谁能找到错误或提供调试建议吗?谢谢
编辑:
正如@lejlot指出的那样,最好能提供数据。这是我用于x的数据(单个样本):http://textuploader.com/5x0f1
y=2
这给出的损失情况是:http://postimg.org/image/o9d97kt9v/
更新后的代码:
def loss_prime_simple(w,node,feature,data): x = data[3] y = data[2] x_f = x[node][feature] y_node = y[node] return -(y_node - w[feature] * x_f) * x_fdef update_weights(w,data,predecs,children,node, learning_rate): len_features = len(data[3][0]) w_new = np.zeros(len_features) for feature_ in range(len_features): w_new[feature_] = loss_prime_simple(w,node,feature_,data) return w - learning_rate * w_newdef loss_simple2(w,data): y_p = data[2] x = data[3] return ((y_p - np.dot(w,np.array(x).T)) ** 2).sum()import numpy as npX = [#put array from http://textuploader.com/5x0f1 here]y = [2]data = None, None, y, Xw = np.random.rand(4096)a = [ loss_simple2(w, data) ]for _ in range(200): for j in range(X.shape[0]): w = update_weights(w,data,None,None,j, 0.0001) a.append( loss_simple2(w, data) )from matplotlib import pyplot as pltplt.figure()plt.plot(a)plt.show()
回答:
所以这样可以工作:
def update_weights(w,x,y, learning_rate): inner_product = 0.0 for f_ in range(len(x)): inner_product += (w[f_] * x[f_]) dloss = inner_product - y for f_ in range(len(x)): w[f_] += (learning_rate * (-x[f_] * dloss)) return w