Solution Review: Building the Generator
Learn to define the network architecture, loss function, and optimiser for the Fashion MNIST generator class.
We'll cover the following...
Solution
Press + to interact
main.py
Generator.py
Discriminator.py
Dataset.py
fashion-mnist_train.csv
import torchimport torch.nn as nn# generator classclass Generator(nn.Module):def __init__(self):# initialise parent pytorch classsuper().__init__()# define neural network layersself.model = nn.Sequential(nn.Linear(100, 200),nn.LeakyReLU(0.02),nn.LayerNorm(200),nn.Linear(200, 784),nn.Sigmoid())# create optimiser, simple stochastic gradient descentself.optimiser = torch.optim.Adam(self.parameters(), lr=0.0001)# counter and accumulator for progressself.counter = 0;self.progress = []passdef forward(self, inputs):# simply run modelreturn self.model(inputs)def train(self, D, inputs, targets):# calculate the output of the networkg_output = self.forward(inputs)# pass onto Discriminatord_output = D.forward(g_output)# calculate errorloss = D.loss_function(d_output, targets)# increase counter and accumulate error every 10self.counter += 1;if (self.counter % 10 == 0):self.progress.append(loss.item())pass# zero gradients, perform a backward pass, update weightsself.optimiser.zero_grad()loss.backward()self.optimiser.step()passdef plot_progress(self):df = pandas.DataFrame(self.progress, columns=['loss'])df.plot(ylim=(0), figsize=(16,8), alpha=0.1, marker='.', grid=True, yticks=(0, 0.25, 0.5, 1.0, 5.0))passpass
Explanation
-
Lines 12-20 ...