Solution Review: Building the Discriminator
Learn to define the network architecture, loss function, and optimiser for the Fashion MNIST discriminator class.
We'll cover the following...
Solution
Press + to interact
main.py
Discriminator.py
Dataset.py
fashion-mnist_train.csv
import torchimport torch.nn as nnfrom torch.utils.data import Dataset# discriminator classclass Discriminator(nn.Module):def __init__(self):# initialise parent pytorch classsuper().__init__()# define neural network layersself.model = nn.Sequential(nn.Linear(784, 200),nn.LeakyReLU(0.02),nn.LayerNorm(200),nn.Linear(200, 1),nn.Sigmoid())# create loss functionself.loss_function = nn.BCELoss()# create optimiser, adamself.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, inputs, targets):# calculate the output of the networkoutputs = self.forward(inputs)# calculate lossloss = self.loss_function(outputs, targets)# increase counter and accumulate error every 10self.counter += 1;if (self.counter % 10 == 0):self.progress.append(loss.item())passif (self.counter % 10000 == 0):print("counter = ", self.counter)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 14-22 define the network architecture ...