Pytorch 笔记

执行下面这段代码后,为什么返回的是 2 ?

python 复制代码
vector = torch.tensor([7, 7])
vector.shape

为什么返回的是 torch.Size([2])

当你创建一个PyTorch张量时,它会记住张量中元素的数量每个维度的大小 。在你的代码中,torch.tensor([7, 7])创建了一个一维张量 ,其中包含两个元素:7和7。因为这是一个一维张量,所以.shape属性返回一个只有一个元素的元组该元素表示张量的长度 。在这种情况下,张量的长度为2,因此返回的形状是torch.Size([2])

tensor 的维度

python 复制代码
TENSOR = torch.tensor([[[1, 2, 3],
                        [3, 6, 9],
                        [2, 4, 5]]])
TENSOR.ndim

返回的是 [1,3,3] , 如何判断?有三层 [ ] 括号,将每个 [ ] 括号视为列表,从最里层起,当前列表有几个并列的元素,TENSOR.ndim 返回的列表最右边的元素就是几,然后去掉最外面一层的 [ ] 括号,继续判断当前列表有几个并列的元素,TENSOR.ndim 返回的列表次右边的元素就是几,依次类推。

Scalar,Vector,Matrix,Tensor

torch.arange()

torch.arange() 返回的是 PyTorch 中的 tensor,而不是 NumPy 数组。

torch中对tensor的各种切片操作

好的,让我们使用一个三维张量来详细解释各种复杂的切片操作。我们首先创建一个形状为 2 × 3 × 4 2 \times 3 \times 4 2×3×4 的三维张量:

python 复制代码
import torch

# 创建一个形状为 2x3x4 的三维张量
tensor = torch.arange(24).reshape(2, 3, 4)
print("Original Tensor:")
print(tensor)

假设我们有一个如下所示的三维张量:

tensor([[[ 0,  1,  2,  3],
         [ 4,  5,  6,  7],
         [ 8,  9, 10, 11]],

        [[12, 13, 14, 15],
         [16, 17, 18, 19],
         [20, 21, 22, 23]]])

1. 选择特定的切片

选择第一个维度的第一个子张量
python 复制代码
slice_1 = tensor[0, :, :]
print("Slice along the first dimension (index 0):")
print(slice_1)

输出:

tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
选择第二个维度的第二个子张量
python 复制代码
slice_2 = tensor[:, 1, :]
print("Slice along the second dimension (index 1):")
print(slice_2)

输出:

tensor([[ 4,  5,  6,  7],
        [16, 17, 18, 19]])
选择第三个维度的第三个子张量
python 复制代码
slice_3 = tensor[:, :, 2]
print("Slice along the third dimension (index 2):")
print(slice_3)

输出:

tensor([[ 2,  6, 10],
        [14, 18, 22]])

2. 高级切片操作

选择第一个维度的第一个子张量中的第1到第2行(不包括第2行)
python 复制代码
slice_4 = tensor[0, 0:1, :]
print("Slice along the first dimension (index 0) and rows 0 to 1:")
print(slice_4)

输出:

tensor([[0, 1, 2, 3]])
选择第二个维度的第0和第2行,并选择所有列
python 复制代码
slice_5 = tensor[:, [0, 2], :]
print("Select rows 0 and 2 from the second dimension:")
print(slice_5)

输出:

tensor([[[ 0,  1,  2,  3],
         [ 8,  9, 10, 11]],

        [[12, 13, 14, 15],
         [20, 21, 22, 23]]])
选择第三个维度的第1和第3列
python 复制代码
slice_6 = tensor[:, :, [1, 3]]
print("Select columns 1 and 3 from the third dimension:")
print(slice_6)

输出:

tensor([[[ 1,  3],
         [ 5,  7],
         [ 9, 11]],

        [[13, 15],
         [17, 19],
         [21, 23]]])

3. 使用布尔张量进行索引

选择大于10的元素
python 复制代码
mask = tensor > 10
slice_7 = tensor[mask]
print("Elements greater than 10:")
print(slice_7)

输出:

tensor([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23])

4. 使用长整型张量进行索引

选择第1和第3列的数据
python 复制代码
indices = torch.tensor([1, 3])
slice_8 = tensor[:, :, indices]
print("Select columns indexed by [1, 3]:")
print(slice_8)

