File size: 1,596 Bytes
0b2d8e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Module: classifier.py
Authors: Christian Bergler, Hendrik Schroeter
GNU General Public License v3.0
Institution: Friedrich-Alexander-University Erlangen-Nuremberg, Department of Computer Science, Pattern Recognition Lab
Last Access: 27.12.2022
"""

import torch
import torch.nn as nn

DefaultClassifierOpts = {
    "input_channels": 512,
    "pooling": "avg",  # avg, max
    "num_classes": 2,
}

"""
Defines classifier neural network consisting of an input, hidden, and output layer 
(fully connected classification part of the CNN) as well as the forward path computation.
"""
class Classifier(nn.Module):
    def __init__(self, opts: dict = DefaultClassifierOpts):
        super().__init__()
        self._opts = opts
        self._layer_output = dict()
        if opts["pooling"] == "avg":
            self.pooling = lambda x: torch.mean(x, dim=-1)
        elif opts["pooling"] == "max":
            self.pooling = lambda x: torch.max(x, dim=-1)[0]
        else:
            raise ValueError("Unkown pooling option")

        self.linear = nn.Linear(opts["input_channels"], opts["num_classes"])

    def forward(self, x):
        x = x.view(x.size(0), x.size(1), -1)
        hidden_layer = self.pooling(x)
        hidden_layer = hidden_layer.view(hidden_layer.size(0), -1)
        self._layer_output["hidden_layer_1"] = hidden_layer
        output_layer = self.linear(hidden_layer)
        self._layer_output["output_layer"] = output_layer
        return output_layer

    def model_opts(self):
        return self._opts

    def get_layer_output(self):
        return self._layer_output