forked from Gabriel-Angouillant/42_leaffliction
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
378 lines (280 loc) · 11.1 KB
/
Copy pathtrain.py
File metadata and controls
378 lines (280 loc) · 11.1 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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import csv
import os
import sys
import shutil
import pandas as pd
import numpy as np
from math import isnan, inf
import cv2
import copy
from scipy.stats import skew
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
from config import LEARNING_RATE, EPOCHS, BATCH_SIZE, PATIENCE
from Augmentation import AUGMENTS
from Network import Network
from Transformation import BatchTransformator
SAVE_DIR = "dataset"
def get_images(directory):
images = []
files = os.listdir(directory)
for file in files:
file_path = os.path.join(directory, file)
if os.path.isfile(file_path) and file_path.lower().endswith("jpg"):
img = cv2.imread(file_path)
if img is None:
raise PermissionError
images.append({"path": file, "image": img})
return images
def get_augmented_images(base_images):
augmented_images = []
for image in base_images:
image_augments = [image]
filename, ext = os.path.splitext(os.path.basename(image["path"]))
for augment_name, augment_fun in AUGMENTS.items():
image_augments.append(
{"path": f"{filename}_{augment_name}{ext}",
"image": augment_fun(image=image["image"])["image"]})
augmented_images.extend(image_augments)
return augmented_images
def get_transformations(base_images):
print("\n⏳ Transforming...")
bt = BatchTransformator()
imgs = [img["image"] for img in base_images]
paths = [img["path"] for img in base_images]
bt.import_images(imgs, paths)
bt.apply_transformations()
return bt
def get_histogram_features(t):
labels = ["red", "green", "blue", "saturation", "value",
"lightness", "green-magenta", "blue-yellow"]
methods = [("skew", lambda x: skew(x)),
("p1", lambda x: np.percentile(x, 50)),
("p2", lambda x: np.percentile(x, 75)),
("p3", lambda x: np.percentile(x, 90)),
("std", np.std)]
features = {
f"{label}_{method_name}":
method(t.hist_data[f"{label}_frequencies"]["value"])
for method_name, method in methods for label in labels
}
features["hue_circular_std"] = t.hist_data["hue_circular_std"]["value"]
features["hue_median"] = t.hist_data["hue_median"]["value"]
features["hue_circular_mean"] = t.hist_data["hue_circular_mean"]["value"]
return features
def get_analyze_features(t):
features = t.analyze_data
return features
def add_features(features, new_features):
for key, value in new_features.items():
if isinstance(features.get(key), list):
features[key].append(value)
else:
features[key] = [value]
def calculate_features(bt, label):
features = {"group": []}
for t in bt.transformations:
features["group"].append(label)
add_features(features, get_histogram_features(t))
add_features(features, get_analyze_features(t))
return features
def save_dataset(images):
try:
os.mkdir(SAVE_DIR)
except FileExistsError:
pass
print("➡️ Saving dataset...")
for key, bt in images.items():
print(f"\n⏳ Saving {key}")
bt.save_images(f"{SAVE_DIR}/{key}")
shutil.make_archive(SAVE_DIR, "zip", SAVE_DIR)
def prepare_dataset(directory):
features = {}
try:
dir_files = os.listdir(directory)
for file_path in dir_files:
path = os.path.join(directory, file_path)
if os.path.isdir(path):
print(f"➡️ Now processing {file_path}")
print("➡️ Reading images...")
images = get_images(path)
print("➡️ Augmenting images...")
augmented_images = get_augmented_images(images)
print("➡️ Transforming images...")
bt = get_transformations(augmented_images)
print("➡️ Calculating features...\n")
bt_features = calculate_features(bt, file_path)
for key, value in bt_features.items():
if key not in features:
features[key] = value
else:
features[key].extend(value)
except NotADirectoryError:
return print("❌ Error: not a directory.")
except FileNotFoundError:
return print("❌ Error: directory could not be found.")
except PermissionError:
return print("❌ Error: permission denied on directory")
if "group" not in features:
return print("❌ Error: no features")
min_maxes = {}
xmins = {}
for key, array in features.items():
if key == "group":
continue
np_arr = np.array(array)
nan_mask = np.isnan(np_arr)
if nan_mask.any():
median_val = np.nanmedian(np_arr)
np_arr[nan_mask] = median_val if not isnan(median_val) else 0.0
xmin = np_arr.min()
xmax = np_arr.max()
min_max = xmax - xmin
features[key] = (np_arr - xmin) / min_max if min_max != 0\
else np_arr - xmin
min_maxes[key] = min_max
xmins[key] = xmin
with open("normalization.csv", "w") as f:
writer = csv.DictWriter(f, fieldnames=min_maxes.keys())
writer.writeheader()
writer.writerows([min_maxes, xmins])
with open("dataset.csv", "w") as f:
rows = np.array([{f: features[f][i] for f in features.keys()}
for i, _ in enumerate(features["group"])])
np.random.shuffle(rows)
writer = csv.DictWriter(f, fieldnames=features.keys())
writer.writeheader()
writer.writerows(rows)
return features
def prepare_dataset_csv(directory):
df_train = pd.read_csv("train.csv")
df_val = pd.read_csv("validation.csv")
y_train = df_train["group"].values
X_train = df_train.drop(columns=["group"]).values
y_val = df_val["group"].values
X_val = df_val.drop(columns=["group"]).values
X_train = torch.tensor(X_train, dtype=torch.float32)
y_train = torch.tensor(y_train, dtype=torch.long)
X_val = torch.tensor(X_val, dtype=torch.float32)
y_val = torch.tensor(y_val, dtype=torch.long)
train_dataset = TensorDataset(X_train, y_train)
val_dataset = TensorDataset(X_val, y_val)
input_size = X_train.shape[1]
num_classes = len(torch.unique(y_train))
model = Network(input_size, num_classes)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
val_loader = DataLoader(val_dataset, shuffle=True, batch_size=BATCH_SIZE)
epoch_count = EPOCHS
best_val_loss = inf
curr_patience = 0
for epoch in range(epoch_count): # Training for 100 epochs
running_loss = 0.0 # Track total loss for each epoch
val_running_loss = 0.0
# Loop over training batches
for inputs, labels in loader:
optimizer.zero_grad() # Clear previous gradients
outputs = model(inputs) # Forward pass
loss = criterion(outputs, labels) # Compute loss
loss.backward() # Backpropagation
optimizer.step() # Update weights
running_loss += loss.item() # Accumulate loss
model.eval()
with torch.no_grad():
for val_inputs, val_labels in val_loader:
val_outputs = model(val_inputs)
val_loss = criterion(val_outputs, val_labels)
val_running_loss += val_loss.item()
model.train()
# Log loss for the current epoch
avg_loss = running_loss / len(loader)
avg_val_loss = val_running_loss / len(val_loader)
print(f"Epoch [{epoch + 1}/{epoch_count}], Loss: {avg_loss:.4f}, "
+ f"Val loss: {avg_val_loss:.4f}, Best: {best_val_loss:.4f}")
avg_val_loss = round(avg_val_loss, 4)
if best_val_loss > avg_val_loss:
best_val_loss = avg_val_loss
best_model = copy.deepcopy(model.state_dict())
curr_patience = 0
else:
curr_patience += 1
if curr_patience > PATIENCE:
break
torch.save(best_model, "model")
return
def train(features):
_, arr = np.unique(features["group"], return_counts=True)
f_count = len(arr)
model = Network(len(features.keys()) - 1, f_count)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
groups = features["group"]
del features["group"]
unique, encoded = np.unique(groups, return_inverse=True)
groups = encoded
X = np.column_stack(list(features.values()))
X = torch.tensor(X, dtype=torch.float32)
y = torch.tensor(groups)
dataset = TensorDataset(X, y)
train, validation = torch.utils.data.random_split(dataset, [0.7, 0.3])
X_val = torch.stack([validation[i][0] for i in range(len(validation))])
y_val = torch.tensor([validation[i][1] for i in range(len(validation))])
df = pd.DataFrame(X_val.numpy())
df["group"] = y_val.numpy()
X_train = torch.stack([train[i][0] for i in range(len(train))])
y_train = torch.tensor([train[i][1] for i in range(len(train))])
df_train = pd.DataFrame(X_train.numpy())
df_train["group"] = y_train.numpy()
df.to_csv("validation.csv", index=False)
df_train.to_csv("train.csv", index=False)
loader = DataLoader(train, shuffle=True, batch_size=BATCH_SIZE)
val_loader = DataLoader(validation, shuffle=True, batch_size=BATCH_SIZE)
epoch_count = EPOCHS
best_val_loss = inf
curr_patience = 0
for epoch in range(epoch_count):
running_loss = 0.0
val_running_loss = 0.0
for inputs, labels in loader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
model.eval()
with torch.no_grad():
for val_inputs, val_labels in val_loader:
val_outputs = model(val_inputs)
val_loss = criterion(val_outputs, val_labels)
val_running_loss += val_loss.item()
model.train()
avg_loss = running_loss / len(loader)
avg_val_loss = val_running_loss / len(val_loader)
print(f"Epoch [{epoch + 1}/{epoch_count}], Loss: {avg_loss:.4f}, "
f"Val loss: {avg_val_loss:.4f}")
avg_val_loss = round(avg_val_loss, 4)
if best_val_loss > avg_val_loss:
best_val_loss = avg_val_loss
curr_patience = 0
else:
curr_patience += 1
if curr_patience > PATIENCE:
break
torch.save(model.state_dict(), "model")
return
def main():
if len(sys.argv) != 2:
return print("usage: train.py <directory>")
directory = sys.argv[1]
features = prepare_dataset(directory)
# features = prepare_dataset_csv(directory)
if features is None:
return
train(features)
return
if __name__ == '__main__':
main()