Pytorch积累

数据

常用数据集两种格式讲解:


第一种数据形式:

「文件夹名就是 label」
dataset/
├── cat/
│ ├── cat1. jpg
│ ├── cat2. jpg
├── dog/
│ ├── dog1. jpg
│ ├── dog2. jpg

这里的每个子文件夹名(比如 cat, dog)就是该文件夹中所有图片的标签(label)。
这种结构常被 ImageFolder 自动支持,写自定义 Dataset 也很直观:

1
label = folder_name  # 文件夹名作为标签

第二种数据形式:

「用文本文件来提供标签」

比如你有图片和一个对应的 label 文件:
images/
├── 001. jpg
├── 002. jpg
labels. txt:

  1. jpg 0
  2. jpg 1

或者每张图片一个文本文件:

images/
├── 001. jpg
labels/
├── 001. txt # 内容是 0

这种方式下:

  • 图片和 label 分离
  • 你需要读取 label 文件或内容来自行匹配

dataset

Help on class Dataset in module torch.utils.data.dataset:

class Dataset(typing.Generic)
| An abstract class representing a :class:Dataset.
|
| All datasets that represent a map from keys to data samples should subclass
| it. All subclasses should overwrite :meth:__getitem__, supporting fetching a
| data sample for a given key. Subclasses could also optionally overwrite
| :meth:__len__, which is expected to return the size of the dataset by many
| :class:~torch.utils.data.Sampler implementations and the default options
| of :class:~torch.utils.data.DataLoader.
|
| .. note::
| :class:~torch.utils.data.DataLoader by default constructs a index
| sampler that yields integral indices. To make it work with a map-style
| dataset with non-integral indices/keys, a custom sampler must be provided.
|
| Method resolution order:
| Dataset
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| add(self, other:’Dataset[T_co]’) -> ‘ConcatDataset[T_co]’
|
| getattr(self, attribute_name)
|
| getitem(self, index) -> +T_co

|
| ———————————————————————-
| Class methods defined here:
|
| register_datapipe_as_function(function_name, cls_to_register, enable_df_api_tracing=False) from typing.GenericMeta
|
| register_function(function_name, function) from typing.GenericMeta

|
| ———————————————————————-
| Data descriptors defined here:
|
| dict
| dictionary for instance variables (if defined)
|
| weakref
| list of weak references to the object (if defined)

|
| ———————————————————————-
| Data and other attributes defined here:
|
| abstractmethods = frozenset()
|
| annotations = {‘functions’: typing.Dict[str, typing.Callable]}
|
| args = None
|
| extra = None
|
| next_in_mro = <class ‘object’>
| The most base type
|
| orig_bases = (typing.Generic[+T_co],)
|
| origin = None
|
| parameters = (+T_co,)
|
| tree_hash = -9223371886060913604
|
| functions = {‘concat’: functools.partial(<function Dataset.register_da…/

|
| ———————————————————————-
| Static methods inherited from typing.Generic:
|
| new(cls, *args, **kwds)
| Create and return a new object. See help(type) for accurate signature

核心概念

1. getitem(self, index)

  • 必须实现。
  • 定义了 如何根据索引读取一个样本
  • 通常返回 (data, label) 的元组。

2. len(self)

  • 可选,但建议实现。
  • 返回数据集的总大小。
  • 会被 DataLoader 等组件用来确定迭代次数。

第一种加载方法

假设的数据结构如下:

1
2
3
4
5
6
7
8
dataset/
├── cat/
│ ├── cat1.jpg
│ ├── cat2.jpg
├── dog/
│ ├── dog1.jpg
│ ├── dog2.jpg

自定义 Dataset 代码(等价于 ImageFolder):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import os
from torch.utils.data import Dataset
from PIL import Image

class MyFolderDataset(Dataset):
def __init__(self, root_dir, transform=None):
self.root_dir = root_dir
self.transform = transform

# 找出所有类别文件夹名,建立类别到数字的映射
self.classes = sorted(os.listdir(root_dir))
self.class_to_idx = {cls_name: idx for idx, cls_name in enumerate(self.classes)}

# 收集所有图片路径和对应标签
self.samples = []
for cls_name in self.classes:
cls_folder = os.path.join(root_dir, cls_name)
for fname in os.listdir(cls_folder):
if fname.endswith(('.jpg', '.png')):
path = os.path.join(cls_folder, fname)
label = self.class_to_idx[cls_name]
self.samples.append((path, label))

def __len__(self):
return len(self.samples)

def __getitem__(self, index):
path, label = self.samples[index]
image = Image.open(path).convert('RGB')

if self.transform:
image = self.transform(image)

return image, label

使用示例:

1
2
3
4
5
6
7
8
9
10
11
12
from torchvision import transforms

transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor()
])

dataset = MyFolderDataset(root_dir='dataset', transform=transform)

from torch.utils.data import DataLoader
loader = DataLoader(dataset, batch_size=32, shuffle=True)

第二种加载方法

一个 txt 文件

假设你的数据结构如下:

1
2
3
4
5
6
dataset/
├── images/
│ ├── 001.jpg
│ ├── 002.jpg
│ ├── ...
├── labels.txt # 每行格式:文件名 label(用空格或逗号分隔)

**例如 labels.txt 内容:

1
2
3
001.jpg 0
002.jpg 1
003.jpg 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os

from torch.utils.data import Dataset

from PIL import Image

class MyImageDataset(Dataset):

    def __init__(self, image_dir, label_file, transform=None):

        self.image_dir = image_dir

        self.transform = transform

        self.data = []


        with open(label_file, 'r') as f:

            for line in f:

                # 支持空格或逗号分隔

                parts = line.strip().replace(',', ' ').split()

                if len(parts) == 2:

                    filename, label = parts

                    self.data.append((filename, int(label)))

    def __len__(self):

        return len(self.data)

    def __getitem__(self, index):

        filename, label = self.data[index]

        img_path = os.path.join(self.image_dir, filename)

        image = Image.open(img_path).convert('RGB')


        if self.transform:

            image = self.transform(image)

        return image, label
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from torchvision import transforms

transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor()
])

dataset = MyImageDataset(
image_dir='dataset/images',
label_file='dataset/labels.txt',
transform=transform
)

from torch.utils.data import DataLoader
loader = DataLoader(dataset, batch_size=32, shuffle=True)
每一张图片对应一个 txt

假设你的数据结构如下:

1
2
3
4
5
6
7
8
dataset/
├── images/
│ ├── 001.jpg
│ ├── 002.jpg
│ ├── ...
├── labels/
│ ├── 001.txt # 里面内容是标签,例如:0
│ ├── 002.txt # 或者多个标签,例如:1 0 1

自定义 Dataset 代码(支持单标签和多标签):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import os
from torch.utils.data import Dataset
from PIL import Image

class MyImageTxtLabelDataset(Dataset):
def __init__(self, image_dir, label_dir, transform=None, multi_label=False):
self.image_dir = image_dir
self.label_dir = label_dir
self.transform = transform
self.multi_label = multi_label

self.filenames = [f for f in os.listdir(image_dir) if f.endswith('.jpg') or f.endswith('.png')]

def __len__(self):
return len(self.filenames)

def __getitem__(self, index):
filename = self.filenames[index]
img_path = os.path.join(self.image_dir, filename)
label_path = os.path.join(self.label_dir, os.path.splitext(filename)[0] + '.txt')

image = Image.open(img_path).convert('RGB')

if self.transform:
image = self.transform(image)

with open(label_path, 'r') as f:
label_line = f.readline().strip()
if self.multi_label:
label = [int(x) for x in label_line.split()]
else:
label = int(label_line)

return image, label

使用方式(单标签):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from torchvision import transforms

transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor()
])

dataset = MyImageTxtLabelDataset(
image_dir='dataset/images',
label_dir='dataset/labels',
transform=transform,
multi_label=False # 改成 True 支持多标签
)

from torch.utils.data import DataLoader
loader = DataLoader(dataset, batch_size=32, shuffle=True)

在 two_stage 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import os
import json
import torch
from PIL import Image
from torchvision import transforms
from torch.utils.data import Dataset

