第一课
什么是PyTorch?
PyTorch是一个基于Python的科学计算库,它有以下特点:
- 类似于NumPy,但是它可以使用GPU
- 可以用它定义深度学习模型,可以灵活地进行深度学习模型的训练和使用
Tensors
Tensor类似与NumPy的ndarray,唯一的区别是Tensor可以在GPU上加速运算。
In [1]:
from __future__ import print_function
import torch
构造一个未初始化的5x3矩阵:
In [2]:
x = torch.empty(5, 3)
print(x)
tensor([[0.0000e+00, 0.0000e+00, 0.0000e+00],
[0.0000e+00, 4.7339e+30, 1.4347e-19],
[2.7909e+23, 1.8037e+28, 1.7237e+25],
[9.1041e-12, 6.2609e+22, 4.7428e+30],
[3.8001e-39, 0.0000e+00, 0.0000e+00]])
构建一个随机初始化的矩阵:
In [3]:
x = torch.rand(5, 3)
print(x)
tensor([[0.4821, 0.3854, 0.8517],
[0.7962, 0.0632, 0.5409],
[0.8891, 0.6112, 0.7829],
[0.0715, 0.8069, 0.2608],
[0.3292, 0.0119, 0.2759]])
构建一个全部为0,类型为long的矩阵:
In [4]:
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
从数据直接直接构建tensor:
In [5]:
x = torch.tensor([5.5, 3])
print(x)
tensor([5.5000, 3.0000])
也可以从一个已有的tensor构建一个tensor。这些方法会重用原来tensor的特征,例如,数据类型,除非提供新的数据。
In [6]:
x = x.new_ones(5, 3, dtype=torch.double) # new_* methods take in sizes
print(x)
x = torch.randn_like(x, dtype=torch.float) # override dtype!
print(x) # result has the same size
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor([[ 1.4793, -2.4772, 0.9738],
[ 2.0328, 1.3981, 1.7509],
[-0.7931, -0.0291, -0.6803],
[-1.2944, -0.7352, -0.9346],
[ 0.5917, -0.5149, -1.8149]])
得到tensor的形状:
In [7]:
print(x.size())
torch.Size([5, 3])
注意
``