深度学习--基础语法
目录
使用 torch.Tensor() 创建指定大小的张量 f:
1. 使用 torch.rand() 创建随机初始化的张量 g:
2. 使用 torch.randn() 创建从标准正态分布中采样的张量 h:
3. 使用 torch.randn_like() 根据现有张量 g 的形状创建新的张量 i:
2. 使用 torch.arange() 指定步长生成等差序列:
3. 使用 torch.linspace() 生成等间隔序列:
pytorch的tensor与numpy
关系
PyTorch 的 Tensor 和 NumPy 的 ndarray 在很多方面非常相似,它们都是用来存储和操作多维数据的数据结构,但它们也有一些重要的区别。
相似性:
数据类型支持:PyTorch 的 Tensor 和 NumPy 的 ndarray 都支持多种数据类型,如浮点数、整数等,并且可以通过指定 dtype 来指定数据类型。
多维数组:两者都支持多维数组操作,可以通过索引访问元素,并支持切片操作。
数学操作:PyTorch 的 Tensor 和 NumPy 的 ndarray 都支持广播(broadcasting)和各种数学操作,如加法、乘法、矩阵乘法等。
与 CPU/GPU 的兼容性:两者都能够在 CPU 和 GPU 上进行计算,且切换方式类似。
区别:
自动求导:PyTorch 的 Tensor 支持自动求导(Autograd),这意味着可以在计算中记录操作,并自动计算梯度。NumPy 的 ndarray 不支持自动求导功能。
计算性能:PyTorch 的 Tensor 针对深度学习任务进行了优化,特别是在 GPU 上的计算性能通常比 NumPy 的 ndarray 更高效。
库生态系统:PyTorch 作为一个深度学习库,有着丰富的深度学习函数和模型库,能够进行神经网络的构建、训练和部署。NumPy 则更为通用,适合于广泛的科学计算任务。
NumPy 示例:
import numpy as np
# 创建一个 NumPy 数组
a = np.array([[1, 2, 3], [4, 5, 6]])
# 访问元素
print(a[0, 1]) # 输出: 2
# 数学操作
b = np.array([[7, 8, 9], [10, 11, 12]])
c = a + b
print(c) # 输出: [[ 8 10 12]
# [14 16 18]]
PyTorch 示例:
import torch
# 创建一个 PyTorch Tensor
d = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 访问元素
print(d[0, 1]) # 输出: tensor(2)
# 数学操作
e = torch.tensor([[7, 8, 9], [10, 11, 12]])
f = d + e
print(f) # 输出: tensor([[ 8, 10, 12],
# [14, 16, 18]])
tensor与numpy的转换:
import torch
import numpy as np
print(torch.__version__)
a=np.array([[1,2],[3,4]])#numpy数组
print(type(a))
print(a)
print()
b=torch.tensor([[1,2,3],[4,5,6]])#torch张量
print(type(b))
print(b)
print()
c = b.numpy() #torch张量转换numpy数组
print(type(c))
print(c)
print()
结果
1.9.1
<class 'numpy.ndarray'>
[[1 2]
[3 4]]
<class 'torch.Tensor'>
tensor([[1, 2, 3],
[4, 5, 6]])
<class 'numpy.ndarray'>
[[1 2 3]
[4 5 6]]
<class 'torch.Tensor'>
tensor([[1, 2, 3],
[4, 5, 6]])
区别:
tensor与numpy在输出时tensor会显示tensor的标志
<class 'numpy.ndarray'>
[[1 2 3]
[4 5 6]]
<class 'torch.Tensor'>
tensor([[1, 2, 3],
[4, 5, 6]])
创建tensor
一 numpy数组,list列表转换为tensor
a=np.array([[1,2],[3,4]])#numpy二维数组
print(a)
print()
b=torch.from_numpy(a)#numpy数组转换为tensor张量
print(b)
print()
c=torch.tensor([2,1.2])#list转换为tensor张量
print(c)
d=torch.tensor([[1,2],[3,4]])
print(d)
[[1 2]
[3 4]]
tensor([[1, 2],
[3, 4]], dtype=torch.int32)
tensor([2.0000, 1.2000])
tensor([[1, 2],
[3, 4]])
二 未初始化创建tensor
torch.empty(1) 创建了一个包含一个元素的未初始化张量,输出可能接近于 0,但确切的值取决于内存状态。
torch.Tensor(2, 3) 创建了一个 2x3 的张量,并且初始化了其值为 [0, 1) 内的随机数。
创建空的 PyTorch 张量 e:
e=torch.empty(1)
print(e)
tensor([2.0000])
这段代码创建了一个大小为 (1,) 的空张量 e。torch.empty() 函数会创建一个未初始化的张量,其值取决于内存的状态。这意味着张量的内容可以是任意值,而不是零或其他特定值。
使用 torch.Tensor() 创建指定大小的张量 f:
f=torch.Tensor(2,3)
print(f)
tensor([[0., 0., 0.],
[0., 0., 0.]])
这里使用了 torch.Tensor() 函数创建了一个 2x3 的张量 f。与 torch.empty() 不同,torch.Tensor() 会创建一个具有指定形状的张量,并初始化其值。默认情况下,这些值是在区间 [0, 1) 内的随机数。
三 随机生成tensor
torch.rand() 用于创建从 [0, 1) 均匀分布中采样的张量。
torch.randn() 用于创建从标准正态分布中采样的张量。
torch.randn_like() 用于根据输入张量的形状创建新的张量,并从标准正态分布中采样值。
1. 使用 torch.rand() 创建随机初始化的张量 g:
g=torch.rand(3,3)
print(g)
tensor([[0.0023, 0.5854, 0.4163],
[0.4341, 0.5436, 0.8461],
[0.8126, 0.6083, 0.6263]])
这段代码创建了一个形状为 (3, 3) 的张量 g,其中的元素是从 [0, 1) 的均匀分布中随机采样的值。
2. 使用 torch.randn() 创建从标准正态分布中采样的张量 h:
h=torch.randn(3,3)
print(h)
tensor([[-0.5487, 1.3024, 1.4909],
[-0.1682, 0.8304, -1.1007],
[ 0.3323, 1.3830, 2.4619]])
这段代码创建了一个形状为 (3, 3) 的张量 h,其中的元素是从标准正态分布(均值为 0,标准差为 1)中随机采样的值。
与 torch.rand() 不同,torch.randn() 生成的值更接近于正态分布的中心
3. 使用 torch.randn_like() 根据现有张量 g 的形状创建新的张量 i:
i = torch.randn_like(g)
print(i)
tensor([[-0.3863, 1.3241, 0.7400],
[-0.1386, 0.7476, -0.2747],
[ 0.1088, 0.7457, -0.3099]])
这段代码创建了一个与张量 g 具有相同形状 (3, 3) 的新张量 i,其中的元素也是从标准正态分布中随机采样的值。
与 torch.randn() 不同的是,torch.randn_like() 使用了 g 的形状信息来创建新的张量,但采样的方式仍然是从标准正态分布中。
四 序列生成tensor
1. 使用 torch.arange() 生成等差序列:
print(torch.arange(0,10))
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
这段代码生成一个从 0 到 9 的序列,步长为 1(默认步长)。
2. 使用 torch.arange() 指定步长生成等差序列:
print(torch.arange(0,10,2))
tensor([0, 2, 4, 6, 8])
这段代码生成一个从 0 到 9 的序列,步长为 2。
3. 使用 torch.linspace() 生成等间隔序列:
print(torch.linspace(0,10,3))
tensor([ 0., 5., 10.])
这段代码生成一个从 0 到 10 的等间隔序列,总共包含 3 个数。
在 torch.linspace() 中,第一个参数是起始值,第二个参数是结束值,第三个参数是生成序列的长度(包含起始值和结束值),生成的序列是均匀间隔的。
五 全一全零单位生成tensor
1. 创建全一张量(torch.ones()):
print(torch.ones(3,3))
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
这将创建一个形状为 (3, 3) 的张量,所有元素的值都为 1。
2. 创建全零张量(torch.zeros())
print(torch.zeros(2, 3))
tensor([[0., 0., 0.],
[0., 0., 0.]])
这将创建一个形状为 (2, 3) 的张量,所有元素的值都为 0。
3. 创建单位矩阵(torch.eye()):
3.1 创建指定大小的单位矩阵:
print(torch.eye(4, 4))
tensor([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
这将创建一个 4x4 的单位矩阵,即主对角线上的元素为 1,其余元素为 0。
3.2 创建默认大小(2x2)的单位矩阵:
print(torch.eye(2))
tensor([[1., 0.],
[0., 1.]])
补充
补充函数
torch.full()
l = torch.full((2, 3), 5)
print(l)
这将创建一个形状为 (2, 3) 的张量,所有元素初始化为指定的值 5。
torch.randperm()
n = torch.randperm(5)
print(n)
tensor([4, 2, 3, 0, 1])
这将创建一个随机排列的 0 到 4 的整数序列,类似于 [2, 1, 4, 3, 0]。
解释浮点数
在PyTorch中,torch.linspace()函数生成的张量包含了从起始值到结束值(包括)之间的等间隔的数列。让我们解释一下为什么输出是浮点数:
关于输出的解释:
1. 数据类型推断:
- 当使用torch.linspace(0, 10, 3) 时,PyTorch会默认生成浮点数张量,即使起始值和结束值是整数。
- 这是因为在机器学习和科学计算中,通常需要高精度的数值计算,所以生成的默认类型是浮点数(float32或 float64)。
2. 张量中元素类型:
- 在示例中,生成的张量是 torch.Tensor类型,其中包含浮点数值。
- 在PyTorch中,默认的张量类型是 torch.float32(32位浮点数),但具体类型可能会根据环境和硬件配置而有所不同。
总结:
在科学计算和机器学习中,使用浮点数类型是常见的,因为它们提供了足够的精度来处理各种数值计算任务。因此,torch.linspace() 默认生成的张量包含浮点数元素,即使起始值和结束值可以是整数。
tensor的属性
介绍
dtype | 返回张量中元素的数据类型。 |
shape 和 size | tensor.shape 或 tensor.size():返回张量的形状,可以使用两者互换使用。 tensor.size(dim):返回张量在指定维度上的大小。 |
dim | 返回张量的维度数 |
grad | tensor.grad:返回张量的梯度。如果张量是一个叶子节点并且未执行反向传播,则 tensor.grad 通常为 None。 |
device | 返回张量当前所在的设备 |
requires_grad 和 is_leaf | tensor.requires_grad:返回一个布尔值,指示张量是否需要计算梯度。 tensor.is_leaf:返回一个布尔值,指示张量是否是计算图中的叶子节点。 |
T | tensor.T 或 tensor.transpose(dim0, dim1):返回张量的转置(仅限于二维张量)或指定维度的转置。 |
代码演示
import torch
a=torch.tensor([[1,2,3],[2,3,4]],dtype=torch.float)
print(a.dtype)
print(a.shape)
print(a.size())
print(a.size(0))
print(a.size(1))
print(a.dim())
print(a.grad)
print(a.device)
torch.float32
torch.Size([2, 3])
torch.Size([2, 3])
2
3
2
None
cpu
tensor的变形
这些函数在处理张量时提供了灵活性和便利性,使得可以根据具体需要进行形状和维度的变换,是深度学习中常用的操作之一。选择合适的函数取决于需求和操作的具体特性,如内存共享、维度压缩等。
1. reshape() 方法
c = b.reshape(2, 3)
作用:将张量 b 变形为指定的形状 (2, 3),并返回新的张量 c。
注意:返回的新张量和原张量共享内存,即它们指向相同的数据,但形状不同。
2. view()
方法
d = b.view(1, 6)
作用:将张量 b 变形为指定的形状 (1, 6),并返回新的张量 d。
注意:与 reshape() 类似,但在处理不连续的张量时会有区别。也可以用来扩展或收缩维度,但不支持所有操作。
3. flatten() 方法
b = a.flatten()
作用:将高维张量拉平为一维张量,并返回新的张量 b。
注意:返回的张量是原张量在内存中连续存储的版本,因此可能与原张量不共享内存。
4. squeeze() 方法
e = torch.squeeze(d)
作用:去除张量 d 中所有维度为 1 的维度,并返回新的张量 e。
注意:如果 d 中没有维度为 1 的维度,则返回的张量与 d 是相同的。可以用来压缩维度。
5. unsqueeze() 方法
f = torch.unsqueeze(e, 0)
作用:在指定维度上增加一个维度,并返回新的张量 f。
注意:可以在任何维度上增加维度,以扩展张量的形状。
代码演示
import torch
a=torch.tensor([[1,2,3],[4,5,6]],dtype=torch.float)
print("a的值:",a)
print("a的形状:",a.shape)
b=a.flatten()#拉平为一维
print("b的值:",b)
print("b的形状:",b.shape)
c=b.reshape(2,3)
print("c的值:",c)
print("c的形状:",c.shape)
d=b.view(1,6)
print("d的值:",d)
print("d的形状:",d.shape)
e=torch.squeeze(d)
print("e的值:",e)
print("e的形状:",e.shape)
f=torch.unsqueeze(e,0)
print("f的值:",f)
print("f的形状:",f.shape)
f=torch.unsqueeze(e,1)
print("f的值:",f)
print("f的形状:",f.shape)
a的值: tensor([[1., 2., 3.],
[4., 5., 6.]])
a的形状: torch.Size([2, 3])
b的值: tensor([1., 2., 3., 4., 5., 6.])
b的形状: torch.Size([6])
c的值: tensor([[1., 2., 3.],
[4., 5., 6.]])
c的形状: torch.Size([2, 3])
d的值: tensor([[1., 2., 3., 4., 5., 6.]])
d的形状: torch.Size([1, 6])
e的值: tensor([1., 2., 3., 4., 5., 6.])
e的形状: torch.Size([6])
f的值: tensor([[1., 2., 3., 4., 5., 6.]])
f的形状: torch.Size([1, 6])
f的值: tensor([[1.],
[2.],
[3.],
[4.],
[5.],
[6.]])
f的形状: torch.Size([6, 1])
tensor的索引与切片
张量的索引和切片操作非常类似于 Python 中列表的操作,但在多维情况下更加灵活和强大。使用这些操作可以高效地访问、修改和操作张量中的元素,是深度学习中数据处理的基础。
1. 索引单个元素
import torch
# 创建一个张量
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 访问第一个元素(索引从0开始)
element = tensor[0, 0]
print(element) # 输出:tensor(1)
作用:使用逗号分隔的索引来获取张量中特定位置的单个元素
2. 切片操作
# 切片获取第一行的所有元素
row = tensor[0, :]
print(row) # 输出:tensor([1, 2, 3])
# 切片获取第一列的所有元素
column = tensor[:, 0]
print(column) # 输出:tensor([1, 4])
# 切片获取部分子张量
sub_tensor = tensor[1:, 1:]
print(sub_tensor)
# 输出:
# tensor([[5, 6]])
- 作用:
:
表示取整个维度的所有元素。start:end
表示从start
索引到end-1
索引的元素。- 省略
start
表示从该维度的起始位置开始,省略end
表示取到该维度的末尾。
3. 使用索引和切片修改张量的部分元素
# 修改元素
tensor[0, 0] = 10
print(tensor)
# 输出:
# tensor([[10, 2, 3],
# [ 4, 5, 6]])
# 修改子张量的元素
tensor[1:, 1:] = torch.tensor([[50, 60]])
print(tensor)
# 输出:
# tensor([[10, 2, 3],
# [ 4, 50, 60]])
作用:可以通过索引和切片来修改张量中的特定元素或者部分区域的元素值
4. 使用布尔索引
mask = tensor > 5
print(mask)
# 输出:
# tensor([[ True, False, False],
# [False, True, True]])
# 使用布尔掩码获取满足条件的元素
filtered_tensor = tensor[mask]
print(filtered_tensor)
# 输出:
# tensor([10, 50, 60])
- 作用:可以使用布尔张量作为索引,从而筛选出满足条件的元素。
代码演示
import torch
a=torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float)
b=torch.tensor([[10,10,10],[10,10,10],[10,10,10]], dtype=torch.float)
print(a)
print("a[1,2]的值:",a[1,2])
print("a[-1,-1]的值:",a[-1,-1])
print("a的第1行,第1列3行的值:",a[[1],[0,2]])
print("a的值大于4的索引:",a>4)
print("大于5输出a的值,否则输出b:\n",torch.where(a>5,a,b))
print(a)
print("a的第1列:",a[:,0])
print("a的第3列:",a[:,2])
print("a的第3列:",a[:,-1])
print("a的1到2列:",a[:,0:2])
print("a的第1行:",a[0,:])
print("a的第2行:",a[1, :])
print("a的最后1行:",a[-1,:])
print("a的间隔行值",a[::2,::2])
tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
a[1,2]的值: tensor(6.)
a[-1,-1]的值: tensor(9.)
a的第1行,第1列3行的值: tensor([4., 6.])
a的值大于4的索引: tensor([[False, False, False],
[False, True, True],
[ True, True, True]])
大于5输出a的值,否则输出b:
tensor([[10., 10., 10.],
[10., 10., 6.],
[ 7., 8., 9.]])
tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
a的第1列: tensor([1., 4., 7.])
a的第3列: tensor([3., 6., 9.])
a的第3列: tensor([3., 6., 9.])
a的1到3列: tensor([[1., 2.],
[4., 5.],
[7., 8.]])
a的第1行: tensor([1., 2., 3.])
a的第2行: tensor([4., 5., 6.])
a的最后1行: tensor([7., 8., 9.])
a的间隔行值 tensor([[1., 3.],
[7., 9.]])
tensor的连接和拆分
张量的连接和拆分操作是在深度学习中常见的数据处理技术,可以帮助组织数据并进行复杂的模型构建。根据具体的需求,选择适当的函数来进行连接或拆分操作,可以有效地处理数据。
tensor的连接
torch.cat
import torch
# 创建两个张量
tensor1 = torch.tensor([[1, 2], [3, 4]])
tensor2 = torch.tensor([[5, 6]])
# 在第一维度(行)上连接两个张量
concatenated_tensor = torch.cat((tensor1, tensor2), dim=0)
print(concatenated_tensor)
# 输出:
# tensor([[1, 2],
# [3, 4],
# [5, 6]])
作用:通过 torch.cat 可以沿指定的维度将多个张量连接起来。在上面的例子中,dim=0 表示在第一个维度(行)上进行连接,dim=1表示在第二维度(列)上进行连接。
torch.stack
# 创建两个张量
tensor1 = torch.tensor([[1, 2], [3, 4]])
tensor2 = torch.tensor([[5, 6]])
# 在新的维度上堆叠两个张量
stacked_tensor = torch.stack((tensor1, tensor2))
print(stacked_tensor)
# 输出:
# tensor([[[1, 2],
# [3, 4]],
#
# [[5, 6]]])
作用:torch.stack 可以在一个新的维度上堆叠多个张量。在上面的例子中,会创建一个新的维度(第一维度),将 tensor1 和 tensor2 沿此维度堆叠。
代码演示
a=torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float)
b=torch.tensor([[10,10,10],[10,10,10],[10,10,10]], dtype=torch.float)
print(a)
print(b)
print("a,b按行拼接:\n",torch.cat((a,b),dim=0))
print("a,b按行拼接:\n",torch.cat((a,b),dim=0).shape)
print("a,b按列拼接:\n",torch.cat((a,b),dim=1))
print("a,b按列拼接:\n",torch.cat((a,b),dim=1).shape)
print("a,b按行拼接:\n",torch.stack((a,b),dim=0))
print("a,b按行拼接:\n",torch.stack((a,b),dim=0).shape)
print("a,b按列拼接:\n",torch.stack((a,b),dim=1))
print("a,b按列拼接:\n",torch.stack((a,b),dim=1).shape)
tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
tensor([[10., 10., 10.],
[10., 10., 10.],
[10., 10., 10.]])
a,b按行拼接:
tensor([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.],
[10., 10., 10.],
[10., 10., 10.],
[10., 10., 10.]])
a,b按行拼接:
torch.Size([6, 3])
a,b按列拼接:
tensor([[ 1., 2., 3., 10., 10., 10.],
[ 4., 5., 6., 10., 10., 10.],
[ 7., 8., 9., 10., 10., 10.]])
a,b按列拼接:
torch.Size([3, 6])
a,b按行拼接:
tensor([[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]],
[[10., 10., 10.],
[10., 10., 10.],
[10., 10., 10.]]])
a,b按行拼接:
torch.Size([2, 3, 3])
a,b按列拼接:
tensor([[[ 1., 2., 3.],
[10., 10., 10.]],
[[ 4., 5., 6.],
[10., 10., 10.]],
[[ 7., 8., 9.],
[10., 10., 10.]]])
a,b按列拼接:
torch.Size([3, 2, 3])
tensor的拆分
torch.split
# 创建一个张量
tensor = torch.tensor([[1, 2], [3, 4], [5, 6]])
# 在指定维度上拆分张量
split_tensors = torch.split(tensor, split_size_or_sections=2, dim=0)
print(split_tensors)
# 输出:(拆分成两个张量)
# (tensor([[1, 2],
# [3, 4]]), tensor([[5, 6]]))
作用:torch.split 可以在指定维度上将一个张量拆分成多个张量。在上面的例子中,split_size_or_sections=2 表示在第一个维度(行)上每两行拆分成一个张量。
torch.chunk
# 创建一个张量
tensor = torch.tensor([[1, 2], [3, 4], [5, 6]])
# 在指定维度上均匀拆分张量
chunks = torch.chunk(tensor, chunks=3, dim=0)
print(chunks)
# 输出:(拆分成三个张量)
# (tensor([[1, 2]]), tensor([[3, 4]]), tensor([[5, 6]]))
作用:torch.chunk 可以在指定维度上将一个张量均匀地拆分成多个张量。在上面的例子中,chunks=3 表示在第一个维度(行)上均匀拆分成三个张量。
补充
torch.split 和 torch.chunk 的返回值确实是元组形式。具体来说:
torch.split 返回一个元组,元组中包含拆分后的多个张量。每个张量的形状取决于拆分的方式和维度。
torch.chunk 同样返回一个元组,元组中包含均匀拆分后的多个张量。每个张量的形状取决于拆分的方式和维度。
代码演示
import torch
a=torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float)
print(a)
print(torch.split(a,2,dim=0))
print(torch.split(a,1,dim=0))
print(torch.split(a,1,dim=1))
print(torch.chunk(a,2,dim=0))
print(torch.chunk(a,2,dim=1))
tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
(tensor([[1., 2., 3.],
[4., 5., 6.]]), tensor([[7., 8., 9.]]))
(tensor([[1., 2., 3.]]), tensor([[4., 5., 6.]]), tensor([[7., 8., 9.]]))
(tensor([[1.],
[4.],
[7.]]), tensor([[2.],
[5.],
[8.]]), tensor([[3.],
[6.],
[9.]]))
(tensor([[1., 2., 3.],
[4., 5., 6.]]), tensor([[7., 8., 9.]]))
(tensor([[1., 2.],
[4., 5.],
[7., 8.]]), tensor([[3.],
[6.],
[9.]]))
tensor的换位与置换
1 T与torch.t()
只接收二维数组
import torch
a=torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float)
print(a)
print(a.T)#只接收二维
print(torch.t(a))#只接收二维
tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
tensor([[1., 4., 7.],
[2., 5., 8.],
[3., 6., 9.]])
tensor([[1., 4., 7.],
[2., 5., 8.],
[3., 6., 9.]])
将行和列进行交换
2 .transpose()
.transpose()
方法可以用来交换张量的两个维度的顺序。只接收二维数组
import torch
# 创建一个张量
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 使用 transpose 方法交换维度
transposed_tensor = tensor.transpose(0, 1) # 交换第0维和第1维
print(transposed_tensor)
# 输出:
# tensor([[1, 4],
# [2, 5],
# [3, 6]])
tensor.transpose(0, 1)
将第0维和第1维进行了交换,原来的行变成了列,列变成了行。
3 .permute()
.permute()
方法允许对张量的维度进行任意排列,可以不是二维
# 创建一个张量
tensor = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# 使用 permute 方法对维度进行置换
permuted_tensor = tensor.permute(2, 0, 1) # 将第2维放在第0维,第0维放在第1维,第1维放在第2维
print(permuted_tensor)
# 输出:
# tensor([[[1, 3],
# [5, 7]],
#
# [[2, 4],
# [6, 8]]])
tensor.permute(2, 0, 1)
将原始张量的第2维移动到第0维的位置,第0维移动到第1维的位置,第1维移动到第2维的位置,从而实现了张量维度的置换。
代码演示
import torch
a=torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float)
print(a)
print(a.T)#只接收二维
print(torch.t(a))#只接收二维
print(torch.transpose(a,1,0))#只接收二维
print(a.permute(1,0))#不只接收二维
c=torch.unsqueeze(a,0)
print(c)
print(c.shape)
print(c.permute(1,0,2).shape)
tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
tensor([[1., 4., 7.],
[2., 5., 8.],
[3., 6., 9.]])
tensor([[1., 4., 7.],
[2., 5., 8.],
[3., 6., 9.]])
tensor([[1., 4., 7.],
[2., 5., 8.],
[3., 6., 9.]])
tensor([[1., 4., 7.],
[2., 5., 8.],
[3., 6., 9.]])
tensor([[[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]]])
torch.Size([1, 3, 3])
torch.Size([3, 1, 3])
tensor的运算
import torch
a=torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float)
b=torch.tensor([[10,10,10],[10,10,10],[10,10,10]], dtype=torch.float)
print(a)
print(b)
print(a+100)#点加
print(a + b)#点加
print(a.add(b))#点加
print(a*b)#点乘
print(a@b)#矩阵相乘
print(a.matmul(b))#矩阵相乘
print(torch.mm(a,b))#矩阵相乘
tensor([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
tensor([[10., 10., 10.],
[10., 10., 10.],
[10., 10., 10.]])
tensor([[101., 102., 103.],
[104., 105., 106.],
[107., 108., 109.]])
tensor([[11., 12., 13.],
[14., 15., 16.],
[17., 18., 19.]])
tensor([[11., 12., 13.],
[14., 15., 16.],
[17., 18., 19.]])
tensor([[10., 20., 30.],
[40., 50., 60.],
[70., 80., 90.]])
tensor([[ 60., 60., 60.],
[150., 150., 150.],
[240., 240., 240.]])
tensor([[ 60., 60., 60.],
[150., 150., 150.],
[240., 240., 240.]])
tensor([[ 60., 60., 60.],
[150., 150., 150.],
[240., 240., 240.]])
原文地址:https://blog.csdn.net/2403_83147124/article/details/140343550
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!