class VOC2007DetectionTiny(Dataset):
"""
A tiny version of PASCAL VOC 2007 Detection dataset that includes images and
annotations with small images and no difficult boxes.
"""

def __init__(
self,
dataset_dir: str,
split: str = "train",
download: bool = False,
image_size: int = 224,
):
super().__init__()
self.image_size = image_size

if download:
self._attempt_download(dataset_dir)

voc_classes = [
"aeroplane", "bicycle", "bird", "boat", "bottle", "bus",
"car", "cat", "chair", "cow", "diningtable", "dog",
"horse", "motorbike", "person", "pottedplant", "sheep",
"sofa", "train", "tvmonitor"
]

self.class_to_idx = {
_class: _idx for _idx, _class in enumerate(voc_classes)
}
self.idx_to_class = {
_idx: _class for _idx, _class in enumerate(voc_classes)
}

self.instances = json.load(
open(os.path.join(dataset_dir, f"voc07_{split}.json"))
)
self.dataset_dir = dataset_dir

_transforms = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
),
]
self.image_transform = transforms.Compose(_transforms)

@staticmethod
def _attempt_download(dataset_dir: str):
import wget
import tarfile

os.makedirs(dataset_dir, exist_ok=True)

wget.download(
"https://web.eecs.umich.edu/~justincj/data/VOCtrainval_06-Nov-2007.tar",
out=dataset_dir,
)
wget.download(
"https://web.eecs.umich.edu/~justincj/data/voc07_train.json",
out=dataset_dir,
)
wget.download(
"https://web.eecs.umich.edu/~justincj/data/voc07_val.json",
out=dataset_dir,
)

voc_tar = tarfile.open(
os.path.join(dataset_dir, "VOCtrainval_06-Nov-2007.tar")
)
voc_tar.extractall(dataset_dir)
voc_tar.close()

def __len__(self):
return len(self.instances)

def __getitem__(self, index: int):
image_path, ann = self.instances[index]
image_path = image_path.replace("./here/", "")
image_path = os.path.join(self.dataset_dir, image_path)
image = Image.open(image_path).convert("RGB")

gt_boxes = torch.tensor([inst["xyxy"] for inst in ann])
gt_classes = torch.Tensor([self.class_to_idx[inst["name"]] for inst in ann])
gt_classes = gt_classes.unsqueeze(1)

original_width, original_height = image.size

normalize_tens = torch.tensor(
[original_width, original_height, original_width, original_height]
)
gt_boxes /= normalize_tens[None, :]

image = self.image_transform(image)

if self.image_size is not None:
if original_height >= original_width:
new_width = self.image_size
new_height = original_height * self.image_size / original_width
else:
new_height = self.image_size
new_width = original_width * self.image_size / original_height

_x1 = (new_width - self.image_size) // 2
_y1 = (new_height - self.image_size) // 2

gt_boxes[:, 0] = torch.clamp(gt_boxes[:, 0] * new_width - _x1, min=0)
gt_boxes[:, 1] = torch.clamp(gt_boxes[:, 1] * new_height - _y1, min=0)
gt_boxes[:, 2] = torch.clamp(
gt_boxes[:, 2] * new_width - _x1, max=self.image_size
)
gt_boxes[:, 3] = torch.clamp(
gt_boxes[:, 3] * new_height - _y1, max=self.image_size
)

gt_boxes = torch.cat([gt_boxes, gt_classes], dim=1)

invalid = (gt_boxes[:, 0] > gt_boxes[:, 2]) | (
gt_boxes[:, 1] > gt_boxes[:, 3]
)
gt_boxes[invalid] = -1

gt_boxes = torch.cat(
[gt_boxes, torch.zeros(40 - len(gt_boxes), 5).fill_(-1.0)]
)

return image_path, image, gt_boxes


torchvision

1
2
from torchvision import models
_cnn = models.regnet_x_400mf(pretrained=True)

models.regnet_x_400mf:

  • RegNetX-400MF 是一个轻量级的卷积神经网络模型,属于 RegNet 系列(由 Facebook AI 提出)。RegNet 系列的设计目标是提供高效且具有良好性能的神经网络架构。
  • 400MF 表示该模型的计算复杂度大约为 400百万浮动运算(400 million FLOPs),因此它是一个中等规模的模型,适合较小的数据集和资源受限的情况(比如 Colab GPU)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
self.backbone = feature_extraction.create_feature_extractor(

    _cnn,

    return_nodes={

        "trunk_output.block2": "c3",

        "trunk_output.block3": "c4",

        "trunk_output.block4": "c5",

    },

)

这段代码的作用是使用 feature_extraction.create_feature_extractor 方法从预训练的 RegNetX-400MF 模型中提取三个不同层次的特征(c3、c4、c5),并将这些特征保存为自定义名称。然后,self.backbone 将这个特征提取器保存下来,供后续的 FPN 使用,以便实现多尺度目标检测。

  1. feature_extraction.create_feature_extractor:
  • 这是一个工具函数,通常用于从一个预训练的卷积神经网络模型(如 ResNet、RegNet 等)中提取中间层的特征图。
  • 通过这个函数,你可以选择从某些特定的层(如 block2、block3、block4 等)获取输出,而不是仅仅使用最后一个输出层。这个功能对于目标检测或其他需要多尺度特征的任务特别有用。
  1. _cnn:
  • 这是你之前加载的 RegNetX-400MF 模型(一个预训练的 CNN),它包含了多个卷积块,经过训练后能够提取有用的图像特征。
  1. return_nodes:
  • 这是一个字典,指定了你希望从 _cnn 模型中提取的特定层的输出。字典的格式是:{模型的层名称: 自定义的层名称}。

在这个例子中:

  • “trunk_output.block2” → “c3”:提取 block2 层的输出,并将其命名为 c3。这是一个低层次的特征,包含了细节信息。
  • “trunk_output.block3” → “c4”:提取 block3 层的输出,并将其命名为 c4。这一层提取的是中层特征,包含更多语义信息。
  • “trunk_output.block4” → “c5”:提取 block4 层的输出,并将其命名为 c5。这一层提取的是高层特征,通常用于捕捉图像的全局信息。
  1. self.backbone:
  • self.backbone 保存了通过 create_feature_extractor 创建的特征提取器。这个提取器会返回三个不同尺度的特征图(c3、c4、c5),供后续的 Feature Pyramid Network (FPN) 使用。

nn

nn. Moduledict

知识点

nn.ModuleDict 是 PyTorch 中的一个容器,用于存储神经网络模块。它继承自 Python 的 dict(字典),并扩展了它的功能,使其可以自动追踪其包含的子模块的参数和梯度信息。它的作用和字典类似,但为包含的子模块提供了更多的功能,特别是在深度学习模型的构建中。

nn.ModuleDict 的作用:

nn.ModuleDict 主要用于在神经网络模型中存储多个子模块(如卷积层、线性层等),并自动将它们注册为 PyTorch 模型的一部分。这些模块将自动具备可训练的参数,并可以在模型的 forward 函数中进行访问。

基本用法:

1
2
3
4
5
6
7
8
9
10
11
12
import torch
import torch.nn as nn

# 创建一个 ModuleDict
module_dict = nn.ModuleDict({
'conv1': nn.Conv2d(3, 16, kernel_size=3),
'conv2': nn.Conv2d(16, 32, kernel_size=3),
'fc1': nn.Linear(32 * 6 * 6, 128),
})

# 访问模块
print(module_dict['conv1']) # 打印 conv1 层

为什么使用 ModuleDict?

  1. 自动注册参数:

使用 nn.ModuleDict 存储的所有子模块会自动注册为 nn.Module 的子模块,因此它们的参数(权重和偏置)会被自动添加到模型的 parameters() 中,这样可以方便地进行梯度计算和优化。

  1. 便于管理多个模块:

在构建复杂网络时,通常会使用多个层(如卷积层、池化层、线性层等)。使用 ModuleDict 可以将这些层按名称组织起来,避免手动维护每一层。

  1. 动态访问模块:

