-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcVAE_arch2_copied_0906_.py
182 lines (142 loc) · 5.28 KB
/
cVAE_arch2_copied_0906_.py
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 12:02:09 2020
architecture copied and edited from:
https://github.com/AntixK/PyTorch-VAE/blob/master/models/vanilla_vae.py
@author: Jack
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import umap
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sklearn
from sklearn.preprocessing import MinMaxScaler
from sklearn.cluster import KMeans
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
debug = False
class Display(nn.Module):
def forward(self, input):
if debug == True:
print(input.shape)
return input
class VAE(nn.Module):
def __init__(self, image_channels=1, h_dims:list=[32, 64, 128, 256, 512],
z_dim=12):
super(VAE, self).__init__()
self.z_dim = z_dim
modules = []
h_dims = [32, 64, 128, 256, 512]
self.h_dims = h_dims
# Build Encoder
for h_dim in h_dims:
modules.append(
nn.Sequential(
Display(),
nn.Conv2d(image_channels, out_channels=h_dim,
kernel_size= 3, stride= 2, padding = 1),
Display(),
nn.BatchNorm2d(h_dim),
Display(),
nn.LeakyReLU(),
Display())
)
image_channels = h_dim
self.encoder = nn.Sequential(*modules)
self.fc_mu = nn.Linear(h_dims[-1], z_dim)
self.fc_var = nn.Linear(h_dims[-1], z_dim)
# Build Decoder
modules = []
self.decoder_input = nn.Linear(z_dim, h_dims[-1])
h_dims.reverse()
for i in range(len(h_dims) - 1):
pad = 1
if i == 2:
pad = 0
modules.append(
nn.Sequential(
Display(),
nn.ConvTranspose2d(h_dims[i],
h_dims[i + 1],
kernel_size=3,
stride = 2,
padding=1,
output_padding=pad),
Display(),
nn.BatchNorm2d(h_dims[i + 1]),
Display(),
nn.LeakyReLU(),
Display())
)
self.decoder = nn.Sequential(*modules)
self.final_layer = nn.Sequential(
Display(),
nn.ConvTranspose2d(32,
1,
kernel_size=3,
stride=2,
padding=1,
output_padding=1),
Display(),
nn.BatchNorm2d(1),
Display(),
nn.ReLU(),
Display())
#nn.Conv2d(h_dims[-1], out_channels=1,
# kernel_size= 3, padding= 1),
#Display(),
#nn.ReLU(), #was tanh
#Display())
def encode(self, data):
result = self.encoder(data)
if debug == True:
print(f"Enc output = {result.shape}")
result = torch.flatten(result, start_dim=1)
if debug == True:
print(f"flattened: {result.shape}")
# Split the result into mu and var components
# of the latent Gaussian distribution
mu = self.fc_mu(result)
log_var = self.fc_var(result)
if debug == True:
print(f"fc_mu: {mu.shape}")
return mu, log_var
def decode(self, z):
result = self.decoder_input(z)
if debug == True:
print(f"decoderinput layer = {result.shape}")
result = result.view(-1, self.h_dims[0], 1, 1)
result = self.decoder(result)
result = self.final_layer(result)
return result
def reparameterize(self, mu, logvar):
std = logvar.mul(0.5).exp_()
# return torch.normal(mu, std)
esp = torch.randn(*mu.size())
z = mu + std * esp
return z
def representation(self, x):
x = x.type(torch.float)
mu, logvar = self.encode(x)
return mu, logvar
def forward(self, x):
x = x.type(torch.float)
mu, logvar = self.encode(x)
z = self.reparameterize(mu, logvar)
output = self.decode(z)
if debug == True:
print(output.shape)
return output, mu, logvar
def sample(self, num=1):
z = torch.randn(num, self.z_dim)
output = self.decode(z)
return output
if __name__ == '__main__':
x = VAE()