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')

結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章