LH-Tech-AI commited on
Commit
fc14946
·
verified ·
1 Parent(s): c6354b6

Create inference.py

Browse files
Files changed (1) hide show
  1. inference.py +46 -0
inference.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Setup
33
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
34
+ Z_DIM = 128
35
+ FEATURES_G = 256
36
+ model = Generator(Z_DIM, 3, FEATURES_G).to(device)
37
+
38
+ model.load_state_dict(torch.load("facegen_v1_generator_only.pth", map_location=device))
39
+ model.eval()
40
+
41
+ with torch.no_grad():
42
+ noise = torch.randn(16, Z_DIM, 1, 1, device=device)
43
+ fake_images = model(noise).detach().cpu()
44
+
45
+ vutils.save_image(fake_images, "generated_faces.png", normalize=True, nrow=4)
46
+ print("16 new faces generated in generated_faces.png!")