ModuleDict 是字典类型,可以通过模块名称(键)动态地访问对应的子模块,便于模型中层之间的灵活调用。

示例:使用 ModuleDict 来构建模型

假设我们要实现一个简单的卷积神经网络,并希望将不同的层(如卷积层、全连接层)存储在 ModuleDict 中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()

# 使用 ModuleDict 存储网络中的各个模块
self.layers = nn.ModuleDict({
'conv1': nn.Conv2d(1, 32, kernel_size=3),
'conv2': nn.Conv2d(32, 64, kernel_size=3),
'fc1': nn.Linear(64 * 6 * 6, 128),
'fc2': nn.Linear(128, 10)
})

def forward(self, x):
# 使用 ModuleDict 中的模块进行前向传播
x = self.layers['conv1'](x)
x = torch.relu(x)
x = self.layers['conv2'](x)
x = torch.relu(x)
x = x.view(x.size(0), -1) # Flatten the tensor for the fully connected layer
x = self.layers['fc1'](x)
x = torch.relu(x)
x = self.layers['fc2'](x)
return x

# 创建模型实例
model = SimpleCNN()

工作原理:

  • ModuleDict 初始化:在模型的 init 方法中,我们用 nn.ModuleDict 创建了一个字典,其中键是模块的名称,值是对应的子模块(如卷积层、线性层等)。
  • 在 forward 中使用:在 forward 方法中,我们通过 self.layers[‘conv1’] 等来访问各个子模块,然后用它们执行前向传播。

特点:

  1. 自动追踪参数:nn.ModuleDict 会自动跟踪包含在其中的子模块的参数和梯度,因此你不需要手动注册它们。
  2. 方便管理:当你的网络结构变得复杂时,ModuleDict 可以帮助你以字典的形式存储层,使得代码更清晰、更容易管理。
  3. 动态模块访问:你可以根据需要动态访问、修改或替换子模块。

ModuleDict 与普通字典的区别:

  • 普通字典:普通字典仅仅是键值对的存储结构,没有与模型的参数或计算图关联。
  • ModuleDict:ModuleDict 是一个继承自 dict 的类,但它自动将存储的模块注册为 PyTorch 模型的子模块,这些模块的参数会被自动添加到模型中并参与反向传播。

总结:

nn.ModuleDict 是 PyTorch 中非常有用的一个容器,允许你以字典形式管理多个子模块,并且自动处理与这些模块相关的参数。它适用于模型中包含多个子模块的情况,尤其是在构建复杂网络(如多分支网络、动态计算图等)时,能极大简化代码的管理与访问。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import torch
import torch.nn.functional as F

class DetectorBackboneWithFPN(nn.Module):
def __init__(self, out_channels: int):
super().__init__()
self.out_channels = out_channels

_cnn = models.regnet_x_400mf(pretrained=True)

self.backbone = feature_extraction.create_feature_extractor(
_cnn,
return_nodes={
"trunk_output.block2": "c3",
"trunk_output.block3": "c4",
"trunk_output.block4": "c5",
},
)

# Lateral 1x1 convolutions to transform (c3, c4, c5) to out_channels
self.fpn_params = nn.ModuleDict({
'lateral_c3': nn.Conv2d(64, self.out_channels, kernel_size=1, stride=1, padding=0),
'lateral_c4': nn.Conv2d(128, self.out_channels, kernel_size=1, stride=1, padding=0),
'lateral_c5': nn.Conv2d(256, self.out_channels, kernel_size=1, stride=1, padding=0),
})

# Output 3x3 convolutions to generate p3, p4, p5 features
self.fpn_params.update({
'output_p3': nn.Conv2d(self.out_channels, self.out_channels, kernel_size=3, stride=1, padding=1),
'output_p4': nn.Conv2d(self.out_channels, self.out_channels, kernel_size=3, stride=1, padding=1),
'output_p5': nn.Conv2d(self.out_channels, self.out_channels, kernel_size=3, stride=1, padding=1),
})

@property
def fpn_strides(self):
"""
Total stride up to the FPN level. For a fixed ConvNet, these values
are invariant to input image size. You may access these values freely
to implement your logic in FCOS / Faster R-CNN.
"""
return {"p3": 8, "p4": 16, "p5": 32}

def forward(self, images: torch.Tensor):

# Multi-scale features, dictionary with keys: {"c3", "c4", "c5"}.
backbone_feats = self.backbone(images)

# Initialize fpn_feats dictionary
fpn_feats = {"p3": None, "p4": None, "p5": None}

# Apply lateral 1x1 convolutions to transform c3, c4, c5
lateral_c3 = self.fpn_params['lateral_c3'](backbone_feats["c3"])
lateral_c4 = self.fpn_params['lateral_c4'](backbone_feats["c4"])
lateral_c5 = self.fpn_params['lateral_c5'](backbone_feats["c5"])

# Merge features (start from p5 and propagate upwards)
fpn_feats["p5"] = lateral_c5
fpn_feats["p4"] = lateral_c4 + F.interpolate(fpn_feats["p5"], scale_factor=2, mode="nearest")
fpn_feats["p3"] = lateral_c3 + F.interpolate(fpn_feats["p4"], scale_factor=2, mode="nearest")

# Apply output 3x3 convolutions to generate p3, p4, p5 features
fpn_feats["p3"] = self.fpn_params['output_p3'](fpn_feats["p3"])
fpn_feats["p4"] = self.fpn_params['output_p4'](fpn_feats["p4"])
fpn_feats["p5"] = self.fpn_params['output_p5'](fpn_feats["p5"])

return fpn_feats

#• **上采样与加和**:这段代码的核心思想是从最低分辨率的特征图(p5)开始,逐步上采样并与更高分辨率的特征图(如 c4, c3)进行融合。

#• **逐级特征融合**:

#• 从 p5 开始,p4 通过上采样后的 p5 与 lateral_c4 融合;

#• 然后,p3 通过上采样后的 p4 与 lateral_c3 融合;

#• 这使得每个 FPN 输出特征图(p3, p4, p5)包含来自不同尺度的信息,有助于检测不同大小的目标。

#这段代码是 FPN 中 **特征图融合** 的典型实现。通过逐级上采样和加和,FPN 将来自不同层(c3, c4, c5)的特征图结合起来,生成多个不同分辨率的特征图,以更好地处理不同大小的目

nn. F

F.interpolate

F.interpolate 是 PyTorch 中的一个函数,用于对张量(通常是图像或特征图)进行上采样下采样操作,即改变张量的空间尺寸(高度和宽度)。它支持多种上采样和下采样的方式,包括最邻近插值、双线性插值等。

1
2
3
import torch.nn.functional as F

output = F.interpolate(input, scale_factor=2, mode="nearest")

参数说明:

  1. input:要进行插值操作的输入张量。通常是一个图像或特征图,形状为 (B, C, H, W),其中 B 是批次大小,C 是通道数,H 是高度,W 是宽度。
  2. scale_factor:用于定义上采样或下采样的比例。
  • scale_factor=2 表示对张量的空间尺寸(高度和宽度)进行 2 倍的上采样,即将张量的高度和宽度都放大两倍。
  • 如果 scale_factor 小于 1,则表示下采样。
  1. mode:插值方式。可以选择以下几种方式:
  • “nearest”:最近邻插值,简单地复制最近的像素。对于上采样而言,意味着每个新像素会被赋予最近的原像素的值。该方法计算速度非常快,但可能会引入一些马赛克效果(低质量)。
  • “bilinear”:双线性插值,基于四个相邻像素进行加权平均。该方法更平滑,但计算量较大。
  • “bicubic”:双三次插值,比双线性插值有更高的平滑度,适用于高质量的上采样。

nn. Sequential

返回的是一个 nn.Sequential 对象,而 nn.Sequential 是 nn.Module 的子类

1
model = nn.Sequential(...)

本质上构建了一个完整可训练的模型对象

  • 查看它的参数:model.parameters
  • 放到 GPU 上训练:model.to(‘cuda’)
  • 调用 forward 传播:output = model(input)
  • 与 loss 函数、optimizer 联动训练

pytorch

