一、神经网络中间层
首先定义类
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) # 直接储存