【问题标题】:Getting 'pred_table' information for predicted values of a model in 'statsmodels'在“statsmodels”中获取模型预测值的“pred_table”信息
【发布时间】:2014-04-26 14:08:44
【问题描述】:

在 Python 包statsmodels 中,LogitResults.pred_table 可以方便地用于获取“混淆矩阵”,对于任意阈值t,对于表单的Logit 模型

mod_fit = sm.Logit.from_formula('Y ~ a + b + c', train).fit() 
...
mod_fit.pred_table(t) 
#Conceptually: pred_table(t, predicted=mod_fit.predict(train), observed=train.Y)

有没有办法获取测试数据的等效信息?例如,如果我

pred = mod_fit.predict(test)

我如何获得等价物

mod_fit.pred_table(t, predicted=pred, observed=test.Y)

有没有办法让statsmodels 做到这一点(例如,一种从predtrain.Y 构建LogitResults 实例的方法),还是需要“手动”完成 - 和如果是的话怎么办>

【问题讨论】:

标签: python regression statsmodels confusion-matrix


【解决方案1】:

这是个好主意,而且很容易添加。你能发布一个github issue 吗?您可以使用以下代码完成此操作

import numpy as np
pred = np.array(mod_fit.predict(test) > threshold, dtype=float)
table = np.histogram2d(test.Y, pred, bins=2)[0]

【讨论】:

  • 这是否在 API 中实现?
【解决方案2】:

这是另一种方式,使用bincount

from __future__ import division
import numpy as np

def confusionmatrix( true, predicted, classnames="0 1", verbose=1 ):
    """ true aka y, observed class ids: ints [0 .. nclass) or bools
        predicted aka yhat: ints or bools, e.g. (probs > threshold)
    -> e.g.
        confusion matrix, true down, predicted across:
        [[0 2]  -- true 0, pred 0 1
         [7 1]  -- true 1, pred 0 1
    """
    true = np.asarray( true, dtype=int )
    pred = np.asarray( predicted, dtype=int )
    ntrue, npred = true.max() + 1, pred.max() + 1
    counts = np.bincount( npred * true + pred, minlength = ntrue * npred )  # 00 01 10 11
    confus = counts.reshape(( ntrue, npred ))
    if verbose:
        print "true counts %s:      %s" % (classnames, np.bincount(true))
        print "predicted counts %s: %s" % (classnames, np.bincount(pred))
        print "confusion matrix, true down, predicted across:\n", confus
    return confus

#...............................................................................
if __name__ == "__main__":
    n = 10
    np.random.seed( 7 )
    y = np.random.randint( 0, 2, n )
    p = np.random.randint( 0, 2, n )
    print "true:", y
    print "pred:", p
    confusionmatrix( y, p )

【讨论】:

    猜你喜欢
    • 2015-11-18
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 2022-06-08
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 2023-01-16
    相关资源
    最近更新 更多