-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwork2.py
More file actions
133 lines (112 loc) · 4.31 KB
/
work2.py
File metadata and controls
133 lines (112 loc) · 4.31 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
from sklearn.datasets import fetch_lfw_people
from sklearn.model_selection import train_test_split
import numpy as np
import torch
import torchvision.transforms as transforms
import torch.utils.data as util_data
#transform
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (1.0,))])
#device configuration
device = torch.device('cpu')
#setting up filters for model, using 16 filters
cfg = {
'VGG2' : [32, 32, 'M'],
'VGG4' : [64, 64, 'M', 64, 'M'],
'VGG6' : [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512],
'VGG8' : [256,'M', 128, 'M', 64],
'VGG11' : [256, 256, 'M'],
'VGG16' : [64, 64, 128, 128, 256, 256, 256, 512, 512, 512, 512, 512]
}
# Download the data, if not already on disk and load it as numpy arrays
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
# introspect the images arrays to find the shapes (for plotting)
n_samples, h, w = lfw_people.images.shape
# for machine learning we use the 2 data directly (as relative pixel
# positions info is ignored by this model)
X = lfw_people.data
n_features = X.shape[1]
# the label to predict is the id of the person
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
X_train = X_train[:, np.newaxis, :,np.newaxis]
X_test = X_test[:, np.newaxis, :,np.newaxis]
#y_train = y_train[:, np.newaxis, np.newaxis, :]
#y_test = y_test[:, np.newaxis, np.newaxis, :]
X_train_tensor = torch.from_numpy(X_train)
X_test_tensor = torch.from_numpy(X_test)
y_test_tensor = torch.from_numpy(y_test)
y_train_tensor = torch.from_numpy(y_train)
X_train_tensor_list = torch.split(X_train_tensor, 16)
y_train_tensor_list = torch.split(y_train_tensor, 16)
list(X_train_tensor_list)
list(y_train_tensor_list)
print(len(X_train_tensor_list))
class VGG(torch.nn.Module):
def __init__(self, layers, in_channels, nbr_classes=10):
super(VGG, self).__init__()
self.in_channels = in_channels
self.nbr_classes = nbr_classes
self.features = self.make_layers(cfg[layers], self.in_channels)
self.classifier = torch.nn.Linear(13184, self.nbr_classes)
#118400
#59200
#29600
def forward(self, x):
out = self.features(x)
out = out.view(out.size(0), -1)
out = self.classifier(out)
return out
def make_layers(self, cfg, in_channels):
layers = []
for x in cfg:
if x == 'M':
layers += [torch.nn.MaxPool2d(kernel_size=3, stride=3, padding=1)]
else:
layers += [torch.nn.Conv2d(in_channels, x, kernel_size=3, padding=1),
torch.nn.BatchNorm2d(x),
torch.nn.ReLU(inplace=True)]
in_channels = x
layers += [torch.nn.AvgPool2d(kernel_size=1, stride=1)]
return torch.nn.Sequential(*layers)
"""begin question 1"""
#hyper parameters
channels = 1
learning_rate = 5e-3
epochs = 20
#model = VGG('VGG2', channels, nbr_classes=10)
#model = VGG('VGG4', channels, nbr_classes=10)
#model = VGG('VGG6', channels, nbr_classes=10)
model = VGG('VGG8', channels, nbr_classes=10)
#model = VGG('VGG16', channels, nbr_classes=10)
#model = VGG('VGG11', channels, nbr_classes=10)
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate, momentum=0.9, weight_decay=0.01)
#training of model
model.train()
for epoch in range(epochs):
print("epoch", epoch+1)
for count, (batchx, batchy) in enumerate(zip(X_train_tensor_list, y_train_tensor_list)):
batchx = batchx.to(device)
batchy = batchy.to(device)
outputs = model(batchx)
loss = criterion(outputs, batchy)
optimizer.zero_grad()
loss.backward()
optimizer.step()
#if (count%6 == 0):
# print("loss: ", loss.item())
#testing of model
model.eval()
with torch.no_grad():
correct = 0
total = 0
X_test_tensor = X_test_tensor.to(device)
y_test_tensor = y_test_tensor.to(device)
outputs = model(X_test_tensor)
_, predicted = torch.max(outputs.data, 1)
total += y_test_tensor.size(0)
correct += (predicted == y_test_tensor).sum().item()
print('Test accuracy : {} %'. format(100*correct/total))
print("END")