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])
torch.flatten(pred.permute(0, 2, 3, 1), start_dim=1)#通道数放到最后,start_dim=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)
>>>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))
import torch
x = torch.randn(3,4,5)
print(x.numel()) #60
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])
# 假设是时间步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)