torch. no_grad () 关闭计算图,避免额外的梯度计算,节省显存。

w.grad. zero_() 清空梯度,防止梯度累积导致错误。

这段代码是手写 PyTorch 训练循环的关键部分,等价于 optimizer.step () + optimizer. zero_grad ()

optimizer. zero._grad () 将上一步的梯度清零

conda activate pytorch

迁移学习:利用现有的网络架构,去改进,比如

添加层 vgg16_true. classifier. add_module()

修改 vgg16_true. calssifier[6]=nn.Linear (4096,10)

Loss tensor 数据类型

Loss.item () 数字

Gpu: 网络模型损失函数数据有 cuda

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
```python
# 多头注意力操作
Q = Q.view(N, S, H, D_head).transpose(1, 2) # (N, H, S, D_head)
K = K.view(N, T, H, D_head).transpose(1, 2) # (N, H, T, D_head)
V = V.view(N, T, H, D_head).transpose(1, 2) # (N, H, T, D_head)

#**🧠 所以为什么“通常”把 H 放第2维?**
#只要h对齐了就可以计算


#这是一个 **业界约定俗成的规范**,因为:

#• 多数 PyTorch、TensorFlow、JAX 等实现都习惯使用 (N, H, S, D);

#• 这样你处理 batch、head、seq、embedding 都是顺序分布;

#• 更容易读取、调试、可视化;

#• 与 nn.MultiheadAttention 接口的内部实现风格一致。 %%

并行操作:torch.matmul allows you to do a batched matrix multiply

A 形状 B 形状 结果形状 含义
(m, n) (n, p) (m, p) 标准二维矩阵乘法
(b, m, n) (b, n, p) (b, m, p) batched matmul:对每个 batch 独立做矩阵乘法
(N, H, S, D) (N, H, D, T) (N, H, S, T) 多头注意力中常见形状(对每个 head 单独算 attention)
(b1, b2, …, m, n) (b1, b2, …, n, p) (b1, b2, …, m, p) 高维 batch 乘法,前面的维度需要广播一致
概念 说明
.transpose() 不改数据,只改变 shape 和 stride,让你“换个角度看”
.matmul() 根据 shape 和 stride 来决定怎么乘,不要求数据连续
为什么能按转置方式算? 因为 stride 变了,PyTorch 就知道你“打算按转置的方式去乘”
1
2
3
# Step 3: Attention scores (N, H, S, D_head) x (N, H, D_head, T) = (N, H, S, T)

scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(D_head)

掩码操作

1
2
3
#掩码机制
if attn_mask is not None:
scores = scores.masked_fill(~attn_mask.bool(), float('-inf'))

生成自回归掩码(tgt_mask)

1
2

tgt_mask = torch.tril(torch.ones((T, T), device=captions.device)).bool()
  1. torch.ones((T, T), device=captions.device)

这一步创建了一个形状为 全 1 矩阵

  • T 是序列的长度(句子的单词数);
  • captions.device 确保这个矩阵在和 captions 相同的设备上(CPU 或 GPU)。
  1. torch.tril(…)

torch.tril() 函数返回矩阵的 下三角矩阵,即保留主对角线和下方的部分,把上三角部分置为 0。

经过这一步,矩阵变为:

这样我们就得到了 下三角矩阵,它表示的是在当前位置之前或当前位置的信息。

  1. .bool()

最后,调用 .bool() 方法将矩阵的元素转换为布尔值(True 或 False),1 被转换为 True,0 被转换为 False

最终得到的 tgt_mask 是:

1
2
3
4
5
6
7
8
9
10
11
12
# Step 5: Softmax to get attention weights, then dropout

attn_weights = F.softmax(scores, dim=-1) # (N, H, S, T)

attn_weights = self.attn_drop(attn_weights)



# Step 6: Apply weights to values → (N, H, S, D_head)

attn_output = torch.matmul(attn_weights, V)

1
2

loss_box[matched_gt_deltas < 0]

torch.Tensor.max(dim=…)

这是 PyTorch 中 按维度取最大值 的操作。

作用:

在指定维度上,对张量求最大值,并且返回:

  • 每个子张量的 最大值
  • 以及最大值的 索引(index)

返回值:

1
values, indices = tensor.max(dim=某个维度)

举个例子说明:

1
2
3
4
5
6
import torch

x = torch.tensor([
[1, 3, 2],
[7, 4, 6]
]) # shape: (2, 3)
1
values, indices = x.max(dim=1)

unsqueeze 方法

1
tensor = tensor.unsqueeze(dim)
  • 作用:在指定位置 dim 增加一个维度(大小为 1),不改变数据内容
  • dim:要插入的维度的位置,从 0 开始,可以是负数表示倒数维度。
  • 在 Transformer 中,memory(图像特征)target(文本特征) 必须匹配维度。
  • image_embed.unsqueeze(1) 是将图像特征从 (N, W) 转换为 (N, 1, W),将 1 作为目标序列长度(表示“只有一个 token”)进行适配。
  • 这样处理后,Transformer 解码器能够接受这种形式的输入,把它与文本序列(形状 (N, T, W))结合起来进行计算。

torch. rand/randn

概念

函数 分布 取值范围
torch.rand() 均匀分布 [0, 1)
torch.randn() 正态分布 均值 0,标准差 1,范围是 (-∞, ∞)

操作

  • 可以进行各种变换
1
noise = 2 * torch.rand(batch_size, dim) - 1

torch.meshgrid

torch.meshgrid 是一个用于生成 网格坐标 的函数,常用于图像处理、计算机视觉等任务。在你提供的代码中,torch.meshgrid 被用来创建两个二维网格,分别代表 特征图的高度(grid_x)宽度(grid_y) 上的坐标。

解释:

torch.meshgrid 的作用:

torch.meshgrid 函数生成的是两个张量,分别对应 X 轴坐标Y 轴坐标,它们表示网格的坐标点。假设我们要生成一个二维网格,网格的维度由 arange(H) 和 arange(W) 定义。
代码解析:

1
2
3
4
grid_x, grid_y = torch.meshgrid(
torch.arange(H, dtype=dtype, device=device),
torch.arange(W, dtype=dtype, device=device),
)
  1. torch.arange(H, dtype=dtype, device=device):
  • torch.arange(H) 会生成一个从 0 到 H-1 的一维张量(即 高度 上的坐标)。例如,如果 H = 4,则它会返回一个张量 [0, 1, 2, 3]。
  • dtype=dtype 和 device=device 确保生成的张量与指定的数据类型和设备(如 CPU 或 GPU)一致。
  1. torch.arange(W, dtype=dtype, device=device):
  • 同理,torch.arange(W) 会生成一个从 0 到 W-1 的一维张量(即 宽度 上的坐标)。例如,如果 W = 3,则它会返回一个张量 [0, 1, 2]。
  1. torch.meshgrid():
  • torch.meshgrid 用这两个张量(分别是 arange(H) 和 arange(W))生成 网格坐标,并返回两个张量:
  • grid_x:每个网格点的 X 坐标
  • grid_y:每个网格点的 Y 坐标

生成的 grid_x 和 grid_y 是二维的,它们表示网格上每个位置的具体坐标。它们的形状会是 (H, W),也就是网格的高度和宽度。

举个例子:

假设我们有 H=3 和 W=4,即生成一个 3x4 的网格。

1
2
3
4
grid_x, grid_y = torch.meshgrid(
torch.arange(3),
torch.arange(4)
)

结果是:

  • grid_x
1
2
3
tensor([[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]])
  • grid_y
1
2
3
tensor([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2]])

可以看到,grid_x 中的每一列是相同的(表示 X 坐标),而 grid_y 中的每一行是相同的(表示 Y 坐标)。这就是 网格坐标,每个位置 (i, j) 对应 (grid_x[i][j], grid_y[i][j])。

用途:

  • 网格坐标 常用于图像处理、空间变换等任务。在计算机视觉中,这个网格通常用来表示 像素位置特征图位置
  • 在你的代码中,grid_x 和 grid_y 代表特征图上每个位置的 空间坐标。你可以通过这些坐标计算 每个位置在图像中的实际位置,例如通过 stride 映射到实际图像上的坐标 (xc, yc)。

总结:

  • torch.meshgrid 用于生成网格坐标,通常用于生成二维坐标网格。它接受两个一维张量作为输入,输出两个二维张量,分别表示 X 坐标Y 坐标
  • 在你的代码中,grid_x 和 grid_y 分别表示 特征图位置的横向坐标纵向坐标,它们将被用来计算每个位置的图像坐标 (xc, yc)。

Tensor.clamp_()

基本知识

作用:

clamp_() 是 PyTorch 中的一个 原地操作(in-place)方法,用于将张量中的元素 限制在一个区间范围内,超出范围的值会被截断。
比如:

1
2
3
t = torch.tensor([ -5, 2, 100 ])
t.clamp_(min=0, max=10)
# t => tensor([ 0, 2, 10 ])

语法:

1
tensor.clamp_(min=None, max=None)

或你也可以简写为:

1
tensor.clamp_(0, 100)

_ 下划线的含义

  • clamp_() 是 clamp() 的 in-place 版本
  • 直接 修改原 tensor 本身的值
  • 节省内存开销,更高效
1
2
3
x = torch.tensor([1, 2, 3, 100])
x.clamp_(max=10)
print(x) # tensor([1, 2, 3, 10])

Fcon 中的代码

1
2
3
4
level_pred_boxes[:, 0].clamp_(0, W)  # x1 ∈ [0, W]
level_pred_boxes[:, 1].clamp_(0, H) # y1 ∈ [0, H]
level_pred_boxes[:, 2].clamp_(0, W) # x2 ∈ [0, W]
level_pred_boxes[:, 3].clamp_(0, H) # y2 ∈ [0, H]

是将预测框的四个坐标限制在图像的边界内(防止框超出图像区域),非常常见于目标检测后处理。

tensor.type(dtype)

1
2
dtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor
real_data = x.type(dtype)
  1. 保证张量在正确的设备上(CPU/GPU)

如果模型和数据在不同设备,会报错

  1. 确保数据类型一致(float32)

某些操作(比如反向传播)只能用于 float 类型,不能用 int

更现代的写法

1
2
3
real_data = x.to(dtype)
#或更明确
real_data = x.to(device=torch.device('cuda'), dtype=torch.float)

tensor. detach()

见自动求导框架

torch. stack

1
coords = torch.stack((xc.flatten(), yc.flatten()), dim=-1)
  1. xc.flatten() 和 yc.flatten():
  • flatten() 方法用于将张量从多维数组展平为一维数组。对于 xc 和 yc 这两个 (H, W) 形状的张量,flatten() 会将它们展平为一维张量。
  • 例如,如果 xc 和 yc 都是形状 (H, W) 的二维张量(假设 H = 2 和 W = 3),它们分别会展平为一维张量:
1
2
xc.flatten()  # 变成 (H * W,) = (6,)
yc.flatten() # 变成 (H * W,) = (6,)
  1. torch.stack((xc.flatten(), yc.flatten()), dim=-1):
  • torch.stack() 是将多个张量沿指定维度进行拼接的操作。这里,torch.stack 将展平后的 xc 和 yc 张量按 最后一个维度(dim=-1) 进行拼接。
  • dim=-1 表示按最后一个维度拼接,也就是将每个 (xc, yc) 坐标对拼接成一个 二维向量。每一行表示图像中一个位置的 (xc, yc) 坐标。
  • coords 将会是一个新的张量,形状为 (H * W, 2),每一行包含了特征图位置的 (xc, yc) 坐标。

示例:

假设:

  • H = 2,W = 3,这意味着 xc 和 yc 都是 (2, 3) 的形状。
  • xc 和 yc 的内容如下:
1
2
3
4
xc = tensor([[0, 1, 2],
[3, 4, 5]])
yc = tensor([[0, 0, 0],
[1, 1, 1]])

nonzero()

基本知识

这个是 PyTorch 中的方法,返回布尔张量中值为 True 的 索引位置
例如:

1
2
3
a = torch.tensor([True, False, True])
a.nonzero()
# 输出:tensor([[0], [2]])

random.choice(fg_idxs_p3)

这行就是从前景索引里 随机挑选一个点的下标

比如 fg_idxs_p3 = tensor([[0], [2], [8], [10]]),

那么 random.choice(fg_idxs_p3) 可能会返回 tensor([2])。

注意

因为 nonzero() 的结果是二维的(每个索引是 [i] 而不是单个整数),

你可以加 .item() 变成纯 int 类型:

1
_idx = random.choice(fg_idxs_p3).item()

作业中的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import random

from one_stage_detector import fcos_match_locations_to_gt

# Get an image and its GT boxes from train dataset.

_, image, gt_boxes = train_dataset[0]


# Dictionary with keys {"p3", "p4", "p5"} and values as `(N, 5)` tensors

# giving matched GT boxes.

matched_boxes_per_fpn_level = fcos_match_locations_to_gt(

locations_per_fpn_level, backbone.fpn_strides, gt_boxes

)

# Visualize one selected location (yellow point) and its matched GT box (red).

# Get indices of matched locations (whose class ID is not -1) from P3 level.

#注意这段代码关键,从匹配到框的点里选择

FPN_LEVEL = "p4"

fg_idxs_p3 = (matched_boxes_per_fpn_level[FPN_LEVEL][:, 4] != -1).nonzero(as_tuple=False)


# NOTE: Run this cell multiple times to see different matched points. For car

# image, p3/5 will not work because the one and only box was already assigned

# to p4 due to its compatible size to p4 stride.

_idx = random.choice(fg_idxs_p3).item()

detection_visualizer(

inverse_norm(image),

val_dataset.idx_to_class,

bbox=matched_boxes_per_fpn_level[FPN_LEVEL][_idx],

points=locations_per_fpn_level[FPN_LEVEL][_idx]

)

torch. cat

基本知识

一句话理解:

torch.cat(tensor_list, dim=n)

把多个 形状相同的张量(除了 dim 维) 沿着第 dim 个维度拼接起来。
即对dim 维进行操作

基本语法:

1
torch.cat(tensors, dim=0)
  • tensors:是一个张量列表(list of tensors)
  • dim:指定在哪个维度拼接

⚠️ 所有张量的 shape 必须 除了 dim 维度外,其他维度都要一样。


🔍 举例说明:

例 1:拼接两个 shape 一样的 2D 张量(默认 dim=0

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

b = torch.tensor([[5, 6],
[7, 8]])

out = torch.cat([a, b], dim=0)
print(out)

输出:

1
2
3
4
tensor([[1, 2],
[3, 4],
[5, 6],
[7, 8]])

➡️ 沿着第 0 维(行)拼接,结果是 shape (4, 2)。

例 2:dim=1 沿列拼接

1
2
out = torch.cat([a, b], dim=1)
print(out)

输出:

1
2
tensor([[1, 2, 5, 6],
[3, 4, 7, 8]])

➡️ 沿着第 1 维(列)拼接,结果是 shape (2, 4)。

维度检查(重点)

假设你要沿着 dim=1 拼接,所有张量:

  • 在 dim=1 上可以不一样
  • 但其他维度必须一样!

错误示例:

1
2
3
a = torch.randn(2, 3)
b = torch.randn(4, 3)
torch.cat([a, b], dim=1) # 报错:在 dim=0 上形状不同

作业中的代码

用在 FPN 中的场景:

在 FCOS 或其他检测模型中,经常需要将:

1
2
3
4
5
fpn_feats = {
'p3': Tensor(B, N1, C),
'p4': Tensor(B, N2, C),
'p5': Tensor(B, N3, C),
}

合并成:

1
Tensor(B, N1 + N2 + N3, C)

这就靠:

1
torch.cat([fpn_feats['p3'], fpn_feats['p4'], fpn_feats['p5']], dim=1)

eg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Combine predictions and GT from across all FPN levels.

# shape: (batch_size, num_locations_across_fpn_levels, ...)

matched_gt_boxes = self._cat_across_fpn_levels(matched_gt_boxes)

matched_gt_deltas = self._cat_across_fpn_levels(matched_gt_deltas)

pred_cls_logits = self._cat_across_fpn_levels(pred_cls_logits)

pred_boxreg_deltas = self._cat_across_fpn_levels(pred_boxreg_deltas)

pred_ctr_logits = self._cat_across_fpn_levels(pred_ctr_logits)

@staticmethod

def _cat_across_fpn_levels(

dict_with_fpn_levels: Dict[str, torch.Tensor], dim: int = 1

):

"""

Convert a dict of tensors across FPN levels {"p3", "p4", "p5"} to a

single tensor. Values could be anything - batches of image features,

GT targets, etc.

"""

return torch.cat(list(dict_with_fpn_levels.values()), dim=dim)


default_collate()

基本知识

一句话总结:

default_collate() 是 PyTorch 用来 把一个 batch 的样本合并成张量 的函数。它通常由 DataLoader 在后台自动调用,但你也可以手动用它来将 多个 dict、list、tensor 组成一个 batched 数据结构

举个最简单的例子(以 list of tensors 为例):

你有两个样本,每个样本是一个张量:

1
2
3
4
5
6
7
import torch
from torch.utils.data._utils.collate import default_collate

sample1 = torch.tensor([1, 2, 3])
sample2 = torch.tensor([4, 5, 6])
batch = default_collate([sample1, sample2])
print(batch)

输出:

1
2
3
tensor([[1, 2, 3],
[4, 5, 6]])

➡️ 也就是:

default_collate([Tensor1, Tensor2]) 相当于 torch.stack([Tensor1, Tensor2])


更复杂的情况:List of Dictionaries

我们在 FCOS 中遇到的情况其实更复杂一点:

每个样本(图像)对应一个字典,表示每一层 FPN 上的位置匹配的 GT 框:

1
2
3
4
5
6
7
8
9
10
11
12
13
[
{
'p3': Tensor(N1, 5),
'p4': Tensor(N2, 5),
'p5': Tensor(N3, 5),
},
{
'p3': Tensor(N1, 5),
'p4': Tensor(N2, 5),
'p5': Tensor(N3, 5),
},
...
]

你希望变成一个 batch(多张图像的结构合并在一起):

1
2
3
4
5
{
'p3': Tensor(B, N1, 5),
'p4': Tensor(B, N2, 5),
'p5': Tensor(B, N3, 5),
}

直接写:

1
2
3
from torch.utils.data._utils.collate import default_collate

batched_boxes = default_collate(list_of_dicts)

PyTorch 会自动:

  • 遍历每一层的 key(p3/p4/p5)
  • 对应 key 下的所有样本值进行 stack

所以它的作用总结如下:

输入形式 default_collate 作用
List[Tensor] torch.stack(…)
List[Dict[str, Tensor]] 合并每个键的 value,生成 batched dict
List[Tuple[Tensor, Tensor]] 合并每个位置,变成 Tuple[Tensor, Tensor]
List[int/float] 转为 Tensor

实际作业中的代码

你对每张图像都执行:

1
matched_boxes = fcos_match_locations_to_gt(...)

你得到的是:

1
matched_gt_boxes = [dict1, dict2, ..., dictB]

然后用:

1
matched_gt_boxes = default_collate(matched_gt_boxes)

就会变成:

1
2
3
4
5
{
'p3': Tensor(B, N, 5),
'p4': Tensor(B, N, 5),
'p5': Tensor(B, N, 5),
}

torchvision.transforms (as T)

T.ToTensor()

操作 说明
把 PIL 图像转换为 PyTorch Tensor 通常是 torch.FloatTensor,形状变为 (C, H, W)
把像素值从 [0, 255] 线性缩放到 [0.0, 1.0] 除以 255

torchvision.datasets (as dset)

dset.MNIST

继承自 torch.utils.data.Dataset 的类,表示 MNIST 数据集对象

1
2
3
#常见写法
mnist_train = torchvision.datasets.MNIST(..., transform=T.ToTensor())

功能 说明
getitem 通过索引拿一张图片和它的标签
len 返回样本总数(如 60000)
可配合 DataLoader 自动分 batch 提供训练数据
名称 含义
dset 你自定义的 torchvision.datasets 简写
dset.MNIST PyTorch 内置的 MNIST 数据集类
类型 是一个 Dataset,可以被 DataLoader 使用
常配合 transform 如 T.ToTensor()、T.Normalize()

optim

1
optimizer.zero_grad()

清空梯度

挖个坑

1
optimizer.step()

自动求导框架

@torch.no_grad() 这个装饰器会不计算梯度

tensor.detach()

计算图(computational graph)和反向传播控制, detach() 是用来切断张量与计算图的连接,使它不再参与梯度计算和反向传播。PyTorch 默认会为所有参与计算的 Tensor 构建动态计算图,用于之后反向传播。
但在某些情况下,你并不希望某个张量再被追踪,这时就需要用 .detach() 来“摘出来”。

常见使用场景总结

使用场景 原因 示例
训练判别器时使用生成器输出 只更新判别器,防止梯度流回生成器 G(z).detach()
避免梯度累积(梯度截断) 不想再传播之前的梯度历史 RNN 中截断 BPTT
用于保存输出但不记录梯度 只想保存中间结果,不参与 loss saved = x.detach()
in-place 修改中间变量时 防止原计算图破坏 x = x.detach().requires_grad_()

一些好的框架

Resnet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
################################################################################
# TODO:
# Experiment with any architectures, optimizers, and hyperparameters. #
# Achieve AT LEAST 70% accuracy on the *validation set* within 10 epochs. #
# #
# Note that you can use the check_accuracy function to evaluate on either #
# the test set or the validation set, by passing either loader_test or #
# loader_val as the second argument to check_accuracy. You should not touch #
# the test set until you have finished your architecture and hyperparameter #
# tuning, and only run the test set once at the end to report a final value. #
################################################################################

model = None
optimizer = None

# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
import torch
import torch.nn as nn
import torch.nn.functional as F

class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(out_channels)

self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels)
)

def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
out += self.shortcut(x)
out = F.relu(out)
return out

class ResNetSmall(nn.Module):
def __init__(self):
super(ResNetSmall, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2)
)
self.res1 = ResidualBlock(32, 32)
self.res2 = ResidualBlock(32, 64, stride=2)
self.res3 = ResidualBlock(64, 128, stride=2)
self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(128, 10)

def forward(self, x):
out = self.layer1(x)
out = self.res1(out)
out = self.res2(out)
out = self.res3(out)
out = self.avg_pool(out)
out = out.view(out.size(0), -1)
out = self.fc(out)
return out

model = ResNetSmall().to(device=device)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

################################################################################
# END OF YOUR CODE #
################################################################################

# You should get at least 70% accuracy.if seed is not None:

torch.manual_seed(seed)# You may modify the number of epochs to any number below 15.
train_part34(model, optimizer, epochs=10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

```python
import torch.nn as nn
import torch.nn.functional as F

