pytorch教程(1.1)——认识tensor

摘要

张量是一种特殊的数据结构,与数组和矩阵非常相似。 在 PyTorch 中,我们使用张量对模型的输入和输出以及模型的参数进行编码。
张量类似于 NumPy 的 ndarray,不同之处在于张量可以在 GPU 或其他硬件加速器上运行。 事实上,张量和 NumPy 数组通常可以共享相同的底层内存,从而无需复制数据(参见 Bridge with NumPy)。 张量也针对自动微分进行了优化(我们将在后面的 Autograd 部分看到更多相关信息)。 如果您熟悉 ndarrays,那么您将熟悉 Tensor API。

import torch
import numpy as np

初始化张量

张量可以通过多种方式初始化。 看看下面的例子:

直接从数据中

可以直接从数据中创建张量。

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

从 NumPy 数组

可以从 NumPy 数组创建张量(反之亦然 - 请参阅 Bridge with NumPy)。

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

来自另一个张量:

新张量保留参数张量的属性(形状、数据类型),除非明确覆盖。

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

输出:
在这里插入图片描述

使用随机值或常量值:

形状是张量维度的元组。 在下面的函数中,它决定了输出张量的维度。

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}")

在这里插入图片描述

张量的属性

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

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}")

在这里插入图片描述

张量运算

这里全面描述了 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')
  print(f"Device tensor is stored on: {tensor.device}")

在这里插入图片描述

尝试列表中的一些操作。 如果您熟悉 NumPy API,您会发现 Tensor API 使用起来轻而易举。
标准的类似 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)

在这里插入图片描述
连接张量您可以使用 torch.cat 沿给定维度连接一系列张量。 另见torch.stack。

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
t2 = torch.cat([tensor, tensor, tensor], dim=0)
print(t2)

在这里插入图片描述
在这里插入图片描述

算术运算

a=torch.Tensor([[1,2,3],[4,5,6]])
print("a:", "\n",a)
print("矩阵相乘:", "\n", a@a.T)
print("矩阵对应位置相乘:", "\n", a*a)

在这里插入图片描述
就地操作将结果存储到操作数中的操作称为就地操作。 它们由 _ 后缀表示。 例如:x.copy_(y), x.t_(),会改变x。

print(tensor, "\n")
tensor.add_(5)
print(tensor)

在这里插入图片描述

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

使用 NumPy 桥接

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

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

在这里插入图片描述
张量的变化反映在 NumPy 数组中。

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

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

leetteel

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值