import numpy as np
import torch.nn as nn
import torch
import cv2
import matplotlib.pyplot as plt
class torch.nn.ReLU(inplace=False) [source]
参数: inplace-选择是否在本地运算
class Model3(nn.Module):
def __init__(self):
super(Model3, self).__init__()
self.conv1 = nn.Conv2d(3, 10 ,5,padding = "same") # [ N, C_in , H , W]
self.add_module("conv2", nn.Conv2d(10,20,5,padding='same'))
self.relu = nn.ReLU() # 本地运算
def forward(self,x):
x1 = self.relu(self.conv1(x))
x2 = self.relu(self.conv2(x1))
return x1,x2
row_figure = cv2.imread("../Figures/guangzhou tower.jpg")
row_figure = cv2.cvtColor(row_figure,cv2.COLOR_BGR2RGB)
figure = torch.tensor(row_figure.reshape(1,3,675,1200),dtype=torch.float32)
model = Model3()
out1 ,out2 = model.forward(figure)
plt.title("row_figure")
plt.imshow(row_figure)
<matplotlib.image.AxesImage at 0x19d465e2f60>
由于 feature_map 是 tensor形式, 在Storage篮子中 带有require——grad = True属性
我们不需要这些,先把 这些东西都去掉,然后再转为numpy形式
"""循环打印查看 卷积提取的特征图"""
out1, out2 = torch.squeeze(out1), torch.squeeze(out2)
for i, feature_map in enumerate(out1):
plt.subplot(5,2,i+1)
plt.imshow(feature_map.detach().numpy(),cmap='gray')
plt.show()
for i, feature_map in enumerate(out2):
plt.subplot(5,4,i+1)
plt.imshow(feature_map.detach().numpy(),cmap='gray')
plt.show()