输出层|PyTorch可视化理解卷积神经网络( 四 )

<0 else 'black')步骤3:定义CNN模型
本文构建的CNN模型具有卷积层和最大池层 , 并且使用上述过滤器初始化权重:
import torchimport torch.nn as nnimport torch.nn.functional as F class Net(nn.Module):def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) # initializes the weights of the convolutional layer self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(2, 2) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x)# applies pooling layer pooled_x = self.pool(activated_x)# returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weightsweight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor)model = Net(weight)# print out the layer in the networkprint(model)Net(
(conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False)
(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
步骤4:可视化过滤器
快速浏览一下所使用的过滤器
def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20))for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1) ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1))fig = plt.figure(figsize=(12, 6))fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05)for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1))gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1)
输出层|PyTorch可视化理解卷积神经网络文章插图
步骤5:每层过滤器的输出
在卷积层和池化层输出的图像如下所示:
卷积层:
输出层|PyTorch可视化理解卷积神经网络文章插图
池化层:
输出层|PyTorch可视化理解卷积神经网络文章插图
可以看到不同层结构得到的效果会有所差别 , 正是由于不同层提取到的特征不同 , 在输出层集合到的特征才能很好地抽象出图像信息 。
作者信息Vihar Kurama , 机器学习
本文由阿里云云栖社区组织翻译 。
文章_本文原题《Understanding Convolutional Neural Networks through Visualizations in PyTorch》 , 译者:海棠 , 审校:Uncle_LLD 。


推荐阅读