Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

Race_Classifier.py 9.6 KB

You have to be logged in to leave a comment. Sign In
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
  1. import torch
  2. # print(torch.__version__)
  3. from torch.utils.data import Dataset, DataLoader
  4. import torch
  5. import torch.nn as nn
  6. import pandas as pd
  7. from torchvision import transforms, utils
  8. import cv2
  9. import torch.backends.cudnn as cudnn
  10. cudnn.benchmark = False
  11. from torchsummary import summary
  12. # from google.colab import drive
  13. import os
  14. import numpy as np
  15. import torch.optim as optim
  16. from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, ConfusionMatrixDisplay
  17. from time import sleep
  18. from tqdm import tqdm
  19. class ClassifierModel(nn.Module):
  20. def __init__(self):
  21. super(ClassifierModel, self).__init__()
  22. self.conv1 = nn.Conv2d(3, 16, 3, padding=1)
  23. self.relu1 = nn.ReLU()
  24. self.batch1 = nn.BatchNorm2d(16)
  25. self.maxpool1 = nn.MaxPool2d(3)
  26. self.drop1 = nn.Dropout(p=0.25)
  27. self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
  28. self.relu2 = nn.ReLU()
  29. self.batch2 = nn.BatchNorm2d(32)
  30. self.maxpool2 = nn.MaxPool2d(2)
  31. self.drop2 = nn.Dropout(p=0.25)
  32. self.conv3 = nn.Conv2d(32, 32, 3, padding=1)
  33. self.relu3 = nn.ReLU()
  34. self.batch3 = nn.BatchNorm2d(32)
  35. self.maxpool3 = nn.MaxPool2d(2)
  36. self.drop3 = nn.Dropout(p=0.25)
  37. self.flatten = nn.Flatten()
  38. self.dense1 = nn.LazyLinear(128)
  39. self.relu4 = nn.ReLU()
  40. self.batch4 = nn.BatchNorm1d(128)
  41. self.drop4 = nn.Dropout(p=0.5)
  42. self.dense2 = nn.LazyLinear(7)
  43. self.soft = nn.Softmax(dim=1)
  44. def forward(self, x):
  45. x = self.conv1(x)
  46. x = self.relu1(x)
  47. x = self.batch1(x)
  48. x = self.maxpool1(x)
  49. x = self.drop1(x)
  50. x = self.conv2(x)
  51. x = self.relu2(x)
  52. x = self.batch2(x)
  53. x = self.maxpool2(x)
  54. x = self.drop2(x)
  55. x = self.conv3(x)
  56. x = self.relu3(x)
  57. x = self.batch3(x)
  58. x = self.maxpool3(x)
  59. x = self.drop3(x)
  60. x = self.flatten(x)
  61. x = self.dense1(x)
  62. x = self.relu4(x)
  63. x = self.batch4(x)
  64. x = self.drop4(x)
  65. x = self.dense2(x)
  66. x = self.soft(x)
  67. return x
  68. class custom_transformer():
  69. def __init__(self, img_size):
  70. # Get image you want to resize to at intilization
  71. self.img_size = img_size
  72. def __call__(self, sample):
  73. self.img, self.label = sample["image"], sample["label"]
  74. # resize image
  75. self.img = cv2.resize(self.img, self.img_size)
  76. tensor = transforms.ToTensor()
  77. norm = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
  78. ## Transform image into tensor then normalize values
  79. self.img = tensor(self.img)
  80. self.img = norm(self.img)
  81. ## Transform label into tensor then normalize values
  82. self.label = torch.FloatTensor([self.label]).long()
  83. return {"image": self.img, "label": self.label}
  84. class custom_dataset():
  85. def __init__(self, csv_file, root_dir, transform=None):
  86. # print("Dataset intialized")
  87. ## Read csv file
  88. self.images = pd.read_csv(csv_file)
  89. ## Get data root directory
  90. self.root_dir = root_dir
  91. ## get the transform function
  92. self.transform = transform
  93. self.races = {"White": 0, "Black": 1, "East Asian": 2, "Indian": 3, "Latino_Hispanic": 4, "Middle Eastern": 5,
  94. "Southeast Asian": 6}
  95. def __len__(self):
  96. return len(self.images)
  97. def __getitem__(self, idx):
  98. # print("Get Item")
  99. if torch.is_tensor(idx):
  100. idx = idx.tolist()
  101. img_name = os.path.join(self.root_dir, self.images.iloc[idx, 0])
  102. image = cv2.imread(img_name)
  103. # transform race to id using the self.races dictionary
  104. labels = self.races[self.images.iloc[idx, 3]]
  105. sample = {'image': image, 'label': labels}
  106. if self.transform:
  107. sample = self.transform(sample)
  108. # print(sample)
  109. return sample
  110. def eval_model(model, validation_loader, criterion, device):
  111. model.eval()
  112. running_loss = 0
  113. val_label = []
  114. val_prediction = []
  115. print("Validation Time !!")
  116. with tqdm(validation_loader, unit="batch") as vepoch:
  117. for sample in vepoch:
  118. vepoch.set_description("Validation Epoch")
  119. imgs, labels = sample['image'], sample['label']
  120. imgs = imgs.to(device)
  121. labels = labels.to(device)
  122. # Get Loss for validation
  123. logits = model(imgs)
  124. loss = criterion(logits, torch.reshape(labels, (-1,)))
  125. running_loss += loss.item()
  126. # Get All Preditions and Labels in the validation set
  127. val_label = val_label + labels.tolist()
  128. argmax_logits = torch.argmax(logits, dim=1)
  129. val_prediction = val_prediction + argmax_logits.tolist()
  130. vepoch.set_postfix(loss=loss.item())
  131. sleep(0.1)
  132. val_label = np.array(val_label)
  133. val_prediction = np.array(val_prediction)
  134. val_label = torch.tensor(val_label.flatten())
  135. val_prediction = torch.tensor(val_prediction.flatten())
  136. model.train()
  137. return running_loss / len(validation_loader), accuracy_score(val_label, val_prediction), recall_score(val_label,
  138. val_prediction,
  139. average='micro'), precision_score(
  140. val_label, val_prediction, average='micro'), confusion_matrix(val_label, val_prediction)
  141. def train_model(model, device, train_dataloader, validation_dataloader, n_epoch, save_path):
  142. criterion = nn.CrossEntropyLoss()
  143. optimizer = optim.Adam(model.parameters(), lr=0.0001)
  144. torch.backends.cudnn.benchmark = False
  145. for epoch in range(n_epoch):
  146. print("Epoch number:", epoch)
  147. model.train()
  148. running_loss = 0
  149. train_label = []
  150. train_prediction = []
  151. with tqdm(train_dataloader, unit="batch") as tepoch:
  152. for sample in tepoch:
  153. tepoch.set_description(f"Epoch {epoch}")
  154. ## Get Images and Labels
  155. imgs = sample['image'].to(device)
  156. labels = sample['label'].to(device)
  157. # Prepare Optimzer
  158. optimizer.zero_grad()
  159. # Get Prediction in a form of (batch_size * num_classes)
  160. prediction = model(imgs)
  161. ## Append all real labels into a list to be able to calculate training accuracy
  162. train_label = train_label + labels.tolist()
  163. ## Get indices with highst probability and append it to calculate training accuracy
  164. argmax_prediction = torch.argmax(prediction, dim=1)
  165. train_prediction = train_prediction + argmax_prediction.tolist()
  166. ## Calculate loss
  167. loss = criterion(prediction, torch.reshape(labels, (-1,)))
  168. loss.backward()
  169. ## Optimizer step to update weights
  170. optimizer.step()
  171. ## Accumelate training loss
  172. running_loss += loss.item()
  173. tepoch.set_postfix(loss=loss.item())
  174. sleep(0.1)
  175. if epoch % 2 == 0 or epoch == n_epoch - 1:
  176. ## Save model
  177. torch.save(model.state_dict(), os.path.join(save_path, "epoch-" + str(epoch) + ".pth"))
  178. print('Model Saved !')
  179. # Calculate training loss
  180. train_l = running_loss / len(train_dataloader)
  181. # convert train_label and train_prediction to numpy arrays to be able to flatten them
  182. train_label = np.array(train_label)
  183. train_prediction = np.array(train_prediction)
  184. ## Convert them back to tensors to use sckit learn
  185. train_label = torch.tensor(train_label.flatten())
  186. train_prediction = torch.tensor(train_prediction.flatten())
  187. # Get training accuracy
  188. train_acc = accuracy_score(train_label, train_prediction)
  189. ## Evaluation(Validation) loop
  190. val_l, val_acc, val_recall, val_precision, conf_matrix = eval_model(model, validation_dataloader,
  191. criterion, device)
  192. # Print Evaluation
  193. print(
  194. 'epoch %d train loss: %.3f | train acc: %.3f | val loss: %.3f | val acc: %.3f | val recall: '
  195. '%.3f | val precision: %.3f '
  196. % (epoch, train_l, train_acc, val_l, val_acc, val_recall, val_precision))
  197. print(conf_matrix)
  198. def main():
  199. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  200. device = "cpu"
  201. print(device)
  202. train_csv_file = "E:/My Drive/FairFace/fairface_label_train.csv"
  203. val_csv_file = "E:/My Drive/FairFace/fairface_label_val.csv"
  204. root_path = "E:/My Drive/FairFace/fairface-img-margin025-trainval/"
  205. training_data = custom_dataset(csv_file=train_csv_file, root_dir=root_path, transform=custom_transformer((200, 200)))
  206. validation_data = custom_dataset(csv_file=val_csv_file, root_dir=root_path, transform=custom_transformer((200, 200)))
  207. train_dataloader = DataLoader(training_data, batch_size=16, shuffle=True)
  208. validation_dataloader = DataLoader(validation_data, batch_size=16, shuffle=True)
  209. model = ClassifierModel().to(device)
  210. train_model(model, device, train_dataloader, validation_dataloader, 100,"C:/Users/Ahmed Hamdi/PycharmProjects/RaceClassifier")
  211. if __name__ == '__main__':
  212. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...