import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import torch class Net(nn.Module): # 需要继承这个类
def __init__(self):
super(Net, self).__init__()
# 建立了两个卷积层,self.conv1, self.conv2,注意,这些层都是不包含激活函数的
self.conv1 = nn.Conv2d(1, 6, 5) # 1 input image channel, 6 output channels, 5x5 square convolution kernel
self.conv2 = nn.Conv2d(6, 16, 5)
# 三个全连接层
self.fc1 = nn.Linear(16 * 5 * 5, 120) # an affine operation: y = Wx + b
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10) def forward(self, x): # 注意,2D卷积层的输入data维数是 batchsize*channel*height*width
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv2(x)), 2) # If the size is a square you can only specify a single number
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x) print(x)
print('y=--------')
return x def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features net = Net()
# create your optimizer
optimizer = optim.SGD(net.parameters(), lr = 0.01)
num_iteations = 20
input = Variable(torch.randn(2, 1, 32, 32))
print('input=',input)
#target = Variable(torch.Tensor([5],dtype=torch.long))
target = Variable(torch.LongTensor([5,7]))
# in your training loop:
for i in range(num_iteations):
optimizer.zero_grad() # zero the gradient buffers,如果不归0的话,gradients会累加 output = net(input) # 这里就体现出来动态建图了,你还可以传入其他的参数来改变网络的结构
criterion = nn.CrossEntropyLoss()
loss = criterion(output, target)
loss.backward() # 得到grad,i.e.给Variable.grad赋值
optimizer.step() # Does the update,i.e. Variable.data -= learning_rate*Variable.grad

这里是给出的一个代码。

init只是规定了conv的输入通道数量、输出通道数量和卷积核尺寸。

然后在神经网络中,充当卷积层的是forward部分。

input = Variable(torch.randn(2, 1, 32, 32))    #batchsize,channel,height,width
target = Variable(torch.LongTensor([5,7]))     #我希望两个神经网络,第一个等于5,第二个等于7.当然随便两个数。(不代表5*7维矩阵呀)

简单了解pytorch的forward的更多相关文章

  1. 超简单!pytorch入门教程(五):训练和测试CNN

    我们按照超简单!pytorch入门教程(四):准备图片数据集准备好了图片数据以后,就来训练一下识别这10类图片的cnn神经网络吧. 按照超简单!pytorch入门教程(三):构造一个小型CNN构建好一 ...

  2. 超简单!pytorch入门教程(四):准备图片数据集

    在训练神经网络之前,我们必须有数据,作为资深伸手党,必须知道以下几个数据提供源: 一.CIFAR-10 CIFAR-10图片样本截图 CIFAR-10是多伦多大学提供的图片数据库,图片分辨率压缩至32 ...

  3. 超简单!pytorch入门教程(三):构造一个小型CNN

    torch.nn只接受mini-batch的输入,也就是说我们输入的时候是必须是好几张图片同时输入. 例如:nn. Conv2d 允许输入4维的Tensor:n个样本 x n个色彩频道 x 高度 x ...

  4. pytorch 调用forward 的具体流程

    forward方法的具体流程: 以一个Module为例:1. 调用module的call方法2. module的call里面调用module的forward方法3. forward里面如果碰到Modu ...

  5. 超简单!pytorch入门教程(一):Tensor

    http://www.jianshu.com/p/5ae644748f21 二.pytorch的基石--Tensor张量 其实标量,向量,矩阵它们三个也是张量,标量是零维的张量,向量是一维的张量,矩阵 ...

  6. 超简单!pytorch入门教程(二):Autograd

    一.autograd自动微分 autograd是专门为了BP算法设计的,所以这autograd只对输出值为标量的有用,因为损失函数的输出是一个标量.如果y是一个向量,那么backward()函数就会失 ...

  7. PyTorch之前向传播函数自动调用forward

    参考:1. pytorch学习笔记(九):PyTorch结构介绍 2.pytorch学习笔记(七):pytorch hook 和 关于pytorch backward过程的理解 3.Pytorch入门 ...

  8. 机器翻译注意力机制及其PyTorch实现

    前面阐述注意力理论知识,后面简单描述PyTorch利用注意力实现机器翻译 Effective Approaches to Attention-based Neural Machine Translat ...

  9. pytorch中检测分割模型中图像预处理探究

    Object Detection and Classification using R-CNNs 目标检测:数据增强(Numpy+Pytorch) - 主要探究检测分割模型数据增强操作有哪些? - 检 ...

随机推荐

  1. 【工具】switchhost

    1.前提 主要功能切换host 2.下载路径 https://oldj.github.io/SwitchHosts/ 3.使用略(太简单)

  2. spotlight工具监控oracle

    spotlight工具版本Version: 5.0.1.1022 安装步骤 安装完成 安装之后,桌面上会生成如下图标 双机此图标,输入License 输入激活码 点击close,再次查看 建立连接,监 ...

  3. pxe+Kickstart自动装机补充知识点

    1.vmlinuzvmlinuz是可引导的.压缩的内核.“vm”代表“Virtual Memory”.Linux 支持虚拟内存,不像老的操作系统比如DOS有640KB内存的限制.Linux能够使用硬盘 ...

  4. centos查看系统版本信息

    1.查看版本文件名称 ll /etc/*centos* 2.显示系统版本号 cat /etc/centos-release

  5. django CBV基于类视图简单实例

    URLS: from django.contrib import admin from django.urls import path from cmbd import views urlpatter ...

  6. AttributeError: 'module' object has no attribute 'main'

    本机环境:ubuntu16.04,  ros-kinetic $ roscore 报错 Traceback (most recent call last): File , in <module& ...

  7. 常量&字符编码

    day1 name='Nod Chen' name2=name print('My name is ',name,name2) name='Luna zhou' print(name,name2) _ ...

  8. python之路——8

    王二学习python的笔记以及记录,如有雷同,那也没事,欢迎交流,wx:wyb199594 学习内容 .1.文件操作 笔记.txt 1.文件路径:D:\python\Day8\笔记.txt 2.编码方 ...

  9. 上线啦,PP.io!

    经过我们PPIO团队成员们在20天零13小时零14分的辛勤努力下,我们的官网终于上线了!   是的,14年前我们就是东半球第一个P2P技术团队.我们的征程始于2004年春天一个温暖的午后.寝室里笨拙的 ...

  10. Django项目的创建

    一. Django介绍 Python的WEB框架有Django.Tornado.Flask 等多种, Django相较与其他WEB框架其优势为: 大而全, 框架本身集成了ORM.模型绑定,.模板引擎, ...