输出:

tensor([[[ 1,  3],
         [ 5,  7],
         [ 9, 11]],

        [[13, 15],
         [17, 19],
         [21, 23]]])

5. 花式索引

使用多个索引数组
python 复制代码
rows = torch.tensor([0, 1])
cols = torch.tensor([2, 3])
slice_9 = tensor[0, rows, cols]
print("Fancy indexing with rows and cols:")
print(slice_9)

输出:

tensor([2, 7])

通过这些示例,希望你对 PyTorch 中的张量索引和切片操作有了更深入的理解。这些操作在数据预处理、特征提取和神经网络模型的实现中非常重要。

torch 中 tensor 的各种乘法

在 PyTorch 中,有多种实现张量相乘的方式,每种方式在实现上有一些差异,有些是就地操作,有些不是。以下是几种主要的实现方式:

1. 元素级相乘 (Element-wise Multiplication)

要求两个 tensor 的 shape 一致

使用 * 操作符
python 复制代码
import torch

a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([[5, 6], [7, 8]])

result = a * b
print(result)
使用 torch.mul()
python 复制代码
result = torch.mul(a, b)
print(result)
就地操作

使用 mul_() 方法:

python 复制代码
a.mul_(b)
print(a)

2. 矩阵乘法 (Matrix Multiplication)

使用 @ 操作符 (Python 3.5+)
python 复制代码
result = a @ b.T  # 转置 b 以使其形状匹配矩阵乘法要求
print(result)
使用 torch.matmul()
python 复制代码
result = torch.matmul(a, b.T)
print(result)
使用 torch.mm()(仅适用于二维张量)
python 复制代码
result = torch.mm(a, b.T)
print(result)

3. 广义点积 (Dot Product for 1D tensors)

使用 torch.dot()
python 复制代码
c = torch.tensor([1, 2, 3])
d = torch.tensor([4, 5, 6])

result = torch.dot(c, d)
print(result)

4. 批量矩阵乘法 (Batch Matrix Multiplication)

使用 torch.bmm()
python 复制代码
e = torch.randn(10, 3, 4)  # 形状为 (batch_size, m, n)
f = torch.randn(10, 4, 5)  # 形状为 (batch_size, n, p)

result = torch.bmm(e, f)
print(result)

5. 广播相乘 (Broadcast Multiplication)

张量会自动广播到兼容的形状。

python 复制代码
g = torch.tensor([1, 2, 3])
h = torch.tensor([[1], [2], [3]])

result = g * h
print(result)

就地操作总结

就地操作会直接修改原始张量的值,通常以 _ 结尾:

  • a.mul_(b):就地进行元素级相乘

非就地操作会创建新的张量并返回结果,而不改变输入张量的值。

这些不同的乘法操作方式在不同的应用场景中有不同的用途,根据需要选择适合的乘法方式。

相关推荐
我命由我123452 分钟前
SSL 协议(HTTPS 协议的关键)
网络·经验分享·笔记·学习·https·ssl·学习方法
肖遥Janic13 分钟前
Stable Diffusion绘画 | 插件-Deforum:动态视频生成(上篇)
人工智能·ai·ai作画·stable diffusion
robinfang201920 分钟前
AI在医学领域:Arges框架在溃疡性结肠炎上的应用
人工智能
给自己一个 smile24 分钟前
如何高效使用Prompt与AI大模型对话
人工智能·ai·prompt
丶Darling.42 分钟前
代码随想录 | Day26 | 二叉树:二叉搜索树中的插入操作&&删除二叉搜索树中的节点&&修剪二叉搜索树
开发语言·数据结构·c++·笔记·学习·算法
魔力之心1 小时前
人工智能与机器学习原理精解【30】
人工智能·机器学习
Hiweir ·1 小时前
NLP任务之文本分类(情感分析)
人工智能·自然语言处理·分类·huggingface
百里香酚兰1 小时前
【AI学习笔记】基于Unity+DeepSeek开发的一些BUG记录&解决方案
人工智能·学习·unity·大模型·deepseek
结衣结衣.2 小时前
python中的函数介绍
java·c语言·开发语言·前端·笔记·python·学习
LN-ZMOI2 小时前
c++学习笔记1
c++·笔记·学习