【问题标题】:Why do my python sklearn logistic regression results differ from this example?为什么我的 python sklearn 逻辑回归结果与此示例不同?
【发布时间】:2019-12-03 18:23:29
【问题描述】:

我在维基百科中找到了以下示例

但是,当我使用 sklearn 时,我的结果有所不同。

from sklearn.linear_model import 
LogisticRegression
hours1=  [0.50,0.75,1.00, 
1.25,1.50,1.75,1.75,2.00,2.25, 
2.50,2.75,3.00,3.25,3.50,4.00,
4.25,4.50,
4.75,5.00,5.50]
len(hours1)
pass1=[0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1]
len(pass1)

X_train=np.array([hours1])
y_train=np.array([pass1])
X_train.shape=(20,1)
y_train.shape=(20,)
clf= 
LogisticRegression(random_state=0).fit(X_train, 
y_train)
print("coef_ is", clf.coef_)
print("intercept_ is" ,clf.intercept_)

# my results are
coef_ is [[0.61126347]]
intercept_ is [-1.36550178]

有人可以帮助解释我如何获得与this wiki page 上显示的相同的结果。

【问题讨论】:

    标签: python scikit-learn intercept


    【解决方案1】:

    您需要通过调整参数来优化模型。

    • 由于您的数据集很小,您需要指定好的算法进行优化。对于小数据集lbfgs 是一个不错的选择。
    • 另一个重要的参数是inverse of regularization strength,在sklearn中是C。在sklearn中C的默认值是1.0。如果你像这样对不同的C值运行一个小测试

    例如

    from sklearn.linear_model import LogisticRegression
    import numpy as np
    import matplotlib.pyplot as plt
    
    hours1=  [0.50,0.75,1.00, 
    1.25,1.50,1.75,1.75,2.00,2.25, 
    2.50,2.75,3.00,3.25,3.50,4.00,
    4.25,4.50,
    4.75,5.00,5.50]
    len(hours1)
    pass1=[0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1]
    len(pass1)
    
    X_train=np.array([hours1])
    y_train=np.array([pass1])
    X_train.shape=(20,1)
    y_train.shape=(20,)
    
    param_grid = [0.001, 0.01, 0.1, 1, 10, 100, 1000]
    coef = []
    intc = []
    param = []
    for p in param_grid: 
        clf = LogisticRegression(C=p,random_state=0,solver='lbfgs',fit_intercept=True)
        clf.fit(X_train, y_train)
    
        coef.append(clf.coef_[0])
        intc.append(clf.intercept_)
        param.append(p)
    
    coef = np.array(coef)
    intc = np.array(intc)
    
    plt.plot(param, coef[:, 0], color='blue', marker='x', label='coefficient')
    plt.plot(param, intc[:, 0], color='green',  marker='o', label='intercept')
    plt.ylabel('intercept/coefficient')
    plt.xlabel('C')
    plt.legend(loc='right')
    plt.xscale('log')
    plt.show()
    

    如果你在不同的 C 值上绘制截距和系数,你可以看到当 C=1000 或附近时你得到了预期的输出。

    现在您可以使用 C as 1000( 1e3 == 1000) 拟合模型

    clf = LogisticRegression(C=1e3,random_state=0,solver='lbfgs',fit_intercept=True)
    clf.fit(X_train, y_train)
    print("coef_ is", clf.coef_)
    print("intercept_ is" ,clf.intercept_)
    

      

    #output 
     coef_ is [[1.50405093]]
     intercept_ is [-4.07616221]
    

    【讨论】:

      猜你喜欢
      • 2016-10-18
      • 2021-06-15
      • 2021-12-19
      • 2021-12-26
      • 2021-03-11
      • 1970-01-01
      • 2016-03-06
      • 2014-05-08
      • 1970-01-01
      相关资源
      最近更新 更多