-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.py
170 lines (150 loc) · 5.95 KB
/
main.py
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
170
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, random_split, Subset, ConcatDataset
from torchvision.datasets import *
from torchvision.transforms.transforms import *
from torchvision.transforms.functional import *
from torchvision.utils import save_image
from tqdm import tqdm
from torchplus.utils import Init, ClassificationAccuracy
if __name__ == "__main__":
batch_size = 8
train_epoches = 50
log_epoch = 2
class_num = 40
root_dir = "D:/log/paper1/logZZPMAIN"
dataset_dir = "E:/datasets/at&t face database"
h = 112
w = 92
init = Init(
seed=9970,
log_root_dir=root_dir,
sep=True,
backup_filename=__file__,
tensorboard=True,
comment=f"main AT and T face",
)
output_device = init.get_device()
writer = init.get_writer()
log_dir, model_dir = init.get_log_dir()
data_workers = 2
transform = Compose([Grayscale(num_output_channels=1), ToTensor()])
ds = ImageFolder(dataset_dir, transform=transform)
ds_len = len(ds)
train_ds, test_ds = random_split(ds, [ds_len * 7 // 10, ds_len - ds_len * 7 // 10])
train_ds_len = len(train_ds)
test_ds_len = len(test_ds)
print(train_ds_len)
print(test_ds_len)
train_dl = DataLoader(
dataset=train_ds,
batch_size=batch_size,
shuffle=True,
num_workers=data_workers,
drop_last=True,
pin_memory=True,
)
test_dl = DataLoader(
dataset=test_ds,
batch_size=batch_size,
shuffle=False,
num_workers=data_workers,
drop_last=False,
pin_memory=True,
)
class Net(nn.Module):
def __init__(self, input_features, output_features):
super(Net, self).__init__()
self.input_features = input_features
self.output_features = output_features
self.regression = nn.Linear(
in_features=self.input_features, out_features=self.output_features
)
def forward(self, x):
x = self.regression(x)
return x
class MLP(nn.Module):
def __init__(self, input_features, output_features):
super(MLP, self).__init__()
self.input_features = input_features
self.middle_features = 3000
self.output_features = output_features
self.fc = nn.Linear(
in_features=self.input_features, out_features=self.middle_features
)
self.regression = nn.Linear(
in_features=self.middle_features, out_features=self.output_features
)
def forward(self, x):
x = self.fc(x)
x = self.regression(x)
return x
mynet = Net(h * w, class_num).to(output_device).train(True)
optimizer = optim.SGD(mynet.parameters(), lr=0.01)
for epoch_id in tqdm(range(1, train_epoches + 1), desc="Total Epoch"):
iters = tqdm(train_dl, desc=f"epoch {epoch_id}")
for i, (im, label) in enumerate(iters):
im = im.to(output_device)
label = label.to(output_device)
bs, c, h, w = im.shape
optimizer.zero_grad()
im_flatten = im.reshape([bs, -1])
out = mynet.forward(im_flatten)
ce = nn.CrossEntropyLoss()(out, label)
loss = ce
loss.backward()
optimizer.step()
if epoch_id % log_epoch == 0:
train_ca = ClassificationAccuracy(class_num)
after_softmax = F.softmax(out, dim=-1)
predict = torch.argmax(after_softmax, dim=-1)
train_ca.accumulate(label=label, predict=predict)
acc_train = train_ca.get()
writer.add_scalar("loss", loss, epoch_id)
writer.add_scalar("acc_training", acc_train, epoch_id)
with open(os.path.join(model_dir, f"mynet_{epoch_id}.pkl"), "wb") as f:
torch.save(mynet.state_dict(), f)
with torch.no_grad():
mynet.eval()
r = 0
celoss = 0
test_ca = ClassificationAccuracy(class_num)
for i, (im, label) in enumerate(tqdm(train_dl, desc="testing train")):
r += 1
im = im.to(output_device)
label = label.to(output_device)
bs, c, h, w = im.shape
im_flatten = im.reshape([bs, -1])
out = mynet.forward(im_flatten)
ce = nn.CrossEntropyLoss()(out, label)
after_softmax = F.softmax(out, dim=-1)
predict = torch.argmax(after_softmax, dim=-1)
test_ca.accumulate(label=label, predict=predict)
celoss += ce
celossavg = celoss / r
acc_test = test_ca.get()
writer.add_scalar("train loss", celossavg, epoch_id)
writer.add_scalar("acc_train", acc_test, epoch_id)
r = 0
celoss = 0
test_ca = ClassificationAccuracy(class_num)
for i, (im, label) in enumerate(tqdm(test_dl, desc="testing test")):
r += 1
im = im.to(output_device)
label = label.to(output_device)
bs, c, h, w = im.shape
im_flatten = im.reshape([bs, -1])
out = mynet.forward(im_flatten)
ce = nn.CrossEntropyLoss()(out, label)
after_softmax = F.softmax(out, dim=-1)
predict = torch.argmax(after_softmax, dim=-1)
test_ca.accumulate(label=label, predict=predict)
celoss += ce
celossavg = celoss / r
acc_test = test_ca.get()
writer.add_scalar("test loss", celossavg, epoch_id)
writer.add_scalar("acc_test", acc_test, epoch_id)
writer.close()