# 残差基本单元(Residual Block)
class Residual(nn.Module):
def __init__(self, in_channels, out_channels, use_1x1conv=False, strides=1):
super(Residual, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3,
padding=1, stride=strides, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3,
padding=1, stride=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)

if use_1x1conv:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1,
stride=strides, bias=False),
nn.BatchNorm2d(out_channels)
)
else:
self.shortcut = nn.Identity()

def forward(self, x):
y = F.relu(self.bn1(self.conv1(x)))
y = self.bn2(self.conv2(y))
y += self.shortcut(x)
return F.relu(y)

# 封装一个 stage(多个 ResidualBlock)
def resnet_block(input_channels, num_channels, num_residuals, first_block=False):
blk = []
for i in range(num_residuals):
if i == 0 and not first_block:
blk.append(Residual(input_channels, num_channels, use_1x1conv=True, strides=2))
else:
blk.append(Residual(num_channels, num_channels))
return blk

# 构建完整网络结构(类 ResNet-18 缩小版)
b1 = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2)
)

b2 = nn.Sequential(*resnet_block(64, 64, 2, first_block=True)) # 不降采样
b3 = nn.Sequential(*resnet_block(64, 128, 2)) # 降采样
b4 = nn.Sequential(*resnet_block(128, 256, 2)) # 降采样
b5 = nn.Sequential(*resnet_block(256, 512, 2)) # 降采样

