Python单行代码需要混淆/应急矩阵

时间:2012-06-09 05:41:30

标签: python numpy

我想编写一个单行来计算混淆/偶然性矩阵M(任何维度等于类数的方阵),它计算在长度为n的两个向量中呈现的情况:Ytrue和Ypredicted。很明显,以下使用python和numpy不起作用:

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

创建单线矩阵混淆计算器的任何提示?

2 个答案:

答案 0 :(得分:4)

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

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

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

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]]

答案 1 :(得分:1)

如果NumPy更新或等于1.6且Ytrue和Ypred是NumPy数组,则此代码有效

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