Feature Map of Pytorch示例
生活随笔
收集整理的這篇文章主要介紹了
Feature Map of Pytorch示例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
場景:假設已訓練好model,并選了最佳模型best_net,現(xiàn)在想提取網絡層的特征并繪出熱力圖。
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')結果:
總結
以上是生活随笔為你收集整理的Feature Map of Pytorch示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于pytorch开发CNN提取全连接层
- 下一篇: Class Activation Map