net = nn.Sequential(
b1, b2, b3, b4, b5,
nn.AdaptiveAvgPool2d((1, 1)),
nn.Flatten(),
nn.Linear(512, 10)
)

# 放入设备
model = net.to(device=device)

# 优化器
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import torch
import torch.nn as nn
import torch.nn.functional as F

# 残差单元
class Residual(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, use_1x1conv=False):
super(Residual, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3,
stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3,
stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)

if use_1x1conv:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1,
stride=stride, bias=False),
nn.BatchNorm2d(out_channels)
)
else:
self.shortcut = nn.Identity()

def forward(self, x):
y = F.relu(self.bn1(self.conv1(x)))
y = self.bn2(self.conv2(y))
y += self.shortcut(x)
return F.relu(y)

# 构建一个 stage(重复 block)
def make_resnet_stage(in_channels, out_channels, num_blocks, first_stage=False):
layers = []
for i in range(num_blocks):
if i == 0:
if first_stage:
layers.append(Residual(in_channels, out_channels, stride=1, use_1x1conv=True))
else:
layers.append(Residual(in_channels, out_channels, stride=2, use_1x1conv=True))
else:
layers.append(Residual(out_channels, out_channels))
return nn.Sequential(*layers)

# 通用 ResNet 类(支持 ResNet-18/34)
class ResNet(nn.Module):
def __init__(self, block_nums, num_classes=10): # block_nums 例如 [2,2,2,2] 表示 ResNet-18
super(ResNet, self).__init__()
self.net = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2, 2),

