Torch_Tensors学习

张量

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

初始化张量

直接来自数据

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

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是张量维度的元组。在下面的函数中,它决定了输出张量的维数。

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)。如果您使用 Colab,请通过转至运行时 > 更改运行时类型 > GPU 来分配 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 使用起来非常简单。

标准的类似 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)

连接张量您可以使用torch.cat它来沿给定维度连接一系列张量。另请参见torch.stack,这是另一个与 略有不同的张量连接运算符torch.cat。

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

算术运算

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

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

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

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

print(f"{tensor} \n")
tensor.add_(5)
print(tensor)

与 NumPy 的桥梁

张量到 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}")

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}")
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
torch.broadcast_tensors函数是PyTorch中用于将张量进行广播运算的函数。在机器学习中,广播运算主要用于将数据进行扩展以便进行计算。比如,计算两个形状不同的张量的和,需要将其中一个张量进行扩展至和另一个张量的形状相同,才能进行计算。 在PyTorch中,torch.broadcast_tensors函数可以将输入的多个张量进行扩展,使它们的形状相同,然后返回扩展后的张量组成的元组。该函数的输入可以是任意数量的张量(至少一个),并且它们的形状必须能够满足广播规则(即能够通过扩展变为相同形状)。 该函数的实现主要依赖于numpy中的broadcast_arrays函数,但要求其输入和输出都是PyTorch张量,因此其返回值是由PyTorch张量组成的元组。该函数返回的所有张量都是新的对象,即它们的数据不共享内存空间。这是为了避免在广播过程中修改原始张量的数据。 例如,以下是使用torch.broadcast_tensors函数将两个张量进行扩展的示例: ``` import torch x = torch.tensor([1, 2, 3]) # shape: (3,) y = torch.tensor([[4], [5]]) # shape: (2, 1) x, y = torch.broadcast_tensors(x, y) print(x) print(y) ``` 输出结果为: ``` tensor([[1, 2, 3], [1, 2, 3]]) tensor([[4, 4, 4], [5, 5, 5]]) ``` 在该示例中,第一个张量x的形状为(3,),第二个张量y的形状为(2, 1)。经过广播计算后,它们的形状都变为了(2, 3),并且将分别被存储在新的张量对象x和y中。这样就可以对两个形状不同的张量进行计算了。 总之,torch.broadcast_tensors函数是实现PyTorch张量广播计算的重要工具,它可以将多个张量进行扩展,使它们的形状相同并满足广播规则,从而便于进行计算。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值