【问题标题】:How to extract coefficients from fitted pipeline for penalized logistic regression?如何从拟合管道中提取系数以进行惩罚逻辑回归?
【发布时间】:2020-02-25 04:38:38
【问题描述】:

我有一组训练数据,其中 X 是一组 n 列数据(特征),Y 是一列目标变量。

我正在尝试使用以下管道使用逻辑回归训练我的模型:

pipeline = sklearn.pipeline.Pipeline([
    ('logistic_regression', LogisticRegression(penalty = 'none', C = 10))
])

我的目标是在线性模型(y = coeff_0 + coeff_1*x1 + ... + coeff_n*xn)的假设下,获得与特征对应的 n 个系数中的每一个的值。

我尝试使用model = pipeline.fit(X, Y) 在我的数据上训练这个管道。所以我认为我现在有了包含我想要的系数的模型。但是,我不知道如何访问它们。我正在寻找类似mode.best_params_('logistic_regression') 的东西。

有人知道如何从这样的模型中提取拟合系数吗?

【问题讨论】:

  • 逻辑回归仅适用于线性数据。对非线性数据使用 ols
  • "设置惩罚='none'会忽略C和l1_ratio
  • 系数是多项式泰勒级数的一部分。您可以使用系数来生成多项式。

标签: machine-learning scikit-learn logistic-regression


【解决方案1】:

这里是如何可视化系数和测量模型准确性的方法。我用宝宝体重身高和孕期预测早产

pipeline = Pipeline([('lr', LogisticRegression(penalty='l2',C=10))])

scaler=StandardScaler()
#X=np.array(df['gestation_wks']).reshape(-1,1)
X=scaler.fit_transform(df[['bwt_lbs','height_ft','gestation_wks']])
y=np.array(df['PreTerm'])

X_train,X_test, y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=123)

pipeline.fit(X_train,y_train)
y_pred_prob=pipeline.predict_proba(X_test)
predictions=pipeline.predict(X_test)
print(predictions)

sns.countplot(x=predictions, orient='h')
plt.show()
#print(predictions[:,0])
print(pipeline['lr'].coef_)
print(pipeline['lr'].intercept_)
print('Coefficients close to zero will contribute little to the end result')

num_err = np.sum(y != pipeline.predict(X))
print("Number of errors:", num_err)

def my_loss(y,w):
    s = 0
    for i in range(y.size):
        # Get the true and predicted target values for example 'i'
        y_i_true = y[i]
        y_i_pred = w[i]
        s = s + (y_i_true - y_i_pred)**2
    return s

 print("Loss:",my_loss(y_test,predictions))

 fpr, tpr, threshholds = roc_curve(y_test,y_pred_prob[:,1])

 plt.plot([0, 1], [0, 1], 'k--')
 plt.plot(fpr, tpr)
 plt.xlabel('False Positive Rate')
 plt.ylabel('True Positive Rate')
 plt.title('ROC Curve')
 plt.show()

 accuracy=round(pipeline['lr'].score(X_train, y_train) * 100, 2)

 print("Model Accuracy={accuracy}".format(accuracy=accuracy))

 cm=confusion_matrix(y_test,predictions)
 print(cm)

【讨论】:

    【解决方案2】:

    pipeline 中获取coefs 的示例。

    from sklearn.linear_model import LogisticRegression
    from sklearn.datasets import load_iris
    from sklearn.pipeline import Pipeline
    
    X, y = load_iris(return_X_y=True)
    
    pipeline = Pipeline([('lr', LogisticRegression(penalty = 'l2', 
                                                   C = 10))])
    pipeline.fit(X, y)
    
    pipeline['lr'].coef_
    
    
    array([[-0.42923513,  2.08235619, -4.28084811, -1.97174699],
           [ 1.06321671, -0.08077595, -0.46911772, -2.3221883 ],
           [-0.63398158, -2.00158024,  4.74996583,  4.29393529]])
    

    【讨论】:

      【解决方案3】:

      看看 scikit-learn documentation for Pipeline,这个例子就是受它启发的:

      from sklearn import svm
      from sklearn.datasets import make_classification
      from sklearn.feature_selection import SelectKBest
      from sklearn.feature_selection import f_regression
      from sklearn.pipeline import Pipeline
      # generate some data to play with
      X, y = make_classification(n_informative=5, n_redundant=0, random_state=42)
      # ANOVA SVM-C
      anova_filter = SelectKBest(f_regression, k=5)
      clf = svm.SVC(kernel='linear')
      anova_svm = Pipeline([('anova', anova_filter), ('svc', clf)])
      anova_svm.set_params(anova__k=10, svc__C=.1).fit(X, y)
      # access coefficients
      print(anova_svm['svc'].coef_)
      

      model.coef_ 完成这项工作,.best_params_ 通常与GridSearch 相关联,即超参数优化。

      在您的具体情况下尝试:model['logistic_regression'].coefs_

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-16
        • 2021-08-31
        • 2023-02-03
        • 2021-06-29
        • 2015-11-18
        • 2022-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多