mirror of
https://github.com/open-mmlab/mmclassification.git
synced 2025-06-03 21:53:55 +08:00
44 lines
1.2 KiB
Python
44 lines
1.2 KiB
Python
|
import torch.nn as nn
|
||
|
from mmcv.cnn import normal_init
|
||
|
|
||
|
from ..builder import HEADS
|
||
|
from .cls_head import ClsHead
|
||
|
|
||
|
|
||
|
@HEADS.register_module()
|
||
|
class LinearClsHead(ClsHead):
|
||
|
"""Linear classifier head.
|
||
|
|
||
|
Args:
|
||
|
num_classes (int): Number of categories excluding the background
|
||
|
category.
|
||
|
in_channels (int): Number of channels in the input feature map.
|
||
|
loss (dict): Config of classification loss.
|
||
|
""" # noqa: W605
|
||
|
|
||
|
def __init__(self,
|
||
|
num_classes,
|
||
|
in_channels,
|
||
|
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
|
||
|
topk=(1, )):
|
||
|
super(LinearClsHead, self).__init__(loss=loss, topk=topk)
|
||
|
self.in_channels = in_channels
|
||
|
self.num_classes = num_classes
|
||
|
|
||
|
if self.num_classes <= 0:
|
||
|
raise ValueError(
|
||
|
f'num_classes={num_classes} must be a positive integer')
|
||
|
|
||
|
self._init_layers()
|
||
|
|
||
|
def _init_layers(self):
|
||
|
self.fc = nn.Linear(self.in_channels, self.num_classes)
|
||
|
|
||
|
def init_weights(self):
|
||
|
normal_init(self.fc, mean=0, std=0.01, bias=0)
|
||
|
|
||
|
def forward_train(self, x, gt_label):
|
||
|
cls_score = self.fc(x)
|
||
|
losses = self.loss(cls_score, gt_label)
|
||
|
return losses
|