【问题标题】:How can I implement the momentum variant of stochastic gradient descent in sklearn如何在 sklearn 中实现随机梯度下降的动量变体
【发布时间】:2021-09-28 11:04:55
【问题描述】:

我已在线阅读文档和各种资源,但我不确定如何在 sklearn 中为线性回归模型实现 SGD 的动量变体。任何让我开始的帮助将不胜感激。

from sklearn import linear_model
from sklearn.datasets import load_boston
X,y = load_boston().data,load_boston().target
clf = linear_model.SGDRegressor(loss='squared_loss',penalty='l2',alpha=0.01,max_iter=1000)
clf.fit(X, y)
print('Score:',clf.score(X,y))
print('Regression coefficients:',clf.coef_)
print('deviation:',clf.intercept_ )

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    一种解决方法是使用不带隐藏层的MLPRegressor,这与执行LinearRegression 相同。

    这将允许您使用SGD 的动量变化,例如adam

    你可以这样做:

    from sklearn.neural_network import MLPRegressor
    
    from sklearn.datasets import make_regression
    from sklearn.model_selection import train_test_split
    
    X, y = make_regression(n_samples=5_000, random_state=1, n_features=10)
    X_train, X_test, y_train, y_test = train_test_split(X, y)
    
    clf = MLPRegressor(solver='adam',
                        alpha=0.01,
                        max_iter=5000,
                        hidden_layer_sizes=(),
                       )
    
    
    clf.fit(X_train, y_train)
    print('Score:',clf.score(X_test,y_test))
    print('Regression coefficients:',clf.coefs_[0])
    print('deviation:',clf.intercepts_ [0])
    

    【讨论】:

    • 非常感谢!这是一个很好的答案!此外,关于参数“动量”,根据 MLPRegressor 的文档,它在 0 到 1 之间,默认为 0.9。你知道 0 - 1 值实际上代表什么吗?
    • 您可以将动量视为先前梯度的一种移动平均线。动量=0.9,您正在考虑下一个 sgd 步骤过去 10 次更新。使用 0,您没有任何信息,这意味着更新只是参数的导数。
    猜你喜欢
    • 2016-09-25
    • 2021-02-20
    • 2019-08-28
    • 2018-07-14
    • 2017-02-12
    • 2011-07-04
    • 1970-01-01
    • 2016-06-13
    • 2017-02-19
    相关资源
    最近更新 更多