torch框架奇葩语法

一、Torch和TensorFlow的不同

  • TensorFlow是先构造一个网络,最后在统一进行计算。
  • Torch是正常的计算流程,写一句计算一句,更符合人的正常思维。
  • Torch可以更加方便的在GPU上面进行计算

这种不同的设计,在使用上带来了什么区别呢?

  • TensorFlow的表格一旦建立好之后,在训练的过程就不能再进行修改了
  • Torch可以进行修改

既然Torch更加优秀,为什么还没有把TensorFlow取代

  • TensorFlow先出现,先一步占领了市场
  • TensorFlow依旧在不断的更新,解决上面的问题,持续进步

二、Torch的简单使用 1

2.1 使用CPU计算

2.1.1 简单计算
1
2
3
4
5
6
7
8
9
import torch

x = torch.ones(2,2)
y = x * 2
print(y)

result:
tensor([[2., 2.],
[2., 2.]])
2.1.1 梯度计算

梯度计算方式是Torch优势最大的地方,原理是对计算步骤的每一步进行跟踪,非常容易的得出其梯度。使用之前需要对需要进行梯度跟踪的变量进行requires_grad标记。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import torch
from torch.autograd import Variable

x = torch.ones(2,2)
x = Variable(x,requires_grad = True)
print(x)
y = x * 2

# backward的必要参数,梯度结果会合里面的数据对应相乘
gradients = torch.FloatTensor(torch.ones(2,2))
y.backward(gradients)
print(x.grad)

result:
tensor([[1., 1.],
[1., 1.]], requires_grad=True)
tensor([[2., 2.],
[2., 2.]])

2.2 使用GPU进行计算

使用GPU计算有一个很简单的规则,数据放在GPU上面的,就通过GPU计算;放在CPU上面的,就通过CPU计算。在变量后面.cuda()可以把变量放到GPU上面。

2.2.1 简单计算
1
2
3
4
5
6
7
8
9
10
11
12
13
import torch

if torch.cuda.is_available() :
x = torch.ones(2,2).cuda()
print(x)
y = x * 2
print(y)

result:
tensor([[1., 1.],
[1., 1.]], device='cuda:0')
tensor([[2., 2.],
[2., 2.]], device='cuda:0')
2.2.2 梯度计算
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import torch
from torch.autograd import Variable

if torch.cuda.is_available() :
x = torch.ones(2,2).cuda()
x = Variable(x,requires_grad = True)
print(x)
y = x * 2
gradients = torch.FloatTensor(torch.ones(2,2)).cuda() # 注意这里也要.cuda
y.backward(gradients)
print(x.grad)

result:
tensor([[1., 1.],
[1., 1.]], device='cuda:0', requires_grad=True)
tensor([[2., 2.],
[2., 2.]], device='cuda:0')

三、Torch的网络搭建

依旧使用基础教程minist来作为例子

代码已经上传到github,里面有详细注解。需要用到的理论知识为:

  • CNN原理
  • 数据集的使用

四、常用函数介绍

4.1 DataLoader函数

数据集处理函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from torch.utils.data import DataLoader,TensorDataset
import torch

a = torch.tensor([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
#tensor([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])

b = torch.tensor([1,2,3,4])
#tensor([1, 2, 3, 4])

c = TensorDataset(a,b)
#<torch.utils.data.dataset.TensorDataset object at 0x0000019B281259B0>

d = DataLoader(dataset=c,batch_size=2,shuffle=True)
#<torch.utils.data.dataloader.DataLoader object at 0x000001FB87D15B38>

for data,index in d :
print(data)
print(index)

result:
tensor([[7, 8, 9],
[1, 2, 3]])
tensor([3, 1])
tensor([[ 4, 5, 6],
[10, 11, 12]])
tensor([2, 4])

4.2 mnist数据集

和TensorFlow的mnist数据集的格式有点不同

  • 获取方法

    1
    2
    3
    4
    5
    6
    7
    8
    import torchvision.datasets

    otrain_data = torchvision.datasets.MNIST(
    root='./mnist/', # 存放位置
    train=True, # True选择训练集,False选择测试集
    transform=torchvision.transforms.ToTensor(), # 转换为Tensor格式
    download=True, # 本地没有,则自动从网络下载
    )
  • 处理方法

    1
    2
    3
    from torch.utils.data import DataLoader

    train_data = DataLoader(dataset=train_data,batch_size = batch_size,shuffle = True)

dataset:数据集
batch_size:一批数据多少个(torch是批量计算的)
shuffle:是否随机打乱顺序

  • 测试方法
    1
    2
    3
    4
    5
    6
    import matplotlib.pyplot as plt

    for D,L in train_data:
    print(L[0])
    plt.imshow(D[0][0])
    plt.show()

4.3 向量对比

1
2
3
4
5
6
7
8
9
10
import torch

a = torch.tensor([2,2,2,2,2,2])
b = torch.tensor([1,1,2,1,2,2])

count_sum = (a == b).sum()
print(count_sum) # 有3个位置的数字相等

result:
tensor(3)

参考文献

1. PyTorch 深度学习:60分钟快速入门
-------------本文结束感谢您的阅读-------------
0%