File size: 1,363 Bytes
146cf41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 numpy as np

import torch.nn as nn
import torch


class Generator(nn.Module):
    def __init__(
        self,
        image_shape: (int, int, int),
        latent_space_dimension: int,
        use_cuda: bool = False,
        saved_model: str or None = None
    ):
        super(Generator, self).__init__()

        self.image_shape = image_shape

        def block(in_feat, out_feat, normalize=True):
            layers = [nn.Linear(in_feat, out_feat)]
            if normalize:
                layers.append(nn.BatchNorm1d(out_feat, 0.8))
            layers.append(nn.LeakyReLU(0.2, inplace=True))
            return layers

        self.model = nn.Sequential(
            *block(latent_space_dimension, 128, normalize=False),
            *block(128, 256),
            *block(256, 512),
            *block(512, 1024),
            nn.Linear(1024, int(np.prod(image_shape))),
            nn.Tanh()
        )
        if saved_model is not None:
            self.model.load_state_dict(
                torch.load(
                    saved_model,
                    map_location=torch.device('cuda' if use_cuda else 'cpu')
                )
            )

    def forward(self, z):
        img = self.model(z)
        img = img.view(img.shape[0], *self.image_shape)
        return img

    def save(self, to):
        torch.save(self.model.state_dict(), to)