代码参考Github : https://github.com/wkentaro/pytorch-fcn
1. _fast_hist
import numpy as np
def _fast_hist(label_true, label_pred, n_class):
mask = (label_true >= 0) & (label_true < n_class)
hist = np.bincount(
n_class * label_true[mask].astype(int) +
label_pred[mask], minlength=n_class ** 2).reshape(n_class, n_class)
return hist
params:label_true表示标签,label_pred表示预测值,n_class表示像素的类别数。
首先mask是一个模板,应该是把分类的序号限定在有意义的类别数中,见下图
然后是hist,这是一个统计矩阵,大概样子如下图,横轴表示预测值,纵轴表示真实值
真实值\预测值 | 0 | 1 | 2 |
---|---|---|---|
0 | |||
1 | |||
2 |
第一行第一列的意思就是真实值是0的标签其预测值也是0的数量。
再看np.bincount里的参数,最主要是这句n_class * label_true[mask].astype(int) + label_pred[mask]
,
这句的意思就是将分类的真实值与预测值对应起来,我们把这个式子简化为
n
×
i
+
j
n \times i + j
n×i+j的形式,其中n=3,
因为在reshape的时候是将一个列表按照行数的顺序来reshape,那么当n=3且矩阵是
3
×
3
3\times3
3×3的形式时,i就代表行号,j代表在这一行中的列号,例如
n
×
2
+
1
n \times 2+1
n×2+1,就代表第三行第二列,也就是真实值为2但预测值为1的像素的标签(预测错误),然后bincount对所有的index进行一个统计(统计完是一个向量),然后reshape到一个hist矩阵中,下面是一个例子。
# a,b矩阵的唯一一个不同的地方在矩阵右下角的元素,真值是2,预测值1,那么根据上面的推算,在hist矩阵中
# 第三行第二列的值应该是1
>>> a = np.array([[1,0,1],[2,2,0],[0,1,2]])
>>> b = np.array([[1,0,1],[2,2,0],[0,1,1]])
>>> k = (a>=0) & (a<3)
>>> a,b,k
(array([[1, 0, 1],
[2, 2, 0],
[0, 1, 2]]),
array([[1, 0, 1],
[2, 2, 0],
[0, 1, 1]]),
array([[ True, True, True],
[ True, True, True],
[ True, True, True]]))
>>> c = 3*a[k]
>>> c
array([3, 0, 3, 6, 6, 0, 0, 3, 6])
>>> d = b[k]
>>> d
array([1, 0, 1, 2, 2, 0, 0, 1, 1])
>>> i = c+d
>>> i
array([4, 0, 4, 8, 8, 0, 0, 4, 7])
>>> hist = np.bincount(i,minlength=3**2).reshape(3,3)
# 跟之前所预测的结果相同,第三行第二列结果是1,对角线上的都是真值==预测值的数量
>>> hist
array([[3, 0, 0],
[0, 3, 0],
[0, 1, 2]], dtype=int64)