Pytorch入门演练

Pytorch入门演练

Pytorch是一个基于Python的科学计算软件包,有以下两种定位:

可以使用多GPU加速的NumPy替代品

提供最大限度灵活性与速度的深度学习研究平台

一 入门

1. Tensors(张量)

Tensors(张量)类似于NumPy中的ndarray,还可以使用GPU加速计算。

from __future__ import print_function
import torch

构造一个未初始化的5*3矩阵:

x = torch.empty(5, 3)
print(x)

输出:

tensor([[-9.0198e-17, 4.5633e-41, -2.9021e-15],
[ 4.5633e-41, 0.0000e+00, 0.0000e+00],
[ 0.0000e+00, 0.0000e+00, 0.0000e+00],
[ 0.0000e+00, 0.0000e+00, 0.0000e+00],
[ 0.0000e+00, 0.0000e+00, 0.0000e+00]])

构造一个随机初始化的矩阵:

x = torch.rand(5, 3) 

print(x)

输出:

tensor([[0.1525, 0.7689, 0.5664],
[0.7688, 0.0039, 0.4129],
[0.9979, 0.3479, 0.2767],
[0.9580, 0.9492, 0.6265],
[0.2716, 0.6627, 0.3248]])

构造一个使用零填充、数据类型为long(长整型)的5*3矩阵:

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(张量)。除非用户提供新值,否则这些方法将重用输入张量的属性,例如dtype:

x = x.new_ones(5, 3, dtype=torch.double) # 使用new_* 方法设定维度 

print(x)
x = torch.randn_like(x, dtype=torch.float) # 重新设定数据类型
Print(x) # 结果维度不变

输出:

tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor([[ 0.4228, 0.3279, 0.6367],
[ 0.9233, -0.5232, -0.6494],
[-0.1946, 1.7199, -0.1954],
[ 0.1222, 0.7204, -1.3328],
[ 0.1230, -0.5800, 0.4562]])

输出它的大小:

print(x.size())

输出:

torch.Size([5, 3])

注意:torch.Size 实际上是一个元组,因此它支持所有元组操作。)

2. 运算

Tensor运算有多种语法。在下面的示例中,我们将先示例加法运算。

加法运算:语法1

y = torch.rand(5, 3) 

print(x + y)

输出:

tensor([[ 0.0732, 0.9384, -0.2489],
[-0.6905, 2.1267, 3.0045],
[ 0.6199, 0.4936, -0.0398],
[-2.0623, -0.5140, 1.6162],
[ 0.3189, -0.0327, -0.5353]])

加法运算:语法2

print(torch.add(x, y))

输出:

tensor([[ 0.0732, 0.9384, -0.2489],
[-0.6905, 2.1267, 3.0045],
[ 0.6199, 0.4936, -0.0398],
[-2.0623, -0.5140, 1.6162],
[ 0.3189, -0.0327, -0.5353]])

加法运算:使用输出Tensor(张量)作为参数

result = torch.empty(5, 3)torch.add(x, y, out=result)
print(result)

输出:

tensor([[ 0.0732, 0.9384, -0.2489],
[-0.6905, 2.1267, 3.0045],
[ 0.6199, 0.4936, -0.0398],
[-2.0623, -0.5140, 1.6162],
[ 0.3189, -0.0327, -0.5353]])

加法运算:内联接

# adds x to y
y.add_(x)
print(y)

输出:

tensor([[ 0.0732, 0.9384, -0.2489],
[-0.6905, 2.1267, 3.0045],
[ 0.6199, 0.4936, -0.0398],
[-2.0623, -0.5140, 1.6162],
[ 0.3189, -0.0327, -0.5353]])

注意:任何改变原张量实现内联接的操作都是通过在后边加_ 实现的。例如:x.copy_(y),x.t_(),将将改变x的值。】

你可以像在NumPy中一样使用索引及其他所有华丽的功能。

print(x[:, 1])

输出:

tensor([ 0.3279, -0.5232, 1.7199, 0.7204, -0.5800])

Resizing(调整大小):如果要resize/reshape张量,可以使用torch.view:

x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # -1是推断出来的
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.1550])
0.15495021641254425

【延伸阅读:

100+张量操作,包括置换,索引,切片,数学运算,线性代数,随机数等等,被详细描述在这里(https://pytorch.org/docs/torch)。】

NUMPY桥接器

将Torch Tensor转换为NumPy array是一件轻而易举的事(反之亦然)。

Torch Tensor和NumPy array共享其底层内存位置,更改一个将改变另一个。

1. 将Torch Tensor转换为NumPy array

a = torch.ones(5)
print(a)

输出:

tensor([1., 1., 1., 1., 1.])
b = a.numpy()

print(b)

输出:

[1. 1. 1. 1. 1.]

了解numpy array的值如何变化。

a.add_(1)
print(a)
print(b)

输出:

tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]

2. 将NumPy array转换为Torch Tensor

了解如何自动地将np array更改为Torch Tensor

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)

除了Char(字符型) Tensor之外,CPU上的所有Tensors都支持转换为NumPy及返回。

三 CUDA TENSORS(张量)

可以使用.to方法将张量移动到任何设备上。

# 仅当CUDA可用的情况下运行这个cell 
# 我们用 ``torch.device`` 对象实现tensors在GPU上的写入与读出if torch.cuda.is_available():
device = torch.device("cuda") # 一个 CUDA 终端对象
y = torch.ones_like(x, device=device) # 直接在GUP上创建Tensor
x = x.to(device) # 或者直接使用字符串`.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # `.to`` 也可以改变对象数据类型

输出:

tensor([2.4519], device='cuda:0')
tensor([2.4519], dtype=torch.float64)

脚本总运行时间:(0分6.338秒)

下载python源代码文件:tensor——tutorial.py

(https://pytorch.org/tutorials/_downloads/092fba3c36cb2ab226bfdaa78248b310/tensor_tutorial.py)

下载Jupyter notebook文件:tensor——tutorial.ipynb

(https://pytorch.org/tutorials/_downloads/3c2b25b8a9f72db7780a6bf9b5fc9f62/tensor_tutorial.ipynb)


分享到:


相關文章: