pytorch的函数(如squeeze,permute,flatten,stack,numel,matmul)

  1. squeeze消去一个或多个维度。只有在指定的维度长度=1时才生效。
    a.squeeze(0):消去第1个维度(这里的索引是从0开始的,和数组索引一样)
    a.squeeze(0,2):消去第1、3个维度
    a.squeeze():消去所有长度=1的维度
    如果指定的维度长度不为1,不报错但是也不会有任何作用.
    摘自PyTorch入门——数组维度及squeeze、unsqueeze
  2. unsqueeze
    增加一个长度=1的维度
b=torch.tensor([[1, 0, 0, 0],
                [0, 1, 0, 0],
                [0, 0, 1, 0],
                [0, 0, 0, 1]])
b1=b.unsqueeze(0)
b2=b.unsqueeze(1)
print(b1)
print(b1.shape)
print(b2)
print(b2.shape)
tensor([[[1, 0, 0, 0],
         [0, 1, 0, 0],
         [0, 0, 1, 0],
         [0, 0, 0, 1]]])
torch.Size([1, 4, 4])
tensor([[[1, 0, 0, 0]],

        [[0, 1, 0, 0]],

        [[0, 0, 1, 0]],

        [[0, 0, 0, 1]]])
torch.Size([4, 1, 4])

  1. torch.bmm(a,b)
    计算两个tensor的矩阵乘法,torch.bmm(a,b),tensor a 的size为(b,h,w),tensor b的size为(b,w,m),注意两个tensor的维度必须为3.也就是说两个tensor的第一维batch是相等的,然后第一个数组的第三维和第二个数组的第二维度要求一样,对于剩下的则不做要求,输出维度 (b,h,m)。
    三维矩阵a里面,含有a1个a2a3的矩阵,这些矩阵要分别和b里面的a1个b2b3个矩阵做矩阵乘法。摘自
  2. permute 将tensor的维度换位
    permute(1,0)得到的就是矩阵的转置
    torch中permute()函数用法
  3. torch.flatten 将某些维度张量拉成一维
    torch.flatten(t, start_dim=0, end_dim=-1) 的实现原理如下。假设类型为 torch.tensor 的张量的形状如下所示:(2,4,3,5,6),则 torch.flatten(t, 1, 3).shape 的结果为 (2, 60, 6)。将索引为 start_dim 和 end_dim 之间(包括该位置)的数量相乘,其余位置不变。因为默认 start_dim=0,end_dim=-1,所以 torch.flatten(t) 返回只有一维的数据。摘自
torch.flatten(pred.permute(0, 2, 3, 1), start_dim=1)#通道数放到最后,start_dim=1将后三个拉成一维向量
  1. torch.nn.Sequential(*blk) 摘自
    torch.nn.Sequential类来实现简单的顺序连接模型
    形式(1)
import torch.nn as nn
model = nn.Sequential(
                  nn.Conv2d(1,20,5),
                  nn.ReLU(),
                  nn.Conv2d(20,64,5),
                  nn.ReLU()
                )

形式(2)

import torch.nn as nn
from collections import OrderedDict#给每层添加名字
model = nn.Sequential(OrderedDict([
                  ('conv1', nn.Conv2d(1,20,5)),
                  ('relu1', nn.ReLU()),
                  ('conv2', nn.Conv2d(20,64,5)),
                  ('relu2', nn.ReLU())
                ]))

形式(3)

import torch.nn as nn
from collections import OrderedDict
model = nn.Sequential()
model.add_module("conv1",nn.Conv2d(1,20,5))
model.add_module('relu1', nn.ReLU())
model.add_module('conv2', nn.Conv2d(20,64,5))
model.add_module('relu2', nn.ReLU())

实例:

def down_sample_blk(in_channels, out_channels):#变化通道数高宽减半
    blk = []
    for _ in range(2):
        blk.append(nn.Conv2d(in_channels, out_channels,
                             kernel_size=3, padding=1))
        blk.append(nn.BatchNorm2d(out_channels))
        blk.append(nn.ReLU())
        in_channels = out_channels
    blk.append(nn.MaxPool2d(2))#2*2最大池化 高宽减半
    return nn.Sequential(*blk)
  1. setattr() 函数, getattr()
    setattr(object, name, value)
>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, 'bar')          # 获取属性 bar 值
1
>>> setattr(a, 'bar', 5)       # 设置属性 bar 值
>>> a.bar
5

实例

setattr(self, f'blk_{
      
      i}', get_blk(i))#给赋了个函数
setattr(self, f'cls_{
      
      i}', cls_predictor(idx_to_in_channels[i],num_anchors, num_classes))
setattr(self, f'bbox_{
      
      i}', bbox_predictor(idx_to_in_channels[i],num_anchors))
  1. pytorch中的numel函数
    获取tensor中一共包含多少个元素
import torch
x = torch.randn(3,4,5)
print(x.numel()) #60
  1. torch.mul(a, b) Hadamard乘积哈达玛乘积.是矩阵a和b对应位相乘,a和b的维度必须相等.
    torch.mm(a, b) 是矩阵a和b矩阵相乘,比如a的维度是(1, 2),b的维度是(2, 3),返回的就是(1, 3)的矩阵.
    torch.bmm该函数提供了batch维度的矩阵乘法运算,即batch内对应的矩阵两两相乘,因此要求参与计算的两个张量必须为三维张量,其中第一个维度为batch_size,必须相同.
    torch.matmul是tensor的乘法,输入可以是高维的。当输入是都是二维时,就是普通的矩阵乘法,和tensor.mm函数用法相同。
  2. torch.max()矩阵中的最大值,并返回索引
    实例:
outputs = torch.rand(2,3)
print('outputs',outputs)
maxY = torch.max(outputs,dim=1)
print(maxY)
print(maxY[1])#返回索引
outputs tensor([[0.2762, 0.0924, 0.4259],
        		[0.0485, 0.8763, 0.7547]])
torch.return_types.max(
	values=tensor([0.4259, 0.8763]),
	indices=tensor([2, 1]))
tensor([2, 1])

  1. stack() 部分摘自torch.stack()的官方解释,详解以及例子
    官方解释:沿着一个新维度对输入张量序列进行连接。 序列中所有的张量都应该为相同形状。
    outputs = torch.stack(inputs, dim=?) → Tensor
    inputs : 待连接的张量序列。
    注:python的序列数据只有list和tuple。
    dim : 新的维度, 必须在0到len(outputs)之间。
    注:len(outputs)是生成数据的维度大小,也就是outputs的维度值。
    示例:
# 假设是时间步T1的输出
T1 = torch.tensor([[1, 2, 3],
        		[4, 5, 6],
        		[7, 8, 9]])
# 假设是时间步T2的输出
T2 = torch.tensor([[10, 20, 30],
        		[40, 50, 60],
        		[70, 80, 90]])

print(torch.stack((T1,T2),dim=0).shape)
print(torch.stack((T1,T2),dim=1).shape)
print(torch.stack((T1,T2),dim=2).shape)
print(torch.stack((T1,T2),dim=3).shape)
# outputs:
torch.Size([2, 3, 3])
torch.Size([3, 2, 3])
torch.Size([3, 3, 2])
'选择的dim>len(outputs),所以报错'
IndexError: Dimension out of range (expected to be in range of [-3, 2], but got 3)

猜你喜欢

转载自blog.csdn.net/weixin_44040169/article/details/126818864