【Pytorch简介】2.What are Tensors 什么是张量?

2.What are Tensors 什么是张量?


张量是一种特殊的数据结构,与数组和矩阵非常相似。在 PyTorch 中,我们使用张量对模型的输入和输出以及模型的参数进行编码。

张量与NumPy 的ndarray类似,不同之处在于张量可以在 GPU 或其他硬件加速器上运行。事实上,张量和 NumPy 数组通常可以共享相同的底层内存,从而无需复制数据(请参阅Bridge with NumPy)。张量还针对自动微分进行了优化(稍后我们将在Autograd部分中了解更多相关内容 )。如果您熟悉 ndarrays,那么您就会熟悉 Tensor API。如果没有,那就跟随吧!

import torch
import numpy as np

Initializing a Tensor 初始化张量

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

Directly from data 直接来自数据

张量可以直接从数据创建。数据类型是自动推断的。

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

From a NumPy array 来自 NumPy 数组

张量可以从 NumPy 数组创建(反之亦然 - 请参阅Bridge with NumPy)。由于 numpy np_array 和张量 x_np 共享相同的内存位置,因此更改其中一个的值将会更改另一个。

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

print(f"Numpy np_array value: \n {np_array} \n")
print(f"Tensor x_np value: \n {x_np} \n")

np.multiply(np_array, 2, out=np_array)

print(f"Numpy np_array after * 2 operation: \n {np_array} \n")
print(f"Tensor x_np value after modifying numpy array: \n {x_np} \n")

Out:

Numpy np_array value: 
 [[1 2]
 [3 4]] 

Tensor x_np value: 
 tensor([[1, 2],
        [3, 4]]) 

Numpy np_array after * 2 operation: 
 [[2 4]
 [6 8]] 

Tensor x_np value after modifying numpy array: 
 tensor([[2, 4],
        [6, 8]]) 

From another tensor 从另一个张量

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

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.8823, 0.9150],
        [0.3829, 0.9593]])

With random or constant values 使用随机值或常数值

shape是张量维度的元组。在下面的函数中,它确定输出张量的维数。

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.3904, 0.6009, 0.2566],
        [0.7936, 0.9408, 0.1332]])

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

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

Attributes of a 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}")

Out:

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

Operations on Tensors 张量运算

这里全面描述了 100 多种张量运算,包括算术、线性代数、矩阵操作(转置、索引、切片)、采样等。

这些操作中的每一个都可以在 GPU 上运行(速度通常高于 CPU)。对于样例和复习,您可以在此处找到全面的描述。

这些操作中的每一个都可以在 GPU 上运行(速度通常高于 CPU)。

  • CPU 最多有 16 个核心。核心是进行实际计算的单元。每个核心按顺序处理任务(一次一个任务)。
  • GPU 有 1000 个核心。 GPU 核心以并行处理方式处理计算。任务在不同的核心之间划分和处理。这就是大多数情况下 GPU 比 CPU 更快的原因。 GPU 在处理大数据时比处理小数据时表现更好。 GPU 通常用于图形或神经网络的高强度计算(我们稍后将在神经网络单元中了解更多信息)。
  • PyTorch 可以使用 Nvidia CUDA 库来利用其 GPU 卡。

默认情况下,张量是在 CPU 上创建的。我们需要使用 .to方法显式地将张量移动到 GPU(在检查 GPU 可用性之后)。请记住,跨设备复制大张量在时间和内存方面可能会很昂贵!

# We move our tensor to the GPU if available
if torch.cuda.is_available():
    tensor = tensor.to("cuda")

尝试列表中的一些操作。如果您熟悉 NumPy API,您会发现 Tensor API 使用起来非常简单。

Standard numpy-like indexing and slicing 标准的类似 numpy 的索引和切片

tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"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.]])

Joining tensors 连接张量

连接张量您可以使用它torch.cat 来沿给定维度连接一系列张量。torch.stack是一个相关的张量连接选项,它沿着新维度连接一系列张量。

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.]])

Arithmetic operations 算术运算

# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
# ``tensor.T`` returns the transpose of a tensor
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

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


# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)

Out:

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

Single-element tensors 单元素张量

单元素张量如果您有一个单元素张量,例如通过将张量的所有值聚合为一个值,您可以使用以下方法将其转换为 Python 数值item()

agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))

Out:

12.0 <class 'float'>

In-place operations就地运算

就地运算 将结果存储到操作数中的操作称为就地运算。它们由_后缀表示。例如:x.copy_(y)x.t_()、 将会改变x

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

print(f"{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 笔记

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

Bridge with NumPy 与 NumPy 的桥梁

CPU 和 NumPy 数组上的张量可以共享其底层内存位置,改变其中一个就会改变另一个。

Tensor to NumPy array 张量到 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.]

NumPy array to Tensor 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.]

知识检查

张量是类似于数组和矩阵的专用数据结构。

参考文献

使用 PyTorch 进行机器学习的简介 - Training | Microsoft Learn

使用 PyTorch 进行机器学习的简介 - Training | Microsoft Learn

Github

storm-ice/PyTorch_Fundamentals

storm-ice/PyTorch_Fundamentals

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

冰雪storm

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

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

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

打赏作者

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

抵扣说明:

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

余额充值