【Pytorch 学习笔记(一)】:Tensor相关

Tensors 基本操作

100+ tensor相关的操作符文档

Tensor 和NumPy 中的ndarray相似。

new

我们可以通过这样的方式来新建一个tensor:

  • 新建一个未初始化的5x3矩阵:
x = torch.empty(5, 3)
print(x)

输出:

tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])
  • 新建一个随机初始化的矩阵:
x = torch.rand(5, 3)
print(x)

输出:

tensor([[0.4494, 0.6230, 0.8681],
        [0.0780, 0.2643, 0.0934],
        [0.1205, 0.0813, 0.9454],
        [0.4212, 0.2899, 0.8791],
        [0.1500, 0.6572, 0.4772]])
  • 新建一个0矩阵,且数据类型为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])

或者,我们也可以通过已有的tensor来构建新的tensor,如果我们不给其赋新值得话(如dtype等),则会沿用之前的属性。

x = x.new_ones(5, 3, dtype = torch.double)
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.2552,  2.0007,  0.0682],
        [-0.8530, -0.1174, -0.6569],
        [-1.1001,  0.8416, -1.3575],
        [-1.0513,  0.4601,  0.6628],
        [ 2.0841, -0.4303,  0.3235]])

输出tensor的大小

print(x.size())

输出,此处的torch.Size其实是一个元组,所以它支持所有元组的操作

torch.Size([5, 3])

add

  • x + y
  • torch.add(x, y)
  • torch.add(x, y, out = result) 可以设置一个argument来保存输出
result = torch.empty(5, 3)
torch.add(x, y, out = result)
print(result)

输出:

tensor([[ 0.7021,  2.1474,  0.0886],
        [-0.5905,  0.0338,  0.2445],
        [-0.9172,  1.5455, -1.1381],
        [-0.6434,  0.5016,  1.0220],
        [ 2.9464, -0.1195,  1.0920]])
  • y.add_(x)

Tips: 在操作符后面有时会看到有_,此时是指在对该tensor做操作时,不会经过复制操作,而是直接在该位置上改变它的值,也就相当于“原地操作”(英文中叫in-place version,相对应的还有out-of-place version)。有些操作,如add,两种version都可以使用,但这并不对所有的操作成立:如narrow没有in-place version,所以.narrow_不存在;同样的,对于fill_也没有out-of-place version,所以.fill不存在。

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

我们同样可以像numpy一样对tensor做操作:

print(x[:, 1])

view

主要的作用是resize,相当于numpy中resize()的功能。同时还可以通过x.resize_(2, 3)来作reshape的操作。

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())

在参数中,-1 会把张量展开成一维张量(如果别的维度不为0,则会相应改变)

torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

item

如果有只有一个元素的张量,可以用.item()来获得值。

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

输出:

tensor([0.5746])
0.5746164917945862

NumPy Bridge

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.]
a.add_(1)
print(a)
print(b)

输出:

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

NumPy 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)

注意此处b的值会随着a的变化而变化

CUDA Tensors

我们可以通过.to方法将tensor移动到任何设备中。

# 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!

总结自

发布了50 篇原创文章 · 获赞 51 · 访问量 1970

猜你喜欢

转载自blog.csdn.net/Chen_2018k/article/details/105616776