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
| import torch import torch.nn as nn from torch.utils.data import Dataset
import pandas import matplotlib.pyplot as plt
class View(nn.Module): def __init__(self, shape): super().__init__() self.shape = shape,
def forward(self, x): return x.view(*self.shape) class MnistDataset(Dataset): def __init__(self, csv_file): self.data_df = pandas.read_csv(csv_file, header=None) def __len__(self): return len(self.data_df) def __getitem__(self, index): label = self.data_df.iloc[index,0] target = torch.zeros((10)) target[label] = 1.0 image_values = torch.tensor(self.data_df.iloc[index,1:].values,dtype=torch.float) / 255.0 return label, image_values, target def plot_image(self, index): img = self.data_df.iloc[index,1:].values.reshape(28,28) plt.title("label = " + str(self.data_df.iloc[index,0])) plt.imshow(img, interpolation='none', cmap='Blues')
class Classifier(nn.Module): def __init__(self):
super().__init__() self.model = nn.Sequential( nn.Conv2d(1, 10, kernel_size=5, stride=2), nn.LeakyReLU(0.02), nn.BatchNorm2d(10), nn.Conv2d(10, 10, kernel_size=3, stride=2), nn.LeakyReLU(0.02), nn.BatchNorm2d(10), View(250), nn.Linear(250, 10), nn.Sigmoid() ) self.loss_function = nn.BCELoss()
self.optimiser = torch.optim.Adam(self.parameters())
self.counter = 0 self.progress = [] def forward(self, inputs): return self.model(inputs) def train(self, inputs, targets):
outputs = self.forward(inputs)
loss = self.loss_function(outputs, targets)
self.counter += 1 if (self.counter % 10 == 0): self.progress.append(loss.item()) pass if (self.counter % 10000 == 0): print("counter = ", self.counter) pass
self.optimiser.zero_grad() loss.backward() self.optimiser.step()
def plot_progress(self): df = pandas.DataFrame(self.progress, columns=['loss']) df.plot(ylim=(0, 1.0), figsize=(16,8), alpha=0.1, marker='.', grid=True, yticks=(0, 0.25, 0.5))
|