Pytorch系列之tensor(超详细)

官网链接:https://pytorch.org

背景

上一篇文章中详细介绍了pytorch如何在不同设备上安装,本文将pytorch的tensor用法和不同API介绍

什么是PYTORCH?

  • 替代NumPy以使用GPU的功能
  • 提供最大灵活性和速度的深度学习研究平台

tensor(张量)

Tensors与NumPy的ndarrays类似,此外,Tensors也可以在GPU上使用以加速计算。

from __future__ import print_function
import torch

声明了一个未初始化的矩阵,但在使用前不包含确定的已知值。创建未初始化的矩阵时,当时分配的内存中的任何值都将显示为初始值。

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

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

终端显示:

tensor([[ 6.0629e+10,  4.5886e-41, -1.6731e+21],
        [ 3.0791e-41,  0.0000e+00,  1.4013e-45],
        [ 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.5683, 0.1334, 0.7669],
        [0.8196, 0.1895, 0.6653],
        [0.3621, 0.8314, 0.6239],
        [0.8716, 0.2269, 0.1005],
        [0.3598, 0.1292, 0.5585]])

构造一个填充零且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]])

直接从数据构造张量:

x = torch.tensor([5.5, 3])
print(x)

终端显示:

tensor([5.5000, 3.0000])

或基于现有张量创建张量。这些方法将重用输入张量的属性,例如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([[-1.4401,  0.0466, -2.1937],
        [-1.0154, -0.0305, -0.3228],
        [ 0.9465, -0.9894,  1.3261],
        [ 1.0201, -0.2246, -0.4310],
        [ 0.1879,  0.5790,  1.0969]])

得到它的大小:

print(x.size())

终端显示:

torch.Size([5, 3])

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

操作方式

加法:语法1

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

终端显示:

tensor([[-1.1343,  0.5873, -2.0787],
        [-0.8963,  0.2650, -0.0433],
        [ 1.0377, -0.3409,  1.5968],
        [ 1.7182,  0.2011,  0.1942],
        [ 0.6774,  1.1133,  1.3968]])

加法:语法2

print(torch.add(x, y))

终端显示:

tensor([[-1.1343,  0.5873, -2.0787],
        [-0.8963,  0.2650, -0.0433],
        [ 1.0377, -0.3409,  1.5968],
        [ 1.7182,  0.2011,  0.1942],
        [ 0.6774,  1.1133,  1.3968]])

加法:语法3

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

终端显示:

tensor([[-1.1343,  0.5873, -2.0787],
        [-0.8963,  0.2650, -0.0433],
        [ 1.0377, -0.3409,  1.5968],
        [ 1.7182,  0.2011,  0.1942],
        [ 0.6774,  1.1133,  1.3968]])

加法:提供输出张量作为参数

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

终端显示:

tensor([[-1.1343,  0.5873, -2.0787],
        [-0.8963,  0.2650, -0.0433],
        [ 1.0377, -0.3409,  1.5968],
        [ 1.7182,  0.2011,  0.1942],
        [ 0.6774,  1.1133,  1.3968]])

使用索引类似NumPy的索引!

print(x[:, 1])

终端显示:

tensor([ 0.0466, -0.0305, -0.9894, -0.2246,  0.5790])

调整大小:如果要调整张量的大小/形状,可以使用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([-2.4280])
-2.428037405014038

将torch张量转换为NumPy数组

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

终端显示:

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

将NumPy数组转换为Torch张量

除CharTensor之外,CPU上的所有张量都支持转换为NumPy并返回。

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)

CUDA张量

使用该.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([-1.4280], device='cuda:0')
tensor([-1.4280], dtype=torch.float64)
发布了74 篇原创文章 · 获赞 47 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_40639095/article/details/103985001