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
|
import torch
from torch.utils.data import DataLoader, Dataset
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
from trainer import Trainer
class PrintLayer(torch.nn.Module):
def forward(self, x):
print(x.shape)
print(x.min())
print(x.max())
return x
class Autoencoder(torch.nn.Module):
def __init__(self, input_dim, latent_dim):
super(Autoencoder, self).__init__()
self.input_dim = input_dim
self.latent_dim = latent_dim
self.latent_size = torch.prod(torch.tensor(latent_dim))
self.encoder = torch.nn.Sequential(
torch.nn.Conv2d(input_dim[0], 16, kernel_size=3, padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(16, 16, kernel_size=3, padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size=2),
torch.nn.Conv2d(16, 32, kernel_size=3, padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(32, 32, kernel_size=3, padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size=2),
torch.nn.Conv2d(32, 64, kernel_size=3, padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(64, 64, kernel_size=3, padding=1),
torch.nn.ReLU(),
torch.nn.Flatten(),
torch.nn.Linear(64 * 7 * 7, self.latent_size),
torch.nn.Sigmoid(),
torch.nn.Unflatten(1, latent_dim),
)
self.decoder = torch.nn.Sequential(
torch.nn.Flatten(),
torch.nn.Linear(self.latent_size, 64 * 7 * 7),
torch.nn.ReLU(),
torch.nn.Unflatten(1, (64, 7, 7)),
torch.nn.Conv2d(64, 64, kernel_size=3, padding=1),
torch.nn.ReLU(),
torch.nn.ConvTranspose2d(64, 32, kernel_size=2, stride=2),
torch.nn.ReLU(),
torch.nn.Conv2d(32, 32, kernel_size=3, padding=1),
torch.nn.ReLU(),
torch.nn.ConvTranspose2d(32, 16, kernel_size=2, stride=2),
torch.nn.ReLU(),
torch.nn.Conv2d(16, 16, kernel_size=3, padding=1),
torch.nn.ReLU(),
torch.nn.Conv2d(16, input_dim[0], kernel_size=3, padding=1),
torch.nn.Sigmoid(),
)
def forward(self, x):
x = self.encoder(x)
x = self.decoder(x)
return x
def encode(self, x):
return self.encoder(x)
def decode(self, x):
return self.decoder(x)
class AutoencoderDataset(Dataset):
def __init__(self, dataset, device='cpu'):
self.dataset = dataset
self.device = device
self.dummy_param = torch.nn.Parameter(torch.empty(0))
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
data = self.dataset[idx][0].to(self.device)
return data, data
def main():
torch.multiprocessing.set_start_method("spawn")
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Load dataset
mnist = datasets.MNIST(
root='data',
train=True,
download=True,
transform=transforms.ToTensor(),
)
dataset = AutoencoderDataset(mnist, device=device)
dataloader = DataLoader(dataset, batch_size=64, shuffle=True,
num_workers=4, persistent_workers=True)
# Initialize model
model = Autoencoder(input_dim=(1, 28, 28), latent_dim=(1, 8, 8))
model.load_state_dict(torch.load('autoencoder.pth'))
model.to(device)
# Train model
trainer = Trainer()
lr = 1e-3
epochs = 10
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
criterion = torch.nn.functional.binary_cross_entropy
trainer.train(model, dataloader, epochs, optimizer, criterion)
# Save model
torch.save(model.state_dict(), 'autoencoder.pth')
# Visualize results
n = 10
with torch.no_grad():
plt.figure(figsize=(2*n, 4))
for i, j in enumerate(torch.randint(0, len(dataset), (n,))):
x, _ = dataset[j]
x = x.unsqueeze(0)
x_hat = model(x)
plt.subplot(2, n, i + 1)
plt.imshow(x.cpu().squeeze().numpy(), cmap='gray')
plt.axis('off')
plt.subplot(2, n, i + n + 1)
plt.imshow(x_hat.cpu().squeeze().numpy(), cmap='gray')
plt.axis('off')
plt.tight_layout()
plt.savefig('autoencoder.tmp.png')
if __name__ == '__main__':
main()
|