0

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

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

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

4

2 回答 2

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]]
于 2012-06-09T06:18:51.510 回答
2

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

np.bincount(n * (Ytrue - 1) + (Ypred -1), minlength=n*n).reshape(n, n)
于 2012-06-10T10:44:53.950 回答