Feature Map of Pytorch示例

场景:假设已训练好model,并选了最佳模型best_net,现在想提取网络层的特征并绘出热力图。

1、oriImg = cv2.imread(image_path) #读取一张图片,image_path是图片路径

2、data = torch.from_numpy(oriImg).type(torch.FloatTensor).cuda()  
     output = best_net(data)   #前向计算,这是best_net上权值结合data生成了网络层的特征值。

3、获取网络层特征值:

activation = {}
def get_activation(name):
    def hook(model, input, output):
        activation[name] = output.detach()
    return hook

# normalizing the output
def normalize_output(img):
    img = img - img.min()
    img = img / img.max()
    return img

#conv1         
best_net.conv1.register_forward_hook(get_activation('conv1'))#maxpool
feature = activation['conv1'].squeeze()
feature_0 = feature[0].cpu().numpy()

    假设这里获取卷积层conv1的特征层,然后提取第一个通道。

4、可视化特征值,即可显示特征热力图。

feature_0 = normalize_output(feature_0)
feature_0 = np.uint8(255 * feature_0)
#plot
height, width, _ = oriImg.shape
featuremap = cv2.applyColorMap(cv2.resize(feature_0,(width, height)), cv2.COLORMAP_JET)
#featuremap = featuremap * 0.3 + oriImg * 0.5
plt.imshow(featuremap)
plt.axis('off')

结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值