Critic

Bases: Module

A Critic model for evaluating images in a Generative Adversarial Network (GAN).

This model acts as a critic or discriminator, taking a 2D image and outputting a scalar value representing the authenticity of the image. It uses a series of linear layers with LeakyReLU activations, except for the output layer which is a linear layer. The input images are first flattened before being passed through the layers.

Attributes:
  • layers_config (list of tuple) –

    Configuration of the layers where each tuple contains (in_features, out_features, negative_slope) for LeakyReLU activated layers, and (in_features, out_features) for the final output layer.

  • model (Sequential) –

    The sequential model comprising the linear and activation layers.

Raises:
  • Exception

    If the layers configuration is not provided during the model instantiation, or if the input to the forward pass is None.

Methods:

Name Description
connected_layer

Constructs a series of connected layers based on the provided configuration.

forward

Passes the input through the model to evaluate its authenticity.

Source code in critic.py
 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
class Critic(nn.Module):
    """
    A Critic model for evaluating images in a Generative Adversarial Network (GAN).

    This model acts as a critic or discriminator, taking a 2D image and outputting
    a scalar value representing the authenticity of the image. It uses a series of
    linear layers with LeakyReLU activations, except for the output layer which is
    a linear layer. The input images are first flattened before being passed through
    the layers.

    Attributes:
        layers_config (list of tuple): Configuration of the layers where each tuple contains
                                       (in_features, out_features, negative_slope) for LeakyReLU
                                       activated layers, and (in_features, out_features) for the
                                       final output layer.
        model (nn.Sequential): The sequential model comprising the linear and activation layers.

    Raises:
        Exception: If the layers configuration is not provided during the model instantiation,
                   or if the input to the forward pass is None.

    Methods:
        connected_layer(layers_config): Constructs a series of connected layers based on the provided configuration.
        forward(x): Passes the input through the model to evaluate its authenticity.
    """

    def __init__(self):
        """
        Initializes the Critic model and constructs the model layers based on a predefined configuration.
        """
        super(Critic, self).__init__()
        self.layers_config = [
            (28 * 28, 512, 0.2),
            (512, 256, 0.2),
            (256, 128, 0.2),
            (128, 1),
        ]
        self.model = self.connected_layer(self.layers_config)

    def connected_layer(self, layers_config=None):
        """
        Constructs a series of connected layers based on the provided configuration.

        Args:
            layers_config (list of tuple): Layer configurations where each tuple contains
                                           (in_features, out_features, negative_slope) for LeakyReLU
                                           activated layers, and (in_features, out_features) for the
                                           final output layer.

        Returns:
            nn.Sequential: A sequential model comprising the linear and activation layers.

        Raises:
            Exception: If the layers configuration is not provided.
        """
        layers = OrderedDict()
        if layers_config is not None:
            for index, (in_features, out_features, negative_slope) in enumerate(
                layers_config[:-1]
            ):
                layers["{}_layer".format(index)] = nn.Linear(
                    in_features=in_features, out_features=out_features
                )
                layers["{}_activation".format(index)] = nn.LeakyReLU(
                    negative_slope=negative_slope, inplace=True
                )

            (in_features, out_features) = layers_config[-1]
            layers["out_layer"] = nn.Linear(
                in_features=in_features, out_features=out_features
            )

            return nn.Sequential(layers)
        else:
            raise Exception("Layers configuration is not defined in the Critic.")

    def forward(self, x):
        """
        Forward pass of the critic model.

        Args:
            x (Tensor): A batch of 2D images.

        Returns:
            Tensor: A batch of scalar values representing the authenticity of the input images.

        Raises:
            Exception: If the input x is None.
        """
        if x is not None:
            x = x.reshape(-1, 28 * 28)
            x = self.model(x)
        else:
            raise Exception("Input is not defined in the Critic.")
        return x

__init__()

Initializes the Critic model and constructs the model layers based on a predefined configuration.

Source code in critic.py
43
44
45
46
47
48
49
50
51
52
53
54
def __init__(self):
    """
    Initializes the Critic model and constructs the model layers based on a predefined configuration.
    """
    super(Critic, self).__init__()
    self.layers_config = [
        (28 * 28, 512, 0.2),
        (512, 256, 0.2),
        (256, 128, 0.2),
        (128, 1),
    ]
    self.model = self.connected_layer(self.layers_config)

connected_layer(layers_config=None)

Constructs a series of connected layers based on the provided configuration.

Parameters:
  • layers_config (list of tuple, default: None ) –

    Layer configurations where each tuple contains (in_features, out_features, negative_slope) for LeakyReLU activated layers, and (in_features, out_features) for the final output layer.

Returns:
  • nn.Sequential: A sequential model comprising the linear and activation layers.

Raises:
  • Exception

    If the layers configuration is not provided.

Source code in critic.py
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
def connected_layer(self, layers_config=None):
    """
    Constructs a series of connected layers based on the provided configuration.

    Args:
        layers_config (list of tuple): Layer configurations where each tuple contains
                                       (in_features, out_features, negative_slope) for LeakyReLU
                                       activated layers, and (in_features, out_features) for the
                                       final output layer.

    Returns:
        nn.Sequential: A sequential model comprising the linear and activation layers.

    Raises:
        Exception: If the layers configuration is not provided.
    """
    layers = OrderedDict()
    if layers_config is not None:
        for index, (in_features, out_features, negative_slope) in enumerate(
            layers_config[:-1]
        ):
            layers["{}_layer".format(index)] = nn.Linear(
                in_features=in_features, out_features=out_features
            )
            layers["{}_activation".format(index)] = nn.LeakyReLU(
                negative_slope=negative_slope, inplace=True
            )

        (in_features, out_features) = layers_config[-1]
        layers["out_layer"] = nn.Linear(
            in_features=in_features, out_features=out_features
        )

        return nn.Sequential(layers)
    else:
        raise Exception("Layers configuration is not defined in the Critic.")

forward(x)

Forward pass of the critic model.

Parameters:
  • x (Tensor) –

    A batch of 2D images.

Returns:
  • Tensor

    A batch of scalar values representing the authenticity of the input images.

Raises:
  • Exception

    If the input x is None.

Source code in critic.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def forward(self, x):
    """
    Forward pass of the critic model.

    Args:
        x (Tensor): A batch of 2D images.

    Returns:
        Tensor: A batch of scalar values representing the authenticity of the input images.

    Raises:
        Exception: If the input x is None.
    """
    if x is not None:
        x = x.reshape(-1, 28 * 28)
        x = self.model(x)
    else:
        raise Exception("Input is not defined in the Critic.")
    return x

total_params(model=None)

Calculates the total number of parameters in a given PyTorch model.

The function iterates over all parameters in the model and sums their number of elements to get the total parameter count.

Parameters:
  • model (torch.nn.Module, optional): The model for which the total number of parameters is to be calculated.
Returns:
  • total_params (int): The total number of parameters in the model.
Raises:
  • Exception: If the model is not defined properly (i.e., model is None).
Source code in critic.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def total_params(model=None):
    """
    Calculates the total number of parameters in a given PyTorch model.

    The function iterates over all parameters in the model and sums their number of elements to get the total parameter count.

    ### Parameters:
    - `model` (torch.nn.Module, optional): The model for which the total number of parameters is to be calculated.

    ### Returns:
    - `total_params` (int): The total number of parameters in the model.

    ### Raises:
    - Exception: If the model is not defined properly (i.e., `model` is None).
    """
    total_params = 0
    if model is not None:
        for _, params in model.named_parameters():
            total_params += params.numel()
    else:
        raise Exception("Model is not defined properly".capitalize())

    return total_params