class CNN(torch.nn.Module):
def __init__(self):
super(CNN, self).__init__()
self._build_net()
def _build_net(self):
self.keep_prob = 0.5
self.layer1 = torch.nn.Sequential(
torch.nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size=2, stride=2))
self.layer2 = torch.nn.Sequential(
torch.nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size=2, stride=2))
self.layer3 = torch.nn.Sequential(
torch.nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size=2, stride=2, padding=1))
self.fc1 = torch.nn.Linear(4 * 4 * 128, 625, bias=True)
torch.nn.init.xavier_uniform_(self.fc1.weight)
self.layer4 = torch.nn.Sequential(
self.fc1,
torch.nn.ReLU(),
torch.nn.Dropout(p=1 - self.keep_prob))
self.fc2 = torch.nn.Linear(625, 10, bias=True)
torch.nn.init.xavier_uniform_(self.fc2.weight)
self.criterion = torch.nn.CrossEntropyLoss()
self.optimizer = torch.optim.Adam(self.parameters(), lr=learning_rate)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = self.layer3(out)
out = out.view(out.size(0), -1)
out = self.layer4(out)
out = self.fc2(out)
return out
def predict(self, x):
self.eval()
return self.forward(x)
def get_accuracy(self, x, y):
prediction = self.predict(x)
correct_prediction = torch.argmax(prediction, 1) == y
self.accuracy = correct_prediction.float().mean().item()
return self.accuracy
def train_model(self, x, y):
self.train()
self.optimizer.zero_grad()
hypothesis = self.forward(x)
self.cost = self.criterion(hypothesis, y)
self.cost.backward()
self.optimizer.step()
return self.cost