神经网络中间层输出可视化


一、神经网络中间层

首先定义类

activation = {}
def get_activation(name):
    def hook(model, input, output):
        # 如果你想feature的梯度能反向传播,那么去掉 detach()
        activation[name] = output.detach()
    return hook

由输出层的名称“self.名称”注册(在循环之前调用)

model_restoration.名称.register_forward_hook(get_activation('名称'))

先前向传播后提取输出层

m_output = model_restoration(m_input)
middle_layer_output = activation['名称']

二、热力图输出

定义函数将矩阵内值[0,1]转化为[0,255]

def img_as_ubyte(image, force_copy=False):
    """Convert an image to 8-bit unsigned integer format.

    Parameters
    ----------
    image : ndarray
        Input image.
    force_copy : bool, optional
        Force a copy of the data, irrespective of its current dtype.

    Returns
    -------
    out : ndarray of ubyte (uint8)
        Output image.

    Notes
    -----
    Negative input values will be clipped.
    Positive values are scaled between 0 and 255.

    """
    return _convert(image, np.uint8, force_copy)
img = img.cpu()[0]  # 形状为[L,L] 可视化一个通道
img = img-torch.min(img)  # 非负化
img = img/torch.max(img)  # 归一化
img = img_as_ubyte(img)  # [0,255]
img = cv2.applyColorMap(img, cv2.COLORMAP_JET)  # 热力图包装
cv2.imwrite(filepath,img) # 直接储存
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值