获取'statsmodels'中模型预测值的'pred_table'信息

4 投票
2 回答
6507 浏览
提问于 2025-04-17 23:03

在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实例),还是说这需要手动来做——如果是这样的话,应该怎么做呢?

2 个回答

0

这里有另一种方法,使用 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 )
5

这是个好主意,而且很容易实现。你能在GitHub上发个问题吗? 你可以用下面的代码来做到这一点。

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

撰写回答