Python oneliner提供所需的混乱/应急矩阵

2024-10-03 17:15:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个一行程序来计算一个混淆/列联矩阵M(任何一个维度都等于类的个数的平方矩阵),它计算两个长度为n的向量:Ytrue和y预测的情况。显然,使用python和numpy时,以下操作不起作用:

error = N.array([error[x,y]+1 for x, y in zip(Ytrue,Ypredicted)]).reshape((n,n))

有什么提示可以创建一个线性矩阵混淆计算器吗?在


Tags: in程序numpyfor情况线性矩阵error
2条回答
error = N.array([zip(Ytrue,Ypred).count(x) for x in itertools.product(classes,repeat=2)]).reshape(n,n)

或者

^{pr2}$

后者效率更高,但可能更令人困惑。在

import numpy as N
import itertools

Ytrue = [1,1,1,1,1,1,1,1,
         2,2,2,2,2,2,2,2,
         3,3,3,3,3,3,3,3]
Ypred = [1,1,2,1,2,1,3,1,
         2,2,2,2,2,2,2,2,
         3,3,2,2,2,1,1,1]

classes = list(set(Ytrue))
n = len(classes)

error = N.array([zip(Ytrue,Ypred).count(x) for x in itertools.product(classes,repeat=2)]).reshape(n,n)
print error

error = N.array([z.count(x) for z in [zip(Ytrue,Ypred)] for x in itertools.product(classes,repeat=2)]).reshape(n,n)
print error

产生

[[5 2 1]
 [0 8 0]
 [3 3 2]]

[[5 2 1]
 [0 8 0]
 [3 3 2]]

如果NumPy更新或等于1.6,并且Ytrue和Ypred是NumPy数组,那么这段代码可以工作

np.bincount(n * (Ytrue - 1) + (Ypred -1), minlength=n*n).reshape(n, n)

相关问题 更多 >