-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimg2num.py
More file actions
84 lines (76 loc) · 2.85 KB
/
img2num.py
File metadata and controls
84 lines (76 loc) · 2.85 KB
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
from torch.autograd import Variable
from torch import nn
import torch
import torch.nn.functional as F
import torch.optim as optim
import torchvision.datasets as dset
import torchvision.transforms as transforms
class Img2Num(nn.Module):
def __init__(self):
self.num_classes = 10
super(Img2Num, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5, padding=2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Conv2d(16, 120, 5)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, self.num_classes)
def forward(self, x):
x = x.float()
if len(x.size()) == 2:
(H, W) = x.data.size()
img = img.view(1, 1, H, W)
x = self.conv1(x)
x = F.relu(x)
x = F.max_pool2d(x, 2, 2)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2, 2)
x = self.fc1(x)
(N,C,H,W) = x.size()
x = x.view(N,-1)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
x = F.relu(x)
return x
def train(self):
self.loss_function = nn.MSELoss()
# self.optimizer = optim.SGD(self.parameters(), lr=0.2)
self.optimizer = optim.Adadelta(self.parameters())
# Load MNIST
root = 'torchvision/mnist/'
download = True
trans = transforms.Compose([transforms.ToTensor()])
train_set = dset.MNIST(root=root, train=True, transform=trans, download=download)
batch_size = 256
train_loader = torch.utils.data.DataLoader(
dataset=train_set,
batch_size=batch_size,
shuffle=True)
epoch = 1
if epoch > 1:
print("== Start training for {0:d} epochs".format(epoch))
for i in range(epoch):
# training
batch_idx = 0
for batch_idx, (x, target) in enumerate(train_loader):
self.optimizer.zero_grad()
x, target = Variable(x), Variable(Img2Num.oneHot(target, self.num_classes))
x_pred = self.forward(x)
loss = self.loss_function(x_pred, target)
loss.backward()
self.optimizer.step()
if (batch_idx+1)% 100 == 0:
# print '==>>> batch index: {}, train loss: {:.6f}'.format(batch_idx, loss.data[0])
print '==>>> batch index: {}/{}'.format(batch_idx+1, len(train_loader))
print '==>>> batch index: {}/{}'.format(batch_idx+1, len(train_loader))
if epoch > 1:
print("-- Finish epoch {0:d}".format(i+1))
@staticmethod
def oneHot(target, num_classes):
# oneHot encoding
label = []
for l in target:
label.append([1 if i==l else 0 for i in range(num_classes)])
return torch.FloatTensor(label)