class ImageClassifier(pl.LightningModule):
def __init__(self):
super(ImageClassifier, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.fc1 = nn.Linear(64 * 6 * 6, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = x.view(-1, 64 * 6 * 6)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return F.log_softmax(x, dim=1)
def training_step(self, batch, batch_idx):
inputs, labels = batch
outputs = self(inputs)
loss = F.nll_loss(outputs, labels)
self.log('train_loss', loss)
return loss
def validation_step(self, batch, batch_idx):
inputs, labels = batch
outputs = self(inputs)
val_loss = F.nll_loss(outputs, labels)
self.log('val_loss', val_loss)
return val_loss
def test_step(self, batch, batch_idx):
inputs, labels = batch
outputs = self(inputs)
test_loss = F.nll_loss(outputs, labels)
preds = torch.argmax(outputs, dim=1)
accuracy = (preds == labels).float().mean()
self.log('test_loss', test_loss)
self.log('test_accuracy', accuracy)
return test_loss
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=1e-3)