【问题标题】:Plot RidgeCV coefficients as a function of the regularization绘制 RidgeCV 系数作为正则化的函数
【发布时间】:2020-09-01 19:48:42
【问题描述】:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import RidgeCV
tips = sns.load_dataset('tips')
X = tips.drop(columns=['tip','sex', 'smoker', 'day', 'time'])
y = tips['tip']
alphas = 10**np.linspace(10,-2,100)*0.5
ridge_clf = RidgeCV(alphas=alphas,scoring='r2').fit(X, y)
ridge_clf.score(X, y)

我想为 RidgeCV 绘制下图。我没有看到像 GridSearhCV 这样的选项。感谢您的建议!

【问题讨论】:

    标签: python matplotlib scikit-learn regression


    【解决方案1】:

    没有迹象表明颜色代表什么。我假设它们代表特征,我们研究每个特征权重的大小作为 alpha 的函数。这是我的解决方案:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from sklearn.linear_model import RidgeCV
    tips = sns.load_dataset('tips')
    X = tips.drop(columns=['tip','sex', 'smoker', 'day', 'time'])
    y = tips['tip']
    alphas = 10**np.linspace(10,-2,100)*0.5
    w = list()
    for a in alphas:
        ridge_clf = RidgeCV(alphas=[a],cv=10).fit(X, y)
        w.append(ridge_clf.coef_)
    w = np.array(w)
    plt.semilogx(alphas,w)
    plt.title('Ridge coefficients as function of the regularization')
    plt.xlabel('alpha')
    plt.ylabel('weights')
    plt.legend(X.keys())
    

    输出:

    由于您在 X 中只有两个特征,因此只有两行。

    【讨论】:

    • 我想使用RidgeCV 来执行corss-validation。 Sklearn 还记录了您提供的解决方案。执行交叉验证是一种普遍做法。
    • 更新了我的答案并添加了RidgeCV
    • 为什么要使用单个 alpha 执行交叉验证?
    【解决方案2】:

    Here 是生成您发布的图的代码。

    首先,我们需要了解RidgeCV 不会为我们在alphas 参数中输入的每个alpha 值返回coef

    拥有RidgeCV 背后的动机是它会尝试alphas 参数中提到的不同alpha 值,然后根据交叉验证评分,它会返回最佳alpha 以及拟合模型。

    因此,使用 cv 为每个 alpha 值获取 coef 的唯一方法是使用每个 alpha 值遍历 RidgeCV。

    例子:

    # Author: Fabian Pedregosa -- <fabian.pedregosa@inria.fr>
    # License: BSD 3 clause
    
    print(__doc__)
    
    import numpy as np
    import matplotlib.pyplot as plt
    from sklearn import linear_model
    
    # X is the 10x10 Hilbert matrix
    X = 1. / (np.arange(1, 11) + np.arange(0, 10)[:, np.newaxis])
    y = np.ones(10)
    
    # #############################################################################
    # Compute paths
    
    n_alphas = 200
    alphas = np.logspace(-10, -2, n_alphas)
    
    coefs = []
    for a in alphas:
        ridge = linear_model.RidgeCV(alphas=[a], fit_intercept=False, cv=3)
        ridge.fit(X, y)
        coefs.append(ridge.coef_)
    
    # #############################################################################
    # Display results
    
    ax = plt.gca()
    
    ax.plot(alphas, coefs)
    ax.set_xscale('log')
    ax.set_xlim(ax.get_xlim()[::-1])  # reverse axis
    plt.xlabel('alpha')
    plt.ylabel('weights')
    plt.title('RidgeCV coefficients as a function of the regularization')
    plt.axis('tight')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多