make_resnet_stage(64, 64, block_nums[0], first_stage=True),
make_resnet_stage(64, 128, block_nums[1]),
make_resnet_stage(128, 256, block_nums[2]),
make_resnet_stage(256, 512, block_nums[3]),

nn.AdaptiveAvgPool2d((1, 1)),
nn.Flatten(),
nn.Linear(512, num_classes)
)

def forward(self, x):
return self.net(x)

重写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
class FCOS(nn.Module):

"""

FCOS: Fully-Convolutional One-Stage Detector



This class puts together everything you implemented so far. It contains a

backbone with FPN, and prediction layers (head). It computes loss during

training and predicts boxes during inference.

"""



def __init__(

self, num_classes: int, fpn_channels: int, stem_channels: List[int]

):

super().__init__()

self.num_classes = num_classes

######################################################################

# TODO: Initialize backbone and prediction network using arguments. #

######################################################################

# Feel free to delete these two lines: (but keep variable names same)

self.backbone = DetectorBackboneWithFPN(out_channels=fpn_channels)

self.pred_net = FCOSPredictionNetwork(num_classes, fpn_channels, stem_channels)

self._normalizer = 150 # for EMA foreground location averaging

# Replace "pass" statement with your code

######################################################################

# END OF YOUR CODE #

######################################################################



# Averaging factor for training loss; EMA of foreground locations.

# STUDENTS: See its use in `forward` when you implement losses.

self._normalizer = 150 # per image



def forward(

self,

images: torch.Tensor,

gt_boxes: Optional[torch.Tensor] = None,

test_score_thresh: Optional[float] = None,

test_nms_thresh: Optional[float] = None,

):

"""

Args:

images: Batch of images, tensors of shape `(B, C, H, W)`.

gt_boxes: Batch of training boxes, tensors of shape `(B, N, 5)`.

`gt_boxes[i, j] = (x1, y1, x2, y2, C)` gives information about

the `j`th object in `images[i]`. The position of the top-left

corner of the box is `(x1, y1)` and the position of bottom-right

corner of the box is `(x2, x2)`. These coordinates are

real-valued in `[H, W]`. `C` is an integer giving the category

label for this bounding box. Not provided during inference.

test_score_thresh: During inference, discard predictions with a

confidence score less than this value. Ignored during training.

test_nms_thresh: IoU threshold for NMS during inference. Ignored

during training.



Returns:

Losses during training and predictions during inference.

"""



######################################################################

# TODO: Process the image through backbone, FPN, and prediction head #

# to obtain model predictions at every FPN location. #

# Get dictionaries of keys {"p3", "p4", "p5"} giving predicted class #

# logits, deltas, and centerness. #

######################################################################

# Feel free to delete this line: (but keep variable names same)

pred_cls_logits, pred_boxreg_deltas, pred_ctr_logits = None, None, None

# Replace "pass" statement with your code

fpn_feats = self.backbone(images)

pred_cls_logits, pred_boxreg_deltas, pred_ctr_logits = self.pred_net(fpn_feats)

fpn_feats_shapes = {k: v.shape for k, v in fpn_feats.items()}



######################################################################

# TODO: Get absolute co-ordinates `(xc, yc)` for every location in

# FPN levels.

#

# HINT: You have already implemented everything, just have to

# call the functions properly.

######################################################################

# Feel free to delete this line: (but keep variable names same)

locations_per_fpn_level = None

# Replace "pass" statement with your code

locations_per_fpn_level = get_fpn_location_coords(fpn_feats_shapes, self.backbone.fpn_strides, device=images.device)

######################################################################

# END OF YOUR CODE #

######################################################################



if not self.training:

# During inference, just go to this method and skip rest of the

# forward pass.

# fmt: off

return self.inference(

images, locations_per_fpn_level,

pred_cls_logits, pred_boxreg_deltas, pred_ctr_logits,

test_score_thresh=test_score_thresh,

test_nms_thresh=test_nms_thresh,

)

# fmt: on



######################################################################

# TODO: Assign ground-truth boxes to feature locations. We have this

# implemented in a `fcos_match_locations_to_gt`. This operation is NOT

# batched so call it separately per GT boxes in batch.

######################################################################

# List of dictionaries with keys {"p3", "p4", "p5"} giving matched

# boxes for locations per FPN level, per image. Fill this list:

matched_gt_boxes = []

matched_gt_deltas = []

# Replace "pass" statement with your code

for i in range(len(gt_boxes)):

matched_boxes = fcos_match_locations_to_gt(locations_per_fpn_level, self.backbone.fpn_strides, gt_boxes[i])

matched_gt_boxes.append(matched_boxes)



matched_deltas = {

level: fcos_get_deltas_from_locations(locations_per_fpn_level[level], matched_boxes[level], self.backbone.fpn_strides[level])

for level in matched_boxes

}

matched_gt_deltas.append(matched_deltas)

# Calculate GT deltas for these matched boxes. Similar structure

# as `matched_gt_boxes` above. Fill this list:

# matched_gt_deltas = []

# Replace "pass" statement with your code

# pass

######################################################################

# END OF YOUR CODE #

######################################################################



# Collate lists of dictionaries, to dictionaries of batched tensors.

# These are dictionaries with keys {"p3", "p4", "p5"} and values as

# tensors of shape (batch_size, locations_per_fpn_level, 5 or 4)

matched_gt_boxes = default_collate(matched_gt_boxes)

matched_gt_deltas = default_collate(matched_gt_deltas)



# Combine predictions and GT from across all FPN levels.

# shape: (batch_size, num_locations_across_fpn_levels, ...)

matched_gt_boxes = self._cat_across_fpn_levels(matched_gt_boxes)

matched_gt_deltas = self._cat_across_fpn_levels(matched_gt_deltas)

pred_cls_logits = self._cat_across_fpn_levels(pred_cls_logits)

pred_boxreg_deltas = self._cat_across_fpn_levels(pred_boxreg_deltas)

pred_ctr_logits = self._cat_across_fpn_levels(pred_ctr_logits)



# Perform EMA update of normalizer by number of positive locations.

num_pos_locations = (matched_gt_boxes[:, :, 4] != -1).sum()

pos_loc_per_image = num_pos_locations.item() / images.shape[0]

self._normalizer = 0.9 * self._normalizer + 0.1 * pos_loc_per_image



