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 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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
| import numpy as np import torch import torch.nn as nn
class ConvBNReLU(nn.Module): def __init__(self, in_nc, out_nc, k=3, s=2, nlayer=1): super().__init__() p = (k - 1) // 2 module_list = list() for i in range(nlayer): mid_nc = out_nc if i == nlayer - 1 else in_nc cur_s = s if i == nlayer - 1 else 1 module_list.extend([ nn.Conv2d(in_nc, mid_nc, kernel_size=k, stride=cur_s, padding=p), nn.BatchNorm2d(mid_nc), nn.ReLU(inplace=True) ]) self.block = nn.Sequential(*module_list)
def forward(self, x): out = self.block(x) return out
class DeconvBNReLU(nn.Module): def __init__(self, in_nc, out_nc, k=2, s=2, nlayer=1): super().__init__() p = (k - 1) // 2 module_list = list() for i in range(nlayer): if i == 0: module_list.extend([ nn.ConvTranspose2d(in_nc, out_nc, kernel_size=k, stride=s, padding=p), nn.BatchNorm2d(out_nc), nn.ReLU(inplace=True) ]) else: module_list.extend([ nn.Conv2d(out_nc, out_nc, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(out_nc), nn.ReLU(inplace=True) ]) self.block = nn.Sequential(*module_list)
def forward(self, x): out = self.block(x) return out
class MLP(nn.Module): def __init__(self, in_nc, mid_nc, out_nc, nlayer=2, is_flatten=True): super().__init__() mlp_blocks = list() for i in range(nlayer): cur_in = in_nc if i == 0 else mid_nc cur_out = out_nc if i == nlayer - 1 else mid_nc mlp_blocks.append(nn.Linear(cur_in, cur_out)) if i < nlayer - 1: mlp_blocks.append(nn.BatchNorm1d(cur_out)) mlp_blocks.append(nn.ReLU(cur_out)) self.mlp = nn.Sequential(*mlp_blocks) self.is_flatten = is_flatten
def forward(self, x): if self.is_flatten: vec = torch.flatten(x, start_dim=1) else: vec = x out = self.mlp(vec) return out
class Encoder(nn.Module): def __init__(self, in_nc=1, in_size=(28, 28), base_ch=8, num_layer=2, mlp_nc=128, latent_dim=64): super().__init__() in_h, in_w = in_size self.out_size = (base_ch * (2 ** (num_layer - 1)), in_h // 2 ** num_layer, in_w // 2 ** num_layer) mlp_in_nc = self.out_size[0] * self.out_size[1] * self.out_size[2] basic_blocks = list() for i in range(num_layer): cur_in = in_nc if i == 0 else base_ch * (2 ** (i - 1)) cur_out = base_ch * (2 ** i) basic_blocks.append( ConvBNReLU(cur_in, cur_out, k=3, s=2, nlayer=3) ) self.encode_block = nn.Sequential(*basic_blocks) self.calc_mean = MLP(mlp_in_nc, mlp_nc, latent_dim, is_flatten=True) self.calc_logvar = MLP(mlp_in_nc, mlp_nc, latent_dim, is_flatten=True)
def forward(self, x): feat = self.encode_block(x) mean = self.calc_mean(feat) logvar = self.calc_logvar(feat) return mean, logvar
class Decoder(nn.Module): def __init__(self, in_size=(64, 7, 7), out_nc=1, base_ch=8, num_layer=2, mlp_nc=128, latent_dim=64): super().__init__() mlp_out_nc = in_size[0] * in_size[1] * in_size[2] self.in_size = in_size self.mlp = MLP(latent_dim, mlp_nc, mlp_out_nc, nlayer=2, is_flatten=False) basic_blocks = list() for i in range(num_layer): cur_in = base_ch * (2 ** (num_layer - 1 - i)) cur_out = out_nc if i == num_layer - 1 else base_ch * (2 ** (num_layer - 2 - i)) basic_blocks.append( DeconvBNReLU(cur_in, cur_out, k=2, s=2, nlayer=3) ) self.decode_block = nn.Sequential(*basic_blocks) def forward(self, x): feat = self.mlp(x) feat = feat.view(-1, *self.in_size) out = self.decode_block(feat) return out
class VariationalAutoEncoder(nn.Module): def __init__(self, in_nc=1, in_size=(28, 28), base_ch=8, num_layer_enc=2, num_layer_dec=2, mlp_nc=128, latent_dim=64, decoder_in_size=(16, 7, 7)): super().__init__() self.latent_dim = latent_dim self.encoder = Encoder(in_nc, in_size, base_ch, num_layer_enc, mlp_nc, latent_dim) self.decoder = Decoder(decoder_in_size, in_nc, base_ch, num_layer_dec, mlp_nc, latent_dim)
def reparam(self, mu, logvar): std = torch.exp(logvar / 2) eps = torch.randn_like(std) return mu + std * eps def forward(self, x): mu, logvar = self.encoder(x) z = self.reparam(mu, logvar) output = self.decoder(z) return output, mu, logvar def sample(self, n_samples): z = torch.randn(n_samples, self.latent_dim) samples = self.decoder(z) return samples
if __name__ == "__main__": vae = VariationalAutoEncoder() dummy_input = torch.randn(4, 1, 28, 28) out = vae(dummy_input) print(out.size())
|