Pytorch入门材料

Pytorch风靡学术圈,作为入门小白,入门的过程从不知所措到稍有眉目,真的是柳暗花明,这里记录一些比较有代表性的入门材料,补充全局观,感谢这些材料的作者,我只是做一个汇总。这个汇总适合有深度学习基础、仅仅需要了解新框架的同学使用,欢迎留言或邮件交流(xuehaowang@buaa.edu.cn)。

1. CPD代码(CPD: Cascaded Partial Decoder for Accurate and Fast Salient Object Detection

这是CVPR2019的文章,代码风格简洁易懂,逻辑清晰,优点:

  • 在网络部分,同时使用了nn.Sequentialnn.Module两个模块,对于加深新手理解很有帮助。
  • 代码包括了基于VGG和ResNet的实现,也可以通过这份代码了解如何使用不同的backbone以及权重赋值
  • 优点很多,自行探索

2. 一个Demo

这个demo设计了一个简单的网络,可以通过整个流程,对Pytorch的使用有一个大概了解,网络实现方式与CPD不一样,二者代表了Pytorch设计网络时的两种风格(无参层位置,详见另一篇文章进行风格解释:PyTorch之nn.ReLU与F.ReLU的区别)。Demo展示放在最后了。

3.  PyTorch implementation of Fully Convolutional Networks

如标题所示,这个实现过程也很清晰易懂,作为参考

附:2所提到的Demo: 

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值