深度学习pytorch基础入门教程(1小时)-张量、操作、转换
文章目录DEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ什么是pytorch开始张量Tensor操作OperationsNumPy BridgeTensor 转化为ArrayArray 转化为TensorCUDA TensorsDEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ最近因为课题的需要,要利用pytorch
文章目录
DEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ
最近因为课题的需要,要利用pytorch实现pointer network,所以在这里对ytorch的基本语法做一个简答的教程,主要参考了《60分钟闪电战:使用pytorch进行深度学习》。
本教程的目标如下:
- 理解pytorch的张量(Tensor)库和顶层神经网络;
- 训练一个简单神经网络进行图像分类。
什么是pytorch
它是一个基于python的科学计算包,针对两类受众:
- 可以代替Numpy从而利用GPU的强大功能;
- 是一个可以提供最大灵活性和速度的深度学习研究平台。
开始
张量Tensor
张量类似于Numpy中的ndarrays,此外张量可以在GPU上使用以加速计算。
from __future__ import print_function
import torch
注意:声明的未初始化的矩阵,在使用之前将不包含明确的已知值。当创建一个未初始化的矩阵时,当时在分配内存中的任何值都将作为初始值出现。
构建一个5x3的未初始化矩阵:
x = torch.empty(5, 3)
print(x)
输出:
tensor([[1.4013e-43, 4.4842e-44, 1.5975e-43],
[1.6395e-43, 1.5414e-43, 1.6115e-43],
[4.4842e-44, 1.4433e-43, 1.5975e-43],
[1.4153e-43, 1.3593e-43, 1.6255e-43],
[4.4842e-44, 1.5554e-43, 1.5414e-43]])
构建随机初始化的矩阵:
x = torch.rand(5, 3)
print(x)
输出:
tensor([[0.5609, 0.0796, 0.9257],
[0.5687, 0.6893, 0.2980],
[0.7573, 0.1314, 0.8814],
[0.8589, 0.7945, 0.0682],
[0.5252, 0.0355, 0.1465]])
构建全零且类型为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]])
直接根据数据创建张量:
x = torch.tensor([5.5, 3])
print(x)
输出:
tensor([5.5000, 3.0000])
或者基于现有的张量创建一个新的张量。如果用户没有提供新的值,则这两种创建方法将重用输入张量的属性,如数据类型。
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.9228, 0.4648, 0.9809],
[ 0.3880, 1.1388, -0.3020],
[ 1.5349, -0.5819, 0.0219],
[ 0.5549, 1.1202, -0.1401],
[ 1.5410, 0.0499, -0.0484]])
获取张量大小:
print(x.size())
输出:
torch.Size([5, 3])
torch.Size实际上是一个元组,所以它支持所有的元组操作。
操作Operations
操作支持多种语法。在下面的示例中,将先查看加法操作。
- 加法:语法1
y = torch.rand(5, 3)
print(x + y)
输出:
tensor([[ 0.4719, 0.3090, -0.3895],
[-1.2460, -0.6719, 2.4085],
[-1.0253, 1.7267, 1.8661],
[ 1.0923, 1.1947, -0.3916],
[ 1.2984, 0.7781, 2.1696]])
- 加法:语法2
print(torch.add(x, y))
输出:
tensor([[ 0.4719, 0.3090, -0.3895],
[-1.2460, -0.6719, 2.4085],
[-1.0253, 1.7267, 1.8661],
[ 1.0923, 1.1947, -0.3916],
[ 1.2984, 0.7781, 2.1696]])
- 加法:提供一个输出张量作为参数
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
输出:
tensor([[ 0.4719, 0.3090, -0.3895],
[-1.2460, -0.6719, 2.4085],
[-1.0253, 1.7267, 1.8661],
[ 1.0923, 1.1947, -0.3916],
[ 1.2984, 0.7781, 2.1696]])
- 加法:在位in-place(直接更新原有的张量)
# adds x to y
y.add_(x)
print(y)
输出:
tensor([[ 0.4719, 0.3090, -0.3895],
[-1.2460, -0.6719, 2.4085],
[-1.0253, 1.7267, 1.8661],
[ 1.0923, 1.1947, -0.3916],
[ 1.2984, 0.7781, 2.1696]])
通过在位改变张量的任意操作都是以后缀"_"结尾的,如
x.copy_(y), x.t_()
都会改变x。
- 可以使用标准的类似于Numpy的索引实现所有功能!
print(x[:, 1])
输出:
tensor([0.4648, 1.1388, -0.5819, 1.1202, 0.0499])
- 改变大小:如果想改变张量的大小或性状,可以通过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])
- 如果张量中只有一个元素,可以通过.item()获取值作为Python数字
x = torch.randn(1)
print(x)
print(x.item())
输出:
tensor([0.2687])
0.26873132586479187
更多张量操作,包括转置(transposing)、索引(indexing)、切片(slicing)、数学操作(mathematical operations)、线性代数(liner algebra)、随机数(random numbers)等,可以点击这里。
NumPy Bridge
NumPy Bridge的作用是实现Torch张量与Numpy array之间的相互转化。
torch的Tensor和numpy的array分享底层的内存地址(如果Torch 张量位于CPU上),所以改变其中一个就会改变另一个。
Tensor 转化为Array
a = torch.ones(5)
print(a)
输出:
tensor([1., 1., 1., 1., 1.])
通过.numpy()直接得到array。
b = a.numpy()
print(b)
输出:
[1. 1. 1. 1. 1.]
查看numpy数组的值是如何变化的。
a.add_(1)
print(a)
print(b)
输出:
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
可以看出a和b都发生了变化。
Array 转化为Tensor
看看如何改变np数组自动改变Torch张量的。
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)
通过from_numpt()可以将array转化为tensor,同时改变数组的值对应的张量也会自动改变。
CUDA Tensors
可以通过.to方法将张量移动到其他设备上。
# 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.8383], device='cuda:0')
tensor([0.8383], dtype=torch.float64)
更多推荐
所有评论(0)