Pytorch官方教程学习笔记(1)
注:本教程在pytorch官方教程的基础上修改得到,原教程请点击pytorch_tutorial
What is PyTorch?
It’s a Python-based scientific computing package targeted at two sets of
audiences:
- A replacement for NumPy to use the power of GPUs
- a deep learning research platform that provides maximum flexibility
and speed
Getting Started
Tensors
与Numpy中的矩阵相比,Tensors的不同之处在于可以使用GPU对其进行加速计算。
from __future__ import print_function
import torch
构建一个大小为5x3的矩阵(不进行初始化):
x = torch.empty(5, 3)
print(x)
tensor([[ 0.0000, 0.0000,
0.0000],
[ 0.0000, 0.0000,
0.0000],
[-17052573744263721910272.0000, 0.0000,
0.0000],
[ 0.0000, 0.0000,
0.0000],
[-17066354759123475628032.0000, 0.0000,
0.0000]])
构建经过随机初始化的矩阵:
x = torch.rand(5, 3)
print(x)
tensor([[0.6351, 0.4463, 0.1681],
[0.6738, 0.3523, 0.2223],
[0.2257, 0.7201, 0.4833],
[0.6948, 0.3860, 0.3745],
[0.4248, 0.7636, 0.7570]])
构建全零矩阵,并指定数据类型为dtype long:
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:
x = torch.tensor([5.5, 3])
print(x)
tensor([5.5000, 3.0000])
也可以在现有tensor的基础上构建tensor,现有tensor的属性将被保留(例如:dtype),也可以给属性指定特定的值:
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([[ 0.2069, 1.2877, -0.5166],
[-1.3450, 0.2592, 1.2161],
[ 0.4427, 0.8569, 0.1560],
[ 1.1272, -1.3213, 0.9066],
[-1.0506, 0.3604, -0.4053]])
Get its size:
print(x.size())
torch.Size([5, 3])
torch.Size
is in fact a tuple, so it supports all tuple operations.
Operations
在tensor上的一些操作:
Addition: syntax 1
y = torch.rand(5, 3)
print(x + y)
tensor([[ 0.6790, 1.6560, -0.2253],
[-1.1419, 0.2704, 2.1830],
[ 0.6909, 1.2795, 0.8529],
[ 1.5204, -0.3262, 1.2432],
[-1.0165, 0.7596, -0.1896]])
Addition: syntax 2
print(torch.add(x, y))
tensor([[ 0.6790, 1.6560, -0.2253],
[-1.1419, 0.2704, 2.1830],
[ 0.6909, 1.2795, 0.8529],
[ 1.5204, -0.3262, 1.2432],
[-1.0165, 0.7596, -0.1896]])
Addition: providing an output tensor as argument
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
tensor([[ 0.6790, 1.6560, -0.2253],
[-1.1419, 0.2704, 2.1830],
[ 0.6909, 1.2795, 0.8529],
[ 1.5204, -0.3262, 1.2432],
[-1.0165, 0.7596, -0.1896]])
原地运算(改变原tensor的值):
# adds x to y
y.add_(x)
print(y)
tensor([[ 0.6790, 1.6560, -0.2253],
[-1.1419, 0.2704, 2.1830],
[ 0.6909, 1.2795, 0.8529],
[ 1.5204, -0.3262, 1.2432],
[-1.0165, 0.7596, -0.1896]])
Note
当操作带有“_”下标时,表明该操作会改变原tensor的值。 For example: ``x.copy_(y)``, ``x.t_()``, will change ``x``.
You can use standard NumPy-like indexing with all bells and whistles!
print(x[:, 1])
tensor([ 1.2877, 0.2592, 0.8569, -1.3213, 0.3604])
Resizing: If you want to resize/reshape tensor, you can use torch.view
:
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
If you have a one element tensor, use .item()
to get the value as a
Python number
x = torch.randn(1)
print(x)
print(x.item())
tensor([-1.2625])
-1.2625398635864258
Read later:
100+ Tensor operations, including transposing, indexing, slicing,
mathematical operations, linear algebra, random numbers, etc.,
are described
here <http://pytorch.org/docs/torch>
_.
NumPy Bridge
Torch的Tensor和Numpy矩阵共享同一内存,因而改变任何一者的值,另一者的值也会随之改变。
将tensor转换为numpy矩阵
a = torch.ones(5)
print(a)
tensor([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)
[ 1. 1. 1. 1. 1.]
See how the numpy array changed in value.
a.add_(1)
print(a)
print(b)
tensor([2., 2., 2., 2., 2.])
[ 2. 2. 2. 2. 2.]
将Numpy矩阵转化为tensor
See how changing the np array changed the Torch Tensor automatically
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
[ 2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
除了字符tensor之外,CPU中的所有tensors都可以转换为numpy矩阵。
CUDA Tensors
Tensors can be moved onto any device using the .to
method.
# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!
tensor([-0.2625], device='cuda:0')
tensor([-0.2625], dtype=torch.float64)