Chapter1

介绍

torch 和 numpy
相同点: 张量(tensors),ndarrays类似
不同点: tensors可用GPU计算
改变维度:torch.view reshape
属性: x.size()&x.shape y.shape?
pytorch和lua底层都是torch

官方60分钟快速入门

1.张量

初始化

import torch
x = torch.empty(5,3)     #torch.Size([5,3])
x = torch.rand(5,3)
x = torch.zeros(5,3,dtype=torch.long)
x = torch.tensor([1,2])  #torch.Size([2])
y = torch.ones_like(x)
x.copy_(y)               #任何以_结尾的操作都会用结果替换原变量
x = torch.randn(4,4)
y = x.view(-1,8)         #torch.Size([2,8]) , size -1 从其他维度推断

转换

#torch到numpy转换
a = torch.ones(5)
b = a.numpy()
#numpy到torch转换
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)

torch tensor 与numpy 数组共享底层内存地址,修改一个另一个会变
CUDA张量

x = torch.randn(5,3)
if torch.cuda.is_available():
	device = torch.device("cuda")           #a CUDA 设备对象
	y = torch.ones_like(x,device=device)    #直接从GPU创建张量
	x = x.to(device)                        #或者直接用.to("cuda") 将张量移动到cuda中
	z = x + y
	print(z)
	print(z.to("cpu",torch.double))    #.to 也会对变量类型做改变

2.自动求导

x = torch.ones(2,2,requires_grad=True) #追踪张量计算历史
y = x + 2                              #y已被计算出来, grad_fn自动生成
print(y.grad_fn)
z = y * y * 3
out = z.mean()
print(z, out)                                            
out.backward()                         #自动计算所有梯度,此张量所有梯度累积到.grad属性
print(x.grad)

阻止张量追踪历史记录,可调用.detach()方法将其与计算历史记录剥离,为防止跟踪历史记录(使用内存),可将代码包装在with_torch.no_grad():

3.神经网络

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square you can only specify a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        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)
        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()
print(net)
Net(
  (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=400, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)

在模型中必须要定义 forward 函数,可以在 forward 函数中使用任何针对 Tensor 的操作。backward 函数(用来计算梯度)会被autograd自动创建。 net.parameters()返回可被学习的参数(权重)列表和值

params = list(net.parameters())
print(len(params))       # 10
print(params[0].size())  # conv1's .weight torch.Size([6, 1, 5, 5])

测试随机输入32×32。 注:这个网络(LeNet)期望的输入大小是32×32,如果使用MNIST数据集来训练这个网络,请把图片大小重新调整到32×32。

input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out) #tensor([[ 0.1120,  0.0713,  0.1014, -0.0696, -0.1210,  0.0084, -0.0206,  0.1366,-0.0455, -0.0036]], grad_fn=<AddmmBackward>)

将所有参数的梯度缓存清零,然后进行随机梯度的的反向传播:

net.zero_grad()
out.backward(torch.randn(1, 10))

概念复习:
torch.nn 只支持小批量输入。整个 torch.nn 包都只支持小批量样本,而不支持单个样本。例如,nn.Conv2d 接受一个4维的张量,每一维分别是sSamples * nChannels * Height * Width(样本数 * 通道数 *高 * 宽)。如果你有单个样本,只需使用 input.unsqueeze(0) 来添加其它的维数。
torch.Tensor:一个用过自动调用 backward()实现支持自动梯度计算的 多维数组 , 并且保存关于这个向量的梯度 w.r.t.
nn.Module:神经网络模块。封装参数、移动到GPU上运行、导出、加载等。
nn.Parameter:一种变量,当把它赋值给一个Module时,被 自动 地注册为一个参数。
autograd.Function:实现一个自动求导操作的前向和反向定义,每个变量操作至少创建一个函数节点,每一个Tensor的操作都回创建一个接到创建Tensor和 编码其历史的函数的Function节点。
损失函数
一个损失函数接受一对 (output, target) 作为输入,计算一个值来估计网络的输出和目标值相差多少。

output = net(input)
target = torch.randn(10)         # 随机值作为样例
target = target.view(1, -1)      # 使target和output的shape相同
criterion = nn.MSELoss()
loss = criterion(output, target) # tensor(0.8109, grad_fn=<MseLossBackward>)
print(loss)
现在,如果在反向过程中跟随loss , 使用它的 .grad_fn 属性,将看到如下所示的计算图。
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
      -> view -> linear -> relu -> linear -> relu -> linear
      -> MSELoss
      -> loss

当我们调用 loss.backward()时,整张计算图都会 根据loss进行微分,而且图中所有设置为requires_grad=True的张量 将会拥有一个随着梯度累积的.grad 张量。

print(loss.grad_fn)  # MSELoss
print(loss.grad_fn.next_functions[0][0])  # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0])  # ReLU

反向传播
调用loss.backward()获得反向传播的误差。但是在调用前需要清除已存在的梯度,否则梯度将被累加到已存在的梯度。现在,我们将调用loss.backward(),并查看conv1层的偏差(bias)项在反向传播前后的梯度。

net.zero_grad()     # 清除梯度

print('conv1.bias.grad before backward') # conv1.bias.grad before backward
print(net.conv1.bias.grad)               # tensor([0., 0., 0., 0., 0., 0.])

loss.backward()

print('conv1.bias.grad after backward')  # conv1.bias.grad after backward
print(net.conv1.bias.grad)               # tensor([ 0.0051,  0.0042,  0.0026,  0.0152, -0.0040, -0.0036])

更新权重
在实践中最简单的权重更新规则是随机梯度下降(SGD):
weight = weight - learning_rate * gradient
我们可以使用简单的Python代码实现这个规则:

learning_rate = 0.01
for f in net.parameters():
    f.data.sub_(f.grad.data * learning_rate)

但是当使用神经网络是想要使用各种不同的更新规则时,比如SGD、Nesterov-SGD、Adam、RMSPROP等,PyTorch中构建了一个包torch.optim实现了所有的这些规则。 使用它们非常简单:

import torch.optim as optim

# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)

# in your training loop:
optimizer.zero_grad()   # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()    # Does the update

4.训练一个分类器

1.使用torchvision加载和归一化CIFAR10训练集和测试集
2.定义一个卷积神经网络
3.定义损失函数
4.在训练集上训练网络
5.在测试集上测试网络
见first_classfication_net_cpu

5.数据并行

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader

# Parameters and DataLoaders
input_size = 5
output_size = 2
batch_size = 30
data_size = 100
#Device
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#创建一个虚拟数据集
class RandomDataset(Dataset):
    def __init__(self, size, length):
        self.len = length
        self.data = torch.randn(length, size)
    def __getitem__(self, index):
        return self.data[index]
    def __len__(self):
        return self.len

rand_loader = DataLoader(dataset=RandomDataset(input_size, data_size),
                         batch_size=batch_size, shuffle=True)
class Model(nn.Module):
    # Our model
    def __init__(self, input_size, output_size):
        super(Model, self).__init__()
        self.fc = nn.Linear(input_size, output_size)
    def forward(self, input):
        output = self.fc(input)
        print("\tIn Model: input size", input.size(),
              "output size", output.size())
        return output

model = Model(input_size, output_size)
if torch.cuda.device_count() > 1:
    print("Let's use", torch.cuda.device_count(), "GPUs!")
    # dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
    model = nn.DataParallel(model)
model.to(device)
for data in rand_loader:
    input = data.to(device)
    output = model(input)
    print("Outside: input size", input.size(),
          "output_size", output.size())
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值