FCN-Pytorch实现源码阅读笔记

代码参考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,这是一个统计矩阵,大概样子如下图,横轴表示预测值,纵轴表示真实值

真实值\预测值012
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)                             
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值