-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbasicmodel.py
More file actions
169 lines (137 loc) · 5.71 KB
/
basicmodel.py
File metadata and controls
169 lines (137 loc) · 5.71 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import torch
from PIL import Image
import torchvision
import torch.nn as nn
import numpy as np
import torchvision.transforms as transforms
from torch.utils.data.sampler import SubsetRandomSampler
import pandas as pd
import os
import argparse
class CustomDataset(torch.utils.data.Dataset):
def __init__(self, imagedir, labelfile):
self.imagedir = imagedir
self.labels = pd.read_csv(labelfile)
# label disease or not (0 - healthy, 1 - not healthy)
# self.labels['disease'] = np.where(self.labels['label'] == 10,0,1)
def __getitem__(self, index):
# TODO
# 1. Read one data from file (e.g. using numpy.fromfile, PIL.Image.open).
# 2. Preprocess the data (e.g. torchvision.Transform).
# 3. Return a data pair (e.g. image and label).
img = os.path.join(self.imagedir, self.labels.iloc[index,0])
label = self.labels.iloc[index,1]
return { 'image': transforms.ToTensor()(Image.open(img)),'label':label }
def __len__(self):
return len(self.labels)
class BasicConvNet(nn.Module):
def __init__(self, num_classes):
super(BasicConvNet, self).__init__()
#input channels = 3
# Relu - (3,128,128) to (16,128,128)
# Pool - (16,128,128) to (16,64,64)
self.layer1 = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
# Relu - (16,64,64) to (32,64,64)
# Pool - (32,64,64) to (32,32,32)
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
#Relu - (32,32,32) to (48,32,32)
#Pool - (48,32,32) to (48,16,16)
self.layer3 = nn.Sequential(
nn.Conv2d(32, 48, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(48),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
#Relu - (48,16,16) to (60,16,16)
#Pool - (60,16,16) to (60,8,8)
self.layer4 = nn.Sequential(
nn.Conv2d(48, 60, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(60),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Linear(8*8*60, num_classes)
#Relu - (60,8,8) to (120,8,8)
#Pool - (120,8,8) to (120,4,4)
self.layer5 = nn.Sequential(
nn.Conv2d(60, 120, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(120),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Linear(4*4*120, num_classes)
def forward(self,x):
out = self.layer1(x)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = self.layer5(out)
out = out.reshape(out.size(0), -1)
out = self.fc(out)
return out
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Supply image directory and label filename")
parser.add_argument('--i', help="File path of original image directory")
parser.add_argument('--l', help="Label File name")
args = parser.parse_args()
print(torch.cuda.is_available())
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
num_epochs = 10
num_classes = 15
batch_size = 100
learning_rate = 0.001
validation_split = 0.2
random_seed = 42
data = CustomDataset(imagedir = args.i,
labelfile = args.l)
dataSize = data.__len__()
indices = list(range(int(dataSize)))
split = int(np.floor(validation_split*dataSize))
np.random.seed(random_seed)
np.random.shuffle(indices)
train_indices, test_indices = indices[split:], indices[:split]
train_sampler = SubsetRandomSampler(train_indices)
test_sampler = SubsetRandomSampler(test_indices)
train_loader = torch.utils.data.DataLoader(data, batch_size=batch_size,
sampler=train_sampler)
test_loader = torch.utils.data.DataLoader(data, batch_size=batch_size,
sampler=test_sampler)
model = BasicConvNet(num_classes).to(device)
criterion = nn.MultiMarginLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, sample in enumerate(train_loader):
images = sample['image'].to(device)
labels = sample['label'].to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i + 1) % 5 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))
# Test the model
model.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
with torch.no_grad():
correct = 0
total = 0
for sample in test_loader:
images = sample['image'].to(device)
labels = sample['label'].to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test Accuracy of the model on the {} test images: {} %'.format(len(test_indices), 100 * correct / total))
# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt')