60分钟入门PyTorch1


注: 本文的翻译基于PyTorch官方文档(1.0.0.dev20190125),在翻译的过程中参考了( https://ptorch.com/docs/3/tensor_tutorial).

入门

张量(Tensors)

Tensors类似于numpyndarrays,另外还可以在GPU上使用Tensors来加速计算。

from __future__ import print_function
import torch

构造一个5x3矩阵,未初始化:

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

输出:

tensor([[-1.1015e-07,  4.5807e-41, -3.5803e-06],
        [ 4.5807e-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.9727, 0.8805, 0.5857],
        [0.1284, 0.4006, 0.1293],
        [0.5041, 0.9665, 0.4347],
        [0.0748, 0.1356, 0.5269],
        [0.2129, 0.0561, 0.2891]])

构造一个零矩阵并且类型为torch.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的属性,除非用户赋予一个新的值。

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! 覆盖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.3323, -0.8246,  1.5832],
        [ 0.1779, -0.0341, -0.3968],
        [-0.4179,  1.3846,  1.0981],
        [-1.5426, -0.4654, -0.6574],
        [-0.9417, -0.0177, -1.1593]])

得到tensor的大小:

print(x.size())

输出:

torch.Size([5, 3])

注:torch.Size输出为一个元组,因此它支持所有关于元组的操作。

运算(Operations)

运算的操作很多,在下面的示例中,我们将查看加法操作。

  1. 例1
y = torch.rand(5, 3)
print(x + y)

输出:

tensor([[ 0.4512, -0.4297,  2.0196],
        [ 1.0648,  0.4395,  0.4832],
        [ 0.2238,  1.5926,  1.7444],
        [-1.1602, -0.1060,  0.1966],
        [-0.4518,  0.6022, -0.3636]])
  1. 例2
print(torch.add(x, y))

输出:

tensor([[ 0.4512, -0.4297,  2.0196],
        [ 1.0648,  0.4395,  0.4832],
        [ 0.2238,  1.5926,  1.7444],
        [-1.1602, -0.1060,  0.1966],
        [-0.4518,  0.6022, -0.3636]])
  1. 例3
    利用已提供的tensor作为参数。
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
tensor([[ 0.4512, -0.4297,  2.0196],
        [ 1.0648,  0.4395,  0.4832],
        [ 0.2238,  1.5926,  1.7444],
        [-1.1602, -0.1060,  0.1966],
        [-0.4518,  0.6022, -0.3636]])
  1. 例4 in-place追加
# adds x to y
y.add_(x)
print(y)

输出:

tensor([[ 0.4512, -0.4297,  2.0196],
        [ 1.0648,  0.4395,  0.4832],
        [ 0.2238,  1.5926,  1.7444],
        [-1.1602, -0.1060,  0.1966],
        [-0.4518,  0.6022, -0.3636]])

注: 该变异就地张量的任何操作是后固定有,例如:x.copy_(y)x.t_(),将改变x.
你可以使用标准的NumPy索引!

print(x[:, 1])

输出:

tensor([-0.8246, -0.0341,  1.3846, -0.4654, -0.0177])

重塑:如果你想调整tonsor的形状,你可以使用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])

如果你想获得一个tonsor的值,使用.item().

x = torch.randn(1)
print(x)
print(x.item())

输出:

tensor([0.9806])
0.9805544018745422

稍后阅读:超过100+的tonsor操作,包括转位、分度、切片、数学运算、线性代数和随机等请查看(https://pytorch.org/docs/stable/torch.html)

Numpy转换

TorchtonsorNumpy数组之间进行转换

TorchtonsorNumpy数组共享底层存储位置,更改一个将改变另一个。
例子

Torchtonsor to Numpy数组

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

Out:

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

Out:

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

Out:

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

Numpy数组 to Torchtonsor

看到如何更改Numpy数组自动与Torchtonsor 之间连锁变动。

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)

Out:

[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

除了CharTensor之外,CPU上的所有传感器都支持转换为NumPy并返回

CUDA Tensors

可以使用该.to功能将传感器移动到GPU上。

# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
#我们使用 ``torch.device``将对象**tonsor**移进或者移出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!
    

Out:

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

以上的源代码
tensor_tutorial.py
tensor_tutorial.ipynb

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值