Pytorch可视化指定层(Udacity)
import cv2
import matplotlib.pyplot as plt
%matplotlib inline # TODO: Feel free to try out your own images here by changing img_path
# to a file path to another image on your computer!
img_path = 'images/udacity_sdc.png' # load color image
bgr_img = cv2.imread(img_path)
# convert to grayscale
gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1]
gray_img = gray_img.astype("float32")/255 # plot image
plt.imshow(gray_img, cmap='gray')
plt.show()
显示图像
定义滤波器,并将其可视化
import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter!
filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape)
Filter shape: (4, 4)
# Defining four different filters,
# all of which are linear combinations of the `filter_vals` defined above # define four filters
filter_1 = filter_vals
filter_2 = -filter_1
filter_3 = filter_1.T
filter_4 = -filter_3
filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1
print('Filter 1: \n', filter_1)
Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]]
定义卷积层和池化层¶
将卷积层初始化,使其包含你所创建的所有滤波器。然后添加一个最大池化层(相关文档请通过点击这里查阅),内核大小为(4x4),这样你就可以看到,在这一步之后,图像分辨率已经降低了!
import torch
import torch.nn as nn
import torch.nn.functional as F # define a neural network with a convolutional layer with four filters
# AND a pooling layer of size (4, 4)
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)
self.conv.weight = torch.nn.Parameter(weight)
# define a pooling layer
self.pool = nn.MaxPool2d(4, 4) 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 weights
weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor)
model = Net(weight) # print out the layer in the network
print(model)
Net(
(conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False)
(pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False)
)
将每个滤波器的输出可视化
首先,我们将定义一个辅助函数viz_layer,它会接收一个特定的层和多个滤波器(可选参数)作为输入,并在图像通过后显示该层的输出。
# helper function for visualizing the output of a given layer
# default number of filters is 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, xticks=[], yticks=[])
# grab layer outputs
ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray')
ax.set_title('Output %s' % str(i+1))
让我们看一下应用ReLu激活函数后,该卷积层的输出是什么。
# plot original image
plt.imshow(gray_img, cmap='gray') # visualize all filters
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)) # convert the image into an input Tensor
gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers
conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer
viz_layer(activated_layer)
将池化层的输出可视化
然后,看一下池化层的输出。池化层将上面描绘的特征映射图作为输入,并通过一些池化因子,通过在一个给定内核区域中构造一个仅拥有最大(即最亮)值的新的较小图像来减少那些映射图的维度。
# visualize the output of the pooling layer
viz_layer(pooled_layer)
Pytorch可视化指定层(Udacity)的更多相关文章
- Pytorch加载并可视化FashionMNIST指定层(Udacity)
加载并可视化FashionMNIST 在这个notebook中,我们要加载并查看 Fashion-MNIST 数据库中的图像. 任何分类问题的第一步,都是查看你正在使用的数据集.这样你可以了解有关图像 ...
- 【转载】 【caffe转向pytorch】caffe的BN层+scale层=pytorch的BN层
原文地址: https://blog.csdn.net/u011668104/article/details/81532592 ------------------------------------ ...
- caffe fine tune 复制预训练model的参数和freeze指定层参数
复制预训练model的参数,只需要重新copy一个train_val.prototxt.然后把不需要复制的层的名字改一下,如(fc7 -> fc7_new),然后fine tune即可. fre ...
- PyTorch可视化——tensorboard、visdom
一.pytorch与tensorboard结合使用 Tensorboard Tensorboard一般都是作为tf的可视化工具,与tf深度集成,它能够展现tf的网络计算图,绘制图像生成的定量指标图以及 ...
- Unity3D 射线指定层获取GameObject 注意 LayerMask
这一篇是纯技术讨论,看过我前面文章的童鞋应该清楚,我的奔跑是靠鼠标响应的,鼠标点到哪就跑到哪,后来又有了界面,麻烦就来了,我的界面居然能点 穿.我不希望点界面的时候还能点到界面后面的地面上,角色傻不拉 ...
- Pytorch - GPU ID 指定 pytorch gpu 指定
PyTorch 关于多 GPUs 时的指定使用特定 GPU. PyTorch 中的 Tensor,Variable 和 nn.Module(如 loss,layer和容器 Sequential) 等可 ...
- pytorch固定BN层参数
背景:基于PyTorch的模型,想固定主分支参数,只训练子分支,结果发现在不同epoch相同的测试数据经过主分支输出的结果不同. 原因:未固定主分支BN层中的running_mean和running_ ...
- pytorch可视化工具visdom
visdom的github repo: https://github.com/facebookresearch/visdom 知乎一个教程:https://zhuanlan.zhihu.com/p/3 ...
- keras计算指定层的输出
import keras model = keras.models.Sequential([ keras.layers.Dense(4, activation='relu', input_dim=1, ...
随机推荐
- session安全&&CBC字符反转攻击&&hash拓展攻击
session安全 p神写的: 在传统PHP开发中,$_SESSION变量的内容默认会被保存在服务端的一个文件中,通过一个叫"PHPSESSID"的Cookie来区分用户.这类se ...
- 后端开发实践:Spring Boot项目模板
在我的工作中,我从零开始搭建了不少软件项目,其中包含了基础代码框架和持续集成基础设施等,这些内容在敏捷开发中通常被称为"第0个迭代"要做的事情.但是,当项目运行了一段时间之后再来反 ...
- Elasticsearch(2):索引详谈
在上一篇博客中,介绍了ES中的一些核心概念和ES.Kibana安装方法.本节开始,我们从索引开始来学习ES的操作方法. 1 创建索引¶ 创建一个索引的方法很简单,在Kibana中运行下行请 ...
- Cypress系列(60)- 运行时的截图和录屏
如果想从头学起Cypress,可以看下面的系列文章哦 https://www.cnblogs.com/poloyy/category/1768839.html 背景 在测试运行时截图和录屏能够在测试错 ...
- Go-The process cannot access the file because it is being used by another process.
where? Go程序在读取文件时候 why? 因为有其他进程也在读取和Go程序想要读取的文件,参数冲突 way? 关闭其他程序进程对该文件的读取操作
- 分享一些比较好用的(免费)网站及推荐理由 SMARK
分享一些比较好用的(免费)网站及推荐理由 --By SMARK 资源类 这里面是一些有供下载的资源的网站等 视频 片库 内容怎么样有待考证 蓝光网 看着还行, 打赏收入 预告片世界 还行, 收入有待考 ...
- 13.深入k8s:Pod 水平自动扩缩HPA及其源码分析
转载请声明出处哦~,本篇文章发布于luozhiyun的博客:https://www.luozhiyun.com 源码版本是1.19 Pod 水平自动扩缩 Pod 水平自动扩缩工作原理 Pod 水平自动 ...
- Python实现的数据结构与算法之双端队列详解
一.概述 双端队列(deque,全名double-ended queue)是一种具有队列和栈性质的线性数据结构.双端队列也拥有两端:队首(front).队尾(rear),但与队列不同的是,插入操作在两 ...
- Docker开启远程连接,本地IDEA使用docker插件连接(不认证的版本和认证的版本都有)
前言 在学校学习的时候,要部署一个Java程序,一般是打成war包,放到服务器上的tomcat的webapp里面去: 后来SpringBoot出现内置了tomcat,就直接打成jar包,丢到服务器任何 ...
- C# excel文件导入导出
欢迎关注微信公众号 C#编程大全 这里有更多入门级实例帮你快速成长 在C#交流群里,看到很多小伙伴在excel数据导入导出到C#界面上存在疑惑,所以今天专门做了这个主题,希望大家有所收获! 环境:wi ...