ianpan's picture
Initial commit
231edce
raw
history blame contribute delete
5.29 kB
from torch import nn
from typing import Optional, Union
from ...base import (
SegmentationModel,
SegmentationHead,
ClassificationHead,
)
from ...encoders.create import create_encoder
from .decoder import NASFPNDecoder
class NASFPN(SegmentationModel):
"""FPN_ is a fully convolution neural network for image semantic segmentation.
Args:
encoder_name: Name of the classification model that will be used as an encoder (a.k.a backbone)
to extract features of different spatial resolution
encoder_depth: A number of stages used in encoder in range [3, 5]. Each stage generate features
two times smaller in spatial dimensions than previous one (e.g. for depth 0 we will have features
with shapes [(N, C, H, W),], for depth 1 - [(N, C, H, W), (N, C, H // 2, W // 2)] and so on).
Default is 5
encoder_weights: One of **None** (random initialization), **"imagenet"** (pre-training on ImageNet) and
other pretrained weights (see table with available weights for each encoder_name)
decoder_pyramid_channels: A number of convolution filters in Feature Pyramid of FPN_
decoder_segmentation_channels: A number of convolution filters in segmentation blocks of FPN_
decoder_merge_policy: Determines how to merge pyramid features inside FPN. Available options are **add**
and **cat**
decoder_dropout: Spatial dropout rate in range (0, 1) for feature pyramid in FPN_
in_channels: A number of input channels for the model, default is 3 (RGB images)
classes: A number of classes for output mask (or you can think as a number of channels of output mask)
activation: An activation function to apply after the final convolution layer.
Available options are **"sigmoid"**, **"softmax"**, **"logsoftmax"**, **"tanh"**, **"identity"**,
**callable** and **None**.
Default is **None**
upsampling: Final upsampling factor. Default is 4 to preserve input-output spatial shape identity
aux_params: Dictionary with parameters of the auxiliary output (classification head). Auxiliary output is build
on top of encoder if **aux_params** is not **None** (default). Supported params:
- classes (int): A number of classes
- pooling (str): One of "max", "avg". Default is "avg"
- dropout (float): Dropout factor in [0, 1)
- activation (str): An activation function to apply "sigmoid"/"softmax"
(could be **None** to return logits)
Returns:
``torch.nn.Module``: **FPN**
.. _FPN:
http://presentations.cocodataset.org/COCO17-Stuff-FAIR.pdf
"""
def __init__(
self,
encoder_name: str,
encoder_params: dict = {"pretrained": True, "depth": 5},
decoder_pyramid_channels: int = 256,
decoder_segmentation_channels: int = 128,
decoder_stack_times: int = 3,
decoder_merge_policy: str = "add",
dropout: float = 0.2,
in_channels: int = 3,
classes: int = 1,
deep_supervision: bool = False,
activation: Optional[str] = None,
upsampling: int = 2,
aux_params: Optional[dict] = None,
):
super().__init__()
encoder_depth = encoder_params.pop("depth", 5)
self.encoder = create_encoder(
name=encoder_name,
encoder_params=encoder_params,
in_channels=in_channels
)
self.decoder = NASFPNDecoder(
in_channels=self.encoder.out_channels,
depth=encoder_depth,
pyramid_channels=decoder_pyramid_channels,
segmentation_channels=decoder_segmentation_channels,
stack_times=decoder_stack_times,
merge_policy=decoder_merge_policy,
deep_supervision=deep_supervision
)
self.segmentation_head = SegmentationHead(
in_channels=self.decoder.out_channels,
out_channels=classes,
kernel_size=1,
dropout=dropout,
upsampling=upsampling,
)
self.deep_supervision = deep_supervision
if self.deep_supervision:
self.supervisor_heads = []
self.supervisor_heads.append(
SegmentationHead(
in_channels=decoder_pyramid_channels,
out_channels=classes,
dropout=dropout,
kernel_size=3,
upsampling=1,
)
)
self.supervisor_heads.append(
SegmentationHead(
in_channels=decoder_pyramid_channels,
out_channels=classes,
dropout=dropout,
kernel_size=3,
upsampling=1,
)
)
self.supervisor_heads = nn.Sequential(*self.supervisor_heads)
if aux_params is not None:
self.classification_head = ClassificationHead(in_channels=self.encoder.out_channels[-1], **aux_params)
else:
self.classification_head = None
self.name = "fpn-{}".format(encoder_name)
self.initialize()