首页 > 编程笔记 > Python笔记 阅读:16

PyTorch张量的基本运算(附带实例)

在深度学习中,数据(图像、文本、视频、音频、蛋白质结构等)被表示为张量。

模型通过研究这些张量并对张量执行一系列操作来学习,以创建输入数据中模式的表示。这些操作通常是相加、相减、相乘、除、矩阵乘法。当然,还有一些操作,但这些是神经网络的基本组成部分。

以正确的方式堆叠这些构建块,就可以创建最复杂的神经网络。

下面从一些基本运算开始介绍,如加法(+)、减法(-)、乘法(*),代码如下:
>>> # Create a tensor of values and add a number to it
>>> tensor = torch.tensor([1, 2, 3])
>>> tensor + 10
tensor([11, 12, 13])
>>> # Multiply it by 10
>>> tensor * 10
tensor([10, 20, 30])

注意,上面的张量值最终并不是 tensor([10, 20, 30]),这是因为张量内部的值不会改变,除非它们被重新分配,代码如下:
>>> # Tensors don't change unless reassigned
>>> tensor
tensor([1, 2, 3])

减去一个数字,重新分配张量变量,代码如下:
>>> # Subtract and reassign
>>> tensor = tensor - 10
>>> tensor
tensor([-9, -8, -7])
>>> # Add and reassign
>>> tensor = tensor + 10
>>> tensor
tensor([1, 2, 3])

PyTorch 还有一组内置函数,如 torch.mul() 和 torch.add(),用于执行基本运算,代码如下:
>>> # Can also use torch functions
>>> tensor = torch.multiply(tensor, 10)
>>> tensor
tensor([10, 20, 30])
>>> # Original tensor is still unchanged
>>> tensor
tensor([1, 2, 3])

更常见的是使用像“*”这样的运算符符号,而不是 torch.mul(),代码如下:
>>> # Element-wise multiplication
>>> # (each element multiplies its equivalent, index 0->0, 1->1, 2->2)
>>> print(tensor, "*", tensor)
tensor([1, 2, 3]) * tensor([1, 2, 3])
>>> print("Equals:", tensor * tensor)
Equals: tensor([1, 4, 9])

机器学习和深度学习算法中最常见的操作之一是矩阵乘法。PyTorch 在 torch.matmul() 方法中可以实现矩阵乘法功能。

矩阵乘法的两个主要规则如下:
① 内部尺寸必须匹配:
② 得到的矩阵具有外部尺寸的形状:
创建一个张量,并对其执行元素乘法和矩阵乘法,代码如下:
>>> import torch
>>> tensor = torch.tensor([1, 2, 3])
>>> tensor.shape
torch.Size([3])
>>> # Element-wise matrix multiplication
>>> tensor * tensor
tensor([1, 4, 9])
>>> # Matrix multiplication
>>> torch.matmul(tensor, tensor)
tensor(14)
>>> # Can also use the "@" symbol for matrix multiplication, though not recommended
>>> tensor @ tensor
tensor(14)
可以手工做矩阵乘法,但不建议这样做,因为内置的 torch.matmul() 方法速可以手工做矩阵乘法,但不建议这样做,因为内置的 torch.matmul() 方法速度更快。

相关文章