数据 常用数据集两种格式讲解:
第一种数据形式:
「文件夹名就是 label」 dataset/ ├── cat/ │ ├── cat1. jpg │ ├── cat2. jpg ├── dog/ │ ├── dog1. jpg │ ├── dog2. jpg
这里的每个子文件夹名(比如 cat, dog)就是该文件夹中所有图片的标签(label)。这种结构常被 ImageFolder 自动支持,写自定义 Dataset 也很直观:
第二种数据形式:
「用文本文件来提供标签」
比如你有图片和一个对应的 label 文件: images/ ├── 001. jpg ├── 002. jpg labels. txt:
jpg 0
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 osfrom torch.utils.data import Datasetfrom PIL import Imageclass 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 transformstransform = transforms.Compose([ transforms.Resize((224 , 224 )), transforms.ToTensor() ]) dataset = MyFolderDataset(root_dir='dataset' , transform=transform) from torch.utils.data import DataLoaderloader = 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 osfrom torch.utils.data import Datasetfrom PIL import Imageclass 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 transformstransform = 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 DataLoaderloader = 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 osfrom torch.utils.data import Datasetfrom PIL import Imageclass 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 transformstransform = transforms.Compose([ transforms.Resize((224 , 224 )), transforms.ToTensor() ]) dataset = MyImageTxtLabelDataset( image_dir='dataset/images' , label_dir='dataset/labels' , transform=transform, multi_label=False ) from torch.utils.data import DataLoaderloader = 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 osimport jsonimport torchfrom PIL import Imagefrom torchvision import transformsfrom torch.utils.data import Datasetclass 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 使用,以便实现多尺度目标检测。
feature_extraction.create_feature_extractor:
这是一个工具函数,通常用于从一个预训练的卷积神经网络模型(如 ResNet、RegNet 等)中提取中间层的特征图。
通过这个函数,你可以选择从某些特定的层(如 block2、block3、block4 等)获取输出,而不是仅仅使用最后一个输出层。这个功能对于目标检测或其他需要多尺度特征的任务特别有用。
_cnn:
这是你之前加载的 RegNetX-400MF 模型(一个预训练的 CNN),它包含了多个卷积块,经过训练后能够提取有用的图像特征。
return_nodes:
这是一个字典,指定了你希望从 _cnn 模型中提取的特定层的输出。字典的格式是:{模型的层名称: 自定义的层名称}。
在这个例子中:
“trunk_output.block2” → “c3”:提取 block2 层的输出,并将其命名为 c3。这是一个低层次的特征,包含了细节信息。
“trunk_output.block3” → “c4”:提取 block3 层的输出,并将其命名为 c4。这一层提取的是中层特征,包含更多语义信息。
“trunk_output.block4” → “c5”:提取 block4 层的输出,并将其命名为 c5。这一层提取的是高层特征,通常用于捕捉图像的全局信息。
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 torchimport torch.nn as nnmodule_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' ])
为什么使用 ModuleDict?
自动注册参数:
使用 nn.ModuleDict 存储的所有子模块会自动注册为 nn.Module 的子模块,因此它们的参数(权重和偏置)会被自动添加到模型的 parameters() 中,这样可以方便地进行梯度计算和优化。
便于管理多个模块:
在构建复杂网络时,通常会使用多个层(如卷积层、池化层、线性层等)。使用 ModuleDict 可以将这些层按名称组织起来,避免手动维护每一层。
动态访问模块:
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__() 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 ): 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 ) 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’] 等来访问各个子模块,然后用它们执行前向传播。
特点:
自动追踪参数 :nn.ModuleDict 会自动跟踪包含在其中的子模块的参数和梯度,因此你不需要手动注册它们。
方便管理 :当你的网络结构变得复杂时,ModuleDict 可以帮助你以字典的形式存储层,使得代码更清晰、更容易管理。
动态模块访问 :你可以根据需要动态访问、修改或替换子模块。
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 torchimport torch.nn.functional as Fclass 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" , }, ) 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 ), }) 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 ): backbone_feats = self .backbone(images) fpn_feats = {"p3" : None , "p4" : None , "p5" : None } 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" ]) 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" ) 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
nn. F F.interpolate F.interpolate 是 PyTorch 中的一个函数,用于对张量(通常是图像或特征图)进行上采样 或下采样 操作,即改变张量的空间尺寸(高度和宽度)。它支持多种上采样和下采样的方式,包括最邻近插值、双线性插值等。
1 2 3 import torch.nn.functional as Foutput = F.interpolate(input , scale_factor=2 , mode="nearest" )
参数说明:
input :要进行插值操作的输入张量。通常是一个图像或特征图,形状为 (B, C, H, W),其中 B 是批次大小,C 是通道数,H 是高度,W 是宽度。
scale_factor :用于定义上采样或下采样的比例。
scale_factor=2 表示对张量的空间尺寸(高度和宽度)进行 2 倍的上采样,即将张量的高度和宽度都放大两倍。
如果 scale_factor 小于 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 ) K = K.view(N, T, H, D_head).transpose(1 , 2 ) V = V.view(N, T, H, D_head).transpose(1 , 2 )
并行操作: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 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 ()
torch.ones((T, T), device=captions.device)
这一步创建了一个形状为 的 全 1 矩阵 。
T 是序列的长度(句子的单词数);
captions.device 确保这个矩阵在和 captions 相同的设备上(CPU 或 GPU)。
torch.tril(…)
torch.tril() 函数返回矩阵的 下三角矩阵 ,即保留主对角线和下方的部分,把上三角部分置为 0。
经过这一步,矩阵变为:
这样我们就得到了 下三角矩阵 ,它表示的是在当前位置之前或当前位置的信息。
.bool()
最后,调用 .bool() 方法将矩阵的元素转换为布尔值(True 或 False),1 被转换为 True,0 被转换为 False 。
最终得到的 tgt_mask 是:
1 2 3 4 5 6 7 8 9 10 11 12 attn_weights = F.softmax(scores, dim=-1 ) attn_weights = self .attn_drop(attn_weights) 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 torchx = torch.tensor([ [1 , 3 , 2 ], [7 , 4 , 6 ] ])
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), )
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)一致。
torch.arange(W, dtype=dtype, device=device):
同理,torch.arange(W) 会生成一个从 0 到 W-1 的一维张量(即 宽度 上的坐标)。例如,如果 W = 3,则它会返回一个张量 [0, 1, 2]。
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 ) )
结果是:
1 2 3 tensor([[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]])
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 )
语法:
1 tensor.clamp_(min =None , max =None )
或你也可以简写为:
_ 下划线的含义
clamp_() 是 clamp() 的 in-place 版本
直接 修改原 tensor 本身的值
节省内存开销,更高效
1 2 3 x = torch.tensor([1 , 2 , 3 , 100 ]) x.clamp_(max =10 ) print (x)
Fcon 中的代码 1 2 3 4 level_pred_boxes[:, 0 ].clamp_(0 , W) level_pred_boxes[:, 1 ].clamp_(0 , H) level_pred_boxes[:, 2 ].clamp_(0 , W) level_pred_boxes[:, 3 ].clamp_(0 , H)
是将预测框的四个坐标限制在图像的边界内(防止框超出图像区域),非常常见于目标检测后处理。
tensor.type(dtype) 1 2 dtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor real_data = x.type (dtype)
保证张量在正确的设备上(CPU/GPU)
如果模型和数据在不同设备,会报错
确保数据类型一致(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 )
xc.flatten() 和 yc.flatten() :
flatten() 方法用于将张量从多维数组展平为一维数组。对于 xc 和 yc 这两个 (H, W) 形状的张量,flatten() 会将它们展平为一维张量。
例如,如果 xc 和 yc 都是形状 (H, W) 的二维张量(假设 H = 2 和 W = 3),它们分别会展平为一维张量:
1 2 xc.flatten() yc.flatten()
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()
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 randomfrom one_stage_detector import fcos_match_locations_to_gt_, image, gt_boxes = train_dataset[0 ] matched_boxes_per_fpn_level = fcos_match_locations_to_gt( locations_per_fpn_level, backbone.fpn_strides, gt_boxes ) FPN_LEVEL = "p4" fg_idxs_p3 = (matched_boxes_per_fpn_level[FPN_LEVEL][:, 4 ] != -1 ).nonzero(as_tuple=False ) _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 )
作业中的代码 用在 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 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 torchfrom torch.utils.data._utils.collate import default_collatesample1 = 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_collatebatched_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 ), }
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
清空梯度
挖个坑
自动求导框架 @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 model = None optimizer = None import torchimport torch.nn as nnimport torch.nn.functional as Fclass 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 ) torch.manual_seed(seed) 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 nnimport torch.nn.functional as Fclass 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) 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 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 torchimport torch.nn as nnimport torch.nn.functional as Fclass 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) 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) class ResNet (nn.Module): def __init__ (self, block_nums, num_classes=10 ): 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_classesself .backbone = DetectorBackboneWithFPN(out_channels=fpn_channels)self .pred_net = FCOSPredictionNetwork(num_classes, fpn_channels, stem_channels)self ._normalizer = 150 self ._normalizer = 150 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. """ pred_cls_logits, pred_boxreg_deltas, pred_ctr_logits = None , None , None 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()} locations_per_fpn_level = None locations_per_fpn_level = get_fpn_location_coords(fpn_feats_shapes, self .backbone.fpn_strides, device=images.device) if not self .training: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, ) matched_gt_boxes = [] matched_gt_deltas = [] 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) matched_gt_boxes = default_collate(matched_gt_boxes) matched_gt_deltas = default_collate(matched_gt_deltas) 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) 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 loss_cls, loss_box, loss_ctr = None , None , None 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 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. """ pred_boxes_all_levels = [] pred_classes_all_levels = [] pred_scores_all_levels = [] for level_name in locations_per_fpn_level.keys(): 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 ] level_pred_boxes, level_pred_classes, level_pred_scores = ( None ,None ,None , ) level_pred_scores = torch.sqrt( level_cls_logits.sigmoid_() * level_ctr_logits.sigmoid_() ) pass pass pass pass pred_boxes_all_levels.append(level_pred_boxes) pred_classes_all_levels.append(level_pred_classes) pred_scores_all_levels.append(level_pred_scores) 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) 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 torchtorch.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()
是
是
遍历所有嵌套模块