#######################################################################

# TODO: Calculate losses per location for classification, box reg and

# centerness. Remember to set box/centerness losses for "background"

# positions to zero.

######################################################################

# Feel free to delete this line: (but keep variable names same)

loss_cls, loss_box, loss_ctr = None, None, None



# Replace "pass" statement with your code

gt_classes = torch.zeros_like(pred_cls_logits)

for i in range(images.shape[0]):

for j in range(matched_gt_boxes.shape[1]):

class_id = matched_gt_boxes[i, j, 4].long()

if class_id != -1:

gt_classes[i, j, class_id] = 1.0

loss_cls = sigmoid_focal_loss(inputs=pred_cls_logits, targets=gt_classes, reduction="none")



loss_box = 0.25 * F.l1_loss(pred_boxreg_deltas, matched_gt_deltas, reduction="none")

loss_box[matched_gt_deltas < 0] *= 0.0



gt_centerness = fcos_make_centerness_targets(matched_gt_deltas)

loss_ctr = F.binary_cross_entropy_with_logits(pred_ctr_logits, gt_centerness, reduction="none")

loss_ctr[gt_centerness < 0] *= 0.0

######################################################################

# END OF YOUR CODE #

######################################################################

# Sum all locations and average by the EMA of foreground locations.

# In training code, we simply add these three and call `.backward()`

return {

"loss_cls": loss_cls.sum() / (self._normalizer * images.shape[0]),

"loss_box": loss_box.sum() / (self._normalizer * images.shape[0]),

"loss_ctr": loss_ctr.sum() / (self._normalizer * images.shape[0]),

}



@staticmethod

def _cat_across_fpn_levels(

dict_with_fpn_levels: Dict[str, torch.Tensor], dim: int = 1

):

"""

Convert a dict of tensors across FPN levels {"p3", "p4", "p5"} to a

single tensor. Values could be anything - batches of image features,

GT targets, etc.

"""

return torch.cat(list(dict_with_fpn_levels.values()), dim=dim)



def inference(

self,

images: torch.Tensor,

locations_per_fpn_level: Dict[str, torch.Tensor],

pred_cls_logits: Dict[str, torch.Tensor],

pred_boxreg_deltas: Dict[str, torch.Tensor],

pred_ctr_logits: Dict[str, torch.Tensor],

test_score_thresh: float = 0.3,

test_nms_thresh: float = 0.5,

):

"""

Run inference on a single input image (batch size = 1). Other input

arguments are same as those computed in `forward` method. This method

should not be called from anywhere except from inside `forward`.



Returns:

Three tensors:

- pred_boxes: Tensor of shape `(N, 4)` giving *absolute* XYXY

co-ordinates of predicted boxes.



- pred_classes: Tensor of shape `(N, )` giving predicted class

labels for these boxes (one of `num_classes` labels). Make

sure there are no background predictions (-1).



- pred_scores: Tensor of shape `(N, )` giving confidence scores

for predictions: these values are `sqrt(class_prob * ctrness)`

where class_prob and ctrness are obtained by applying sigmoid

to corresponding logits.

"""



# Gather scores and boxes from all FPN levels in this list. Once

# gathered, we will perform NMS to filter highly overlapping predictions.

pred_boxes_all_levels = []

pred_classes_all_levels = []

pred_scores_all_levels = []



for level_name in locations_per_fpn_level.keys():



# Get locations and predictions from a single level.

# We index predictions by `[0]` to remove batch dimension.

level_locations = locations_per_fpn_level[level_name]

level_cls_logits = pred_cls_logits[level_name][0]

level_deltas = pred_boxreg_deltas[level_name][0]

level_ctr_logits = pred_ctr_logits[level_name][0]



##################################################################

# TODO: FCOS uses the geometric mean of class probability and

# centerness as the final confidence score. This helps in getting

# rid of excessive amount of boxes far away from object centers.

# Compute this value here (recall sigmoid(logits) = probabilities)

#

# Then perform the following steps in order:

# 1. Get the most confidently predicted class and its score for

# every box. Use level_pred_scores: (N, num_classes) => (N, )

# 2. Only retain prediction that have a confidence score higher

# than provided threshold in arguments.

# 3. Obtain predicted boxes using predicted deltas and locations

# 4. Clip XYXY box-cordinates that go beyond thr height and

# and width of input image.

##################################################################

# Feel free to delete this line: (but keep variable names same)

level_pred_boxes, level_pred_classes, level_pred_scores = (

None,

None,

None, # Need tensors of shape: (N, 4) (N, ) (N, )

)



# Compute geometric mean of class logits and centerness:

level_pred_scores = torch.sqrt(

level_cls_logits.sigmoid_() * level_ctr_logits.sigmoid_()

)

# Step 1:

# Replace "pass" statement with your code

pass



# Step 2:

# Replace "pass" statement with your code

pass



# Step 3:

# Replace "pass" statement with your code

pass



# Step 4: Use `images` to get (height, width) for clipping.

# Replace "pass" statement with your code

pass

##################################################################

# END OF YOUR CODE #

##################################################################



pred_boxes_all_levels.append(level_pred_boxes)

pred_classes_all_levels.append(level_pred_classes)

pred_scores_all_levels.append(level_pred_scores)



######################################################################

# Combine predictions from all levels and perform NMS.

pred_boxes_all_levels = torch.cat(pred_boxes_all_levels)

pred_classes_all_levels = torch.cat(pred_classes_all_levels)

pred_scores_all_levels = torch.cat(pred_scores_all_levels)



# STUDENTS: This function depends on your implementation of NMS.

keep = class_spec_nms(

pred_boxes_all_levels,

pred_scores_all_levels,

pred_classes_all_levels,

iou_threshold=test_nms_thresh,

)

pred_boxes_all_levels = pred_boxes_all_levels[keep]

pred_classes_all_levels = pred_classes_all_levels[keep]

pred_scores_all_levels = pred_scores_all_levels[keep]

return (

pred_boxes_all_levels,

pred_classes_all_levels,

pred_scores_all_levels,

)

seed

1
2
3
4
5
6
7
8

import torch

torch.manual_seed(0)
print(torch.randn(2)) # 输出固定

torch.manual_seed(0)
print(torch.randn(2)) # 和上面一模一样

注意:

若用的是 GPU,还要加一句:

1
torch.cuda.manual_seed(seed)

甚至更全面控制还会加上:

1
2
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

bce_loss

理论公式 实际实现 本质
mean(BCE over mini-batch) 用 batch 平均近似期望
BCEWithLogitsLoss(logits_fake, 1) 最大化判别器被骗的概率
BCEWithLogitsLoss(logits_fake, 0) 判别器正确识别伪造图像
BCEWithLogitsLoss(logits_real, 1) 判别器正确识别真实图像

loglog


train 和 eval

模式 方法调用 BatchNorm 行为 Dropout 行为
训练模式 .train() 用当前 batch 的统计量 有随机丢弃
推理/测试模式 .eval() 用训练期间累积的统计量 不再丢弃神经元

是否自动处理 batch

Linear / Conv 不用管 batch?

因为这些模块是 nn.Module 封装好的,内部就默认处理第一维为 batch,例如:

1
2
nn.Linear(in_features=96, out_features=1024)
→ 自动处理输入 (B, 96)
1
2
nn.Conv2d(in_channels=1, ...)  
→ 自动处理输入 (B, 1, H, W)
操作类型 是否自动处理 batch 你是否需要管
nn.Linear / nn.Conv2d 会自动 不需要管
view() / reshape() / Unflatten() 不会 你得显式传入 batch_size 或 -1

遍历模型的层,模块

1
2
3
4
5
for m in model.children():
print(m) # 只输出模块

for name, m in model.named_children():
print(name, m) # 输出模块名和模块
  • 常用于自定义替换某一层、或提取某些层
1
2
for name, module in model.named_modules():
print(name, module)

这会遍历整个模型内部所有模块

方法名 是否返回名称 是否递归 用途
children() 遍历顶层子模块
named_children() 遍历顶层并返回名称
named_modules() 遍历所有嵌套模块