Create inference.py
Browse files- inference.py +45 -0
inference.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torchvision.utils as vutils
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
|
| 6 |
+
class Generator(nn.Module):
|
| 7 |
+
def __init__(self, z_dim, channels, features_g):
|
| 8 |
+
super(Generator, self).__init__()
|
| 9 |
+
self.net = nn.Sequential(
|
| 10 |
+
nn.ConvTranspose2d(z_dim, features_g * 16, 4, 1, 0, bias=False),
|
| 11 |
+
nn.BatchNorm2d(features_g * 16),
|
| 12 |
+
nn.ReLU(True),
|
| 13 |
+
nn.ConvTranspose2d(features_g * 16, features_g * 8, 4, 2, 1, bias=False),
|
| 14 |
+
nn.BatchNorm2d(features_g * 8),
|
| 15 |
+
nn.ReLU(True),
|
| 16 |
+
nn.ConvTranspose2d(features_g * 8, features_g * 4, 4, 2, 1, bias=False),
|
| 17 |
+
nn.BatchNorm2d(features_g * 4),
|
| 18 |
+
nn.ReLU(True),
|
| 19 |
+
nn.ConvTranspose2d(features_g * 4, features_g * 2, 4, 2, 1, bias=False),
|
| 20 |
+
nn.BatchNorm2d(features_g * 2),
|
| 21 |
+
nn.ReLU(True),
|
| 22 |
+
nn.ConvTranspose2d(features_g * 2, features_g, 4, 2, 1, bias=False),
|
| 23 |
+
nn.BatchNorm2d(features_g),
|
| 24 |
+
nn.ReLU(True),
|
| 25 |
+
nn.ConvTranspose2d(features_g, channels, 4, 2, 1, bias=False),
|
| 26 |
+
nn.Tanh()
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
return self.net(x)
|
| 31 |
+
|
| 32 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 33 |
+
Z_DIM = 128
|
| 34 |
+
FEATURES_G = 256
|
| 35 |
+
model = Generator(Z_DIM, 3, FEATURES_G).to(device)
|
| 36 |
+
|
| 37 |
+
model.load_state_dict(torch.load("catgen_v2_generator_only.pth", map_location=device))
|
| 38 |
+
model.eval()
|
| 39 |
+
|
| 40 |
+
with torch.no_grad():
|
| 41 |
+
noise = torch.randn(16, Z_DIM, 1, 1, device=device)
|
| 42 |
+
fake_images = model(noise).detach().cpu()
|
| 43 |
+
|
| 44 |
+
vutils.save_image(fake_images, "generated_cats.png", normalize=True, nrow=4)
|
| 45 |
+
print("16 new cats generated in generated_cats.png!")
|