【问题标题】:How to get odds-ratios and other related features with scikit-learn如何使用 scikit-learn 获得赔率和其他相关功能
【发布时间】:2017-01-30 06:50:53
【问题描述】:

我正在浏览这个odds ratios in logistic regression tutorial,并尝试使用 scikit-learn 的逻辑回归模块获得完全相同的结果。使用下面的代码,我可以获得系数和截距,但我找不到找到教程中列出的模型的其他属性的方法,例如 log-likelyhood、Odds Ratio、Std。错误,z,P>|z|,[95% Conf.间隔]。如果有人能告诉我如何使用sklearn 包计算它们,我将不胜感激。

import pandas as pd
from sklearn.linear_model import LogisticRegression

url = 'https://stats.idre.ucla.edu/wp-content/uploads/2016/02/sample.csv'
df = pd.read_csv(url, na_values=[''])
y = df.hon.values
X = df.math.values
y = y.reshape(200,1)
X = X.reshape(200,1)
clf = LogisticRegression(C=1e5)
clf.fit(X,y)
clf.coef_
clf.intercept_

【问题讨论】:

  • 仅供参考,您应该以 from sklearn.linear_model import LogisticRegression 身份进行导入
  • 当我运行这段代码时,我得到databricks/python/lib/python3.7/site-packages/sklearn/utils/validation.py:760: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel(). y = column_or_1d(y, warn=True) Out[2]: LogisticRegression(C=100000.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, l1_ratio=None, max_iter=100, multi_class='auto', n_jobs=None, penalty='l2', random_state=None, solver='lbfgs', tol=0.0001, verbose=0,warm_start=False)
  • 我很确定在遇到这个问题时我一直在使用 Python 2.7。

标签: python scikit-learn


【解决方案1】:

您可以通过取系数的指数来获得优势比:

import numpy as np
X = df.female.values.reshape(200,1)
clf.fit(X,y)
np.exp(clf.coef_)

# array([[ 1.80891307]])

至于其他统计数据,这些数据不容易从 scikit-learn 获得(其中模型评估主要使用交叉验证完成),如果您需要它们,最好使用不同的库,例如 statsmodels .

【讨论】:

  • 谢谢@maxymoo。是的,我可以通过statsmodels 获得其他摘要。
  • 当且仅当特征独立时,这些值是否只是优势比? (即特征之间没有交互)。
  • @user48956 查看stats.stackexchange.com/questions/57031/… 了解如何解释优势比的一个很好的例子
【解决方案2】:

除了@maxymoo 的回答,要获取其他统计信息,可以使用statsmodel。假设您的数据位于名为 dfDataFrame 中,下面的代码应该会显示一个很好的摘要:

import pandas as pd
from patsy import dmatrices
import statsmodels.api as sm 

y, X = dmatrices( 'label ~ age + gender', data=df, return_type='dataframe')
mod = sm.Logit(y, X)
res = mod.fit()
print res.summary()

【讨论】:

    【解决方案3】:

    我不知道使用 scikit-learn 的这种方法,但来自 statsmodels.api.stats 的Table2x2 在您的情况下可能很有用,因为它为您提供了 3 行的 OR、SE、CI 和 P 值代码:

    import statsmodels.api as sm
    table = sm.stats.Table2x2(np.array([[73, 756], [14, 826]]))
    table.summary(method='normal')
    """
                   Estimate    SE   LCB    UCB p-value
    Odds ratio        5.697       3.189 10.178   0.000
    Log odds ratio    1.740 0.296 1.160  2.320   0.000
    Risk ratio        5.283       3.007  9.284   0.000
    Log risk ratio    1.665 0.288 1.101  2.228   0.000
    """
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2017-07-18
      • 2014-06-03
      • 2018-10-27
      • 2020-04-26
      • 2019-11-09
      • 2021-10-21
      • 2015-06-15
      • 2014-03-02
      相关资源
      最近更新 更多