gaviego commited on
Commit
acdfdd8
1 Parent(s): 4417b5c

convolution training

Browse files
Files changed (1) hide show
  1. train_conv.py +48 -0
train_conv.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.optim as optim
4
+ from torchvision import datasets, transforms
5
+ from models import NetConv
6
+
7
+
8
+ # Training settings
9
+ batch_size = 64
10
+ test_batch_size = 1000
11
+ epochs = 10
12
+ lr = 0.01
13
+ momentum = 0.5
14
+ seed = 1
15
+ log_interval = 10
16
+
17
+ torch.manual_seed(seed)
18
+
19
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
+
21
+ kwargs = {'num_workers': 1, 'pin_memory': True} if torch.cuda.is_available() else {}
22
+
23
+ # MNIST Dataset
24
+ train_dataset = datasets.MNIST(root='./data/', train=True, transform=transforms.ToTensor(), download=True)
25
+ test_dataset = datasets.MNIST(root='./data/', train=False, transform=transforms.ToTensor())
26
+
27
+ train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, **kwargs)
28
+ test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=test_batch_size, shuffle=False, **kwargs)
29
+
30
+ model = NetConv().to(device)
31
+ optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum)
32
+
33
+ # Training loop
34
+ for epoch in range(1, epochs + 1):
35
+ model.train()
36
+ for batch_idx, (data, target) in enumerate(train_loader):
37
+ data, target = data.to(device), target.to(device)
38
+ optimizer.zero_grad()
39
+ output = model(data)
40
+ loss = F.nll_loss(output, target)
41
+ loss.backward()
42
+ optimizer.step()
43
+ if batch_idx % log_interval == 0:
44
+ print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
45
+ epoch, batch_idx * len(data), len(train_loader.dataset),
46
+ 100. * batch_idx / len(train_loader), loss.item()))
47
+
48
+ torch.save(model,'mnist_conv.pth')