什么是PyTorch?

它是一个基于Python的科学计算软件包。主要针对两类受众:

  • 使用GPU运算来取代Numpy
  • 提供最大灵活性和速度的深度学习研究平台

入门

张量(Tensors) 张量和Numpy的ndarray类似。不同的是张量可以在GPU上运行以加速运算。

使用张量构造一个未初始化的5*3的矩阵:


In [1]:
import torch
x=torch.empty(5,3) # 使用张量构造一个未初始化的5*3的矩阵
y=torch.zeros(5,3,dtype=torch.long) # 构造一个dtype为long的全0矩阵
z=torch.rand(5,3) # 构造一个随机数据的矩阵
print(x)
print(y)
print(z)


tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
tensor([[0.0599, 0.8416, 0.9479],
        [0.7640, 0.9935, 0.1902],
        [0.3242, 0.0427, 0.5336],
        [0.0855, 0.5966, 0.5868],
        [0.0868, 0.8864, 0.5139]])

运算(Operations)

运算有很多种语法。接下来的例子我们看下加法运算。


In [2]:
print(x+y) # 语法1
print(torch.add(x,y)) # 语法2


tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])
tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])

In [ ]: