pytorch学习-tensors

一、头文件

import torch
import numpy as np

二、定义一个张量

  1. 张量可以直接从数据中创建。数据类型是自动推断的。
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
  1. 从 NumPy 数组获取张量
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
  1. 从张量中获取张量
    除非明确覆盖,否则新张量保留参数张量的属性(形状、数据类型)。
x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")

Out

Ones Tensor:
 tensor([[1, 1],
        [1, 1]])

Random Tensor:
 tensor([[0.5566, 0.8507],
        [0.2956, 0.7017]])
  1. 使用随机值或常量值获取张量
    形状是张量维度的元组。在下面的函数中,它决定了输出张量的维度。
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")

Out

Random Tensor:
 tensor([[0.2543, 0.5428, 0.9277],
        [0.8630, 0.6125, 0.7287]])

Ones Tensor:
 tensor([[1., 1., 1.],
        [1., 1., 1.]])

Zeros Tensor:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

三、张量的属性

张量属性描述了它们的形状、数据类型和存储它们的设备。

tensor = torch.rand(3,4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")

Out

Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

四、张量运算

张量的操作包含100多种(从这里可以查阅到),每一个都可以在 GPU 上运行(速度通常比在 CPU 上更高)。
默认情况下,张量是在 CPU 上创建的。我们需要使用 .to 方法(在检查 GPU 可用性之后)显式地将张量移动到 GPU。请记住,跨设备复制大张量在时间和内存方面可能很昂贵!

# We move our tensor to the GPU if available
if torch.cuda.is_available():
  tensor = tensor.to('cuda')
  1. 标准的类似 numpy 的索引和切片:
tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])
tensor[:,1] = 0
print(tensor)

Out

First row:  tensor([1., 1., 1., 1.])
First column:  tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
  1. 连接张量
    可以使用 torch.cat 沿给定维度连接一系列张量。另见torch.stack,另一个连接张量的方法,与torch.cat略有不同。
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)

Out

tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])
  1. 算术运算
# 这将计算两个张量之间的矩阵乘法。 y1, y2, y3 将具有相同的值
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)


# 这将计算逐元素乘积。 z1, z2, z3 将具有相同的值
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
  1. 单元素张量
    如果有一个单元素张量,例如通过将张量的所有值聚合为一个值,使用 item() 将其转换为 Python 数值:
agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))

Out

12.0 <class 'float'>
  1. 就地操作
    将结果存储到操作数中的操作被称为就地。它们由 _ 后缀表示。例如:x.copy_(y), x.t_(),会改变x。
print(tensor, "\n")
tensor.add_(5)
print(tensor)

Out

tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor([[6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.]])

Note:
就地操作节省了一些内存,但在计算导数时可能会出现问题,因为会立即丢失历史记录。因此,不鼓励使用它们。

五、与 NumPy 的桥接

CPU上的张量 和 NumPy 数组上的张量可以共享它们的底层内存位置,改变一个将改变另一个。

  1. 张量到 NumPy 数组
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

Out

t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

张量的变化反映在 NumPy 数组中。

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")

Out

t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
  1. NumPy 数组到张量
n = np.ones(5)
t = torch.from_numpy(n)

NumPy 数组中的变化反映在张量中。

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")

Out

t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]
posted @ 2021-08-03 18:59  小Aer  阅读(2)  评论(0编辑  收藏  举报  来源