File size: 21,594 Bytes
91da6cc |
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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 |
# general
import json
import os
# ML
import numpy as np
import pandas as pd
import torch
# visual
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix
from tqdm import tqdm
from src.running_params import DEBUG_MODE
from src.utiles_data import Nikud, create_missing_folders
CLASSES_LIST = ["nikud", "dagesh", "sin"]
def calc_num_correct_words(input, letter_correct_mask):
SPACE_TOKEN = 104
START_SENTENCE_TOKEN = 1
END_SENTENCE_TOKEN = 2
correct_words_count = 0
words_count = 0
for index in range(input.shape[0]):
input[index][np.where(input[index] == SPACE_TOKEN)[0]] = 0
input[index][np.where(input[index] == START_SENTENCE_TOKEN)[0]] = 0
input[index][np.where(input[index] == END_SENTENCE_TOKEN)[0]] = 0
words_end_index = np.concatenate(
(np.array([-1]), np.where(input[index] == 0)[0])
)
is_correct_words_array = [
bool(
letter_correct_mask[index][
list(range((words_end_index[s] + 1), words_end_index[s + 1]))
].all()
)
for s in range(len(words_end_index) - 1)
if words_end_index[s + 1] - (words_end_index[s] + 1) > 1
]
correct_words_count += np.array(is_correct_words_array).sum()
words_count += len(is_correct_words_array)
return correct_words_count, words_count
def predict(model, data_loader, device="cpu"):
model.to(device)
all_labels = None
with torch.no_grad():
for index_data, data in enumerate(data_loader):
(inputs, attention_mask, labels_demo) = data
inputs = inputs.to(device)
attention_mask = attention_mask.to(device)
labels_demo = labels_demo.to(device)
mask_cant_be_nikud = np.array(labels_demo.cpu())[:, :, 0] == -1
mask_cant_be_dagesh = np.array(labels_demo.cpu())[:, :, 1] == -1
mask_cant_be_sin = np.array(labels_demo.cpu())[:, :, 2] == -1
nikud_probs, dagesh_probs, sin_probs = model(inputs, attention_mask)
pred_nikud = np.array(torch.max(nikud_probs, 2).indices.cpu()).reshape(
inputs.shape[0], inputs.shape[1], 1
)
pred_dagesh = np.array(torch.max(dagesh_probs, 2).indices.cpu()).reshape(
inputs.shape[0], inputs.shape[1], 1
)
pred_sin = np.array(torch.max(sin_probs, 2).indices.cpu()).reshape(
inputs.shape[0], inputs.shape[1], 1
)
pred_nikud[mask_cant_be_nikud] = -1
pred_dagesh[mask_cant_be_dagesh] = -1
pred_sin[mask_cant_be_sin] = -1
pred_labels = np.concatenate((pred_nikud, pred_dagesh, pred_sin), axis=2)
if all_labels is None:
all_labels = pred_labels
else:
all_labels = np.concatenate((all_labels, pred_labels), axis=0)
return all_labels
def predict_single(model, data, device="cpu"):
# model.to(device)
all_labels = None
with torch.no_grad():
(inputs, attention_mask, labels_demo) = data
inputs = inputs.to(device)
attention_mask = attention_mask.to(device)
labels_demo = labels_demo.to(device)
mask_cant_be_nikud = np.array(labels_demo.cpu())[:, :, 0] == -1
mask_cant_be_dagesh = np.array(labels_demo.cpu())[:, :, 1] == -1
mask_cant_be_sin = np.array(labels_demo.cpu())[:, :, 2] == -1
nikud_probs, dagesh_probs, sin_probs = model(inputs, attention_mask)
print("model output: ", nikud_probs, dagesh_probs, sin_probs)
pred_nikud = np.array(torch.max(nikud_probs, 2).indices.cpu()).reshape(
inputs.shape[0], inputs.shape[1], 1
)
pred_dagesh = np.array(torch.max(dagesh_probs, 2).indices.cpu()).reshape(
inputs.shape[0], inputs.shape[1], 1
)
pred_sin = np.array(torch.max(sin_probs, 2).indices.cpu()).reshape(
inputs.shape[0], inputs.shape[1], 1
)
pred_nikud[mask_cant_be_nikud] = -1
pred_dagesh[mask_cant_be_dagesh] = -1
pred_sin[mask_cant_be_sin] = -1
# print(pred_nikud, pred_dagesh, pred_sin)
pred_labels = np.concatenate((pred_nikud, pred_dagesh, pred_sin), axis=2)
print(pred_labels)
if all_labels is None:
all_labels = pred_labels
else:
all_labels = np.concatenate((all_labels, pred_labels), axis=0)
return all_labels
def training(
model,
train_loader,
dev_loader,
criterion_nikud,
criterion_dagesh,
criterion_sin,
training_params,
logger,
output_model_path,
optimizer,
device="cpu",
):
max_length = None
best_accuracy = 0.0
logger.info(f"start training with training_params: {training_params}")
model = model.to(device)
criteria = {
"nikud": criterion_nikud.to(device),
"dagesh": criterion_dagesh.to(device),
"sin": criterion_sin.to(device),
}
output_checkpoints_path = os.path.join(output_model_path, "checkpoints")
create_missing_folders(output_checkpoints_path)
train_steps_loss_values = {"nikud": [], "dagesh": [], "sin": []}
train_epochs_loss_values = {"nikud": [], "dagesh": [], "sin": []}
dev_loss_values = {"nikud": [], "dagesh": [], "sin": []}
dev_accuracy_values = {
"nikud": [],
"dagesh": [],
"sin": [],
"all_nikud_letter": [],
"all_nikud_word": [],
}
for epoch in tqdm(range(training_params["n_epochs"]), desc="Training"):
model.train()
train_loss = {"nikud": 0.0, "dagesh": 0.0, "sin": 0.0}
relevant_count = {"nikud": 0.0, "dagesh": 0.0, "sin": 0.0}
for index_data, data in enumerate(train_loader):
(inputs, attention_mask, labels) = data
if max_length is None:
max_length = labels.shape[1]
inputs = inputs.to(device)
attention_mask = attention_mask.to(device)
labels = labels.to(device)
optimizer.zero_grad()
nikud_probs, dagesh_probs, sin_probs = model(inputs, attention_mask)
for i, (probs, class_name) in enumerate(
zip([nikud_probs, dagesh_probs, sin_probs], CLASSES_LIST)
):
reshaped_tensor = (
torch.transpose(probs, 1, 2)
.contiguous()
.view(probs.shape[0], probs.shape[2], probs.shape[1])
)
loss = criteria[class_name](reshaped_tensor, labels[:, :, i]).to(device)
num_relevant = (labels[:, :, i] != -1).sum()
train_loss[class_name] += loss.item() * num_relevant
relevant_count[class_name] += num_relevant
loss.backward(retain_graph=True)
for i, class_name in enumerate(CLASSES_LIST):
train_steps_loss_values[class_name].append(
float(train_loss[class_name] / relevant_count[class_name])
)
optimizer.step()
if (index_data + 1) % 100 == 0:
msg = f"epoch: {epoch} , index_data: {index_data + 1}\n"
for i, class_name in enumerate(CLASSES_LIST):
msg += f"mean loss train {class_name}: {float(train_loss[class_name] / relevant_count[class_name])}, "
logger.debug(msg[:-2])
for i, class_name in enumerate(CLASSES_LIST):
train_epochs_loss_values[class_name].append(
float(train_loss[class_name] / relevant_count[class_name])
)
for class_name in train_loss.keys():
train_loss[class_name] /= relevant_count[class_name]
msg = f"Epoch {epoch + 1}/{training_params['n_epochs']}\n"
for i, class_name in enumerate(CLASSES_LIST):
msg += f"mean loss train {class_name}: {train_loss[class_name]}, "
logger.debug(msg[:-2])
model.eval()
dev_loss = {"nikud": 0.0, "dagesh": 0.0, "sin": 0.0}
dev_accuracy = {"nikud": 0.0, "dagesh": 0.0, "sin": 0.0}
relevant_count = {"nikud": 0.0, "dagesh": 0.0, "sin": 0.0}
correct_preds = {"nikud": 0.0, "dagesh": 0.0, "sin": 0.0}
un_masks = {"nikud": 0.0, "dagesh": 0.0, "sin": 0.0}
predictions = {"nikud": 0.0, "dagesh": 0.0, "sin": 0.0}
labels_class = {"nikud": 0.0, "dagesh": 0.0, "sin": 0.0}
all_nikud_types_correct_preds_letter = 0.0
letter_count = 0.0
correct_words_count = 0.0
word_count = 0.0
with torch.no_grad():
for index_data, data in enumerate(dev_loader):
(inputs, attention_mask, labels) = data
inputs = inputs.to(device)
attention_mask = attention_mask.to(device)
labels = labels.to(device)
nikud_probs, dagesh_probs, sin_probs = model(inputs, attention_mask)
for i, (probs, class_name) in enumerate(
zip([nikud_probs, dagesh_probs, sin_probs], CLASSES_LIST)
):
reshaped_tensor = (
torch.transpose(probs, 1, 2)
.contiguous()
.view(probs.shape[0], probs.shape[2], probs.shape[1])
)
loss = criteria[class_name](reshaped_tensor, labels[:, :, i]).to(
device
)
un_masked = labels[:, :, i] != -1
num_relevant = un_masked.sum()
relevant_count[class_name] += num_relevant
_, preds = torch.max(probs, 2)
dev_loss[class_name] += loss.item() * num_relevant
correct_preds[class_name] += torch.sum(
preds[un_masked] == labels[:, :, i][un_masked]
)
un_masks[class_name] = un_masked
predictions[class_name] = preds
labels_class[class_name] = labels[:, :, i]
un_mask_all_or = torch.logical_or(
torch.logical_or(un_masks["nikud"], un_masks["dagesh"]),
un_masks["sin"],
)
correct = {
class_name: (torch.ones(un_mask_all_or.shape) == 1).to(device)
for class_name in CLASSES_LIST
}
for i, class_name in enumerate(CLASSES_LIST):
correct[class_name][un_masks[class_name]] = (
predictions[class_name][un_masks[class_name]]
== labels_class[class_name][un_masks[class_name]]
)
letter_correct_mask = torch.logical_and(
torch.logical_and(correct["sin"], correct["dagesh"]),
correct["nikud"],
)
all_nikud_types_correct_preds_letter += torch.sum(
letter_correct_mask[un_mask_all_or]
)
letter_correct_mask[~un_mask_all_or] = True
correct_num, total_words_num = calc_num_correct_words(
inputs.cpu(), letter_correct_mask
)
word_count += total_words_num
correct_words_count += correct_num
letter_count += un_mask_all_or.sum()
for class_name in CLASSES_LIST:
dev_loss[class_name] /= relevant_count[class_name]
dev_accuracy[class_name] = float(
correct_preds[class_name].double() / relevant_count[class_name]
)
dev_loss_values[class_name].append(float(dev_loss[class_name]))
dev_accuracy_values[class_name].append(float(dev_accuracy[class_name]))
dev_all_nikud_types_accuracy_letter = float(
all_nikud_types_correct_preds_letter / letter_count
)
dev_accuracy_values["all_nikud_letter"].append(
dev_all_nikud_types_accuracy_letter
)
word_all_nikud_accuracy = correct_words_count / word_count
dev_accuracy_values["all_nikud_word"].append(word_all_nikud_accuracy)
msg = (
f"Epoch {epoch + 1}/{training_params['n_epochs']}\n"
f'mean loss Dev nikud: {train_loss["nikud"]}, '
f'mean loss Dev dagesh: {train_loss["dagesh"]}, '
f'mean loss Dev sin: {train_loss["sin"]}, '
f"Dev all nikud types letter Accuracy: {dev_all_nikud_types_accuracy_letter}, "
f'Dev nikud letter Accuracy: {dev_accuracy["nikud"]}, '
f'Dev dagesh letter Accuracy: {dev_accuracy["dagesh"]}, '
f'Dev sin letter Accuracy: {dev_accuracy["sin"]}, '
f"Dev word Accuracy: {word_all_nikud_accuracy}"
)
logger.debug(msg)
save_progress_details(
dev_accuracy_values,
train_epochs_loss_values,
dev_loss_values,
train_steps_loss_values,
)
if dev_all_nikud_types_accuracy_letter > best_accuracy:
best_accuracy = dev_all_nikud_types_accuracy_letter
best_model = {
"epoch": epoch,
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"loss": loss,
}
if epoch % training_params["checkpoints_frequency"] == 0:
save_checkpoint_path = os.path.join(
output_checkpoints_path, f"checkpoint_model_epoch_{epoch + 1}.pth"
)
checkpoint = {
"epoch": epoch,
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"loss": loss,
}
torch.save(checkpoint["model_state_dict"], save_checkpoint_path)
save_model_path = os.path.join(output_model_path, "best_model.pth")
torch.save(best_model["model_state_dict"], save_model_path)
return (
best_model,
best_accuracy,
train_epochs_loss_values,
train_steps_loss_values,
dev_loss_values,
dev_accuracy_values,
)
def save_progress_details(
accuracy_dev_values,
epochs_loss_train_values,
loss_dev_values,
steps_loss_train_values,
):
epochs_data_path = "epochs_data"
create_missing_folders(epochs_data_path)
save_dict_as_json(
steps_loss_train_values, epochs_data_path, "steps_loss_train_values.json"
)
save_dict_as_json(
epochs_loss_train_values, epochs_data_path, "epochs_loss_train_values.json"
)
save_dict_as_json(loss_dev_values, epochs_data_path, "loss_dev_values.json")
save_dict_as_json(accuracy_dev_values, epochs_data_path, "accuracy_dev_values.json")
def save_dict_as_json(dict, file_path, file_name):
json_data = json.dumps(dict, indent=4)
with open(os.path.join(file_path, file_name), "w") as json_file:
json_file.write(json_data)
def evaluate(model, test_data, plots_folder=None, device="cpu"):
model.to(device)
model.eval()
true_labels = {"nikud": [], "dagesh": [], "sin": []}
predictions = {"nikud": 0, "dagesh": 0, "sin": 0}
predicted_labels_2_report = {"nikud": [], "dagesh": [], "sin": []}
not_masks = {"nikud": 0, "dagesh": 0, "sin": 0}
correct_preds = {"nikud": 0, "dagesh": 0, "sin": 0}
relevant_count = {"nikud": 0, "dagesh": 0, "sin": 0}
labels_class = {"nikud": 0.0, "dagesh": 0.0, "sin": 0.0}
all_nikud_types_letter_level_correct = 0.0
nikud_letter_level_correct = 0.0
dagesh_letter_level_correct = 0.0
sin_letter_level_correct = 0.0
letters_count = 0.0
words_count = 0.0
correct_words_count = 0.0
with torch.no_grad():
for index_data, data in enumerate(test_data):
if DEBUG_MODE and index_data > 100:
break
(inputs, attention_mask, labels) = data
inputs = inputs.to(device)
attention_mask = attention_mask.to(device)
labels = labels.to(device)
nikud_probs, dagesh_probs, sin_probs = model(inputs, attention_mask)
for i, (probs, class_name) in enumerate(
zip([nikud_probs, dagesh_probs, sin_probs], CLASSES_LIST)
):
labels_class[class_name] = labels[:, :, i]
not_masked = labels_class[class_name] != -1
num_relevant = not_masked.sum()
relevant_count[class_name] += num_relevant
_, preds = torch.max(probs, 2)
correct_preds[class_name] += torch.sum(
preds[not_masked] == labels_class[class_name][not_masked]
)
predictions[class_name] = preds
not_masks[class_name] = not_masked
if len(true_labels[class_name]) == 0:
true_labels[class_name] = (
labels_class[class_name][not_masked].cpu().numpy()
)
else:
true_labels[class_name] = np.concatenate(
(
true_labels[class_name],
labels_class[class_name][not_masked].cpu().numpy(),
)
)
if len(predicted_labels_2_report[class_name]) == 0:
predicted_labels_2_report[class_name] = (
preds[not_masked].cpu().numpy()
)
else:
predicted_labels_2_report[class_name] = np.concatenate(
(
predicted_labels_2_report[class_name],
preds[not_masked].cpu().numpy(),
)
)
not_mask_all_or = torch.logical_or(
torch.logical_or(not_masks["nikud"], not_masks["dagesh"]),
not_masks["sin"],
)
correct_nikud = (torch.ones(not_mask_all_or.shape) == 1).to(device)
correct_dagesh = (torch.ones(not_mask_all_or.shape) == 1).to(device)
correct_sin = (torch.ones(not_mask_all_or.shape) == 1).to(device)
correct_nikud[not_masks["nikud"]] = (
predictions["nikud"][not_masks["nikud"]]
== labels_class["nikud"][not_masks["nikud"]]
)
correct_dagesh[not_masks["dagesh"]] = (
predictions["dagesh"][not_masks["dagesh"]]
== labels_class["dagesh"][not_masks["dagesh"]]
)
correct_sin[not_masks["sin"]] = (
predictions["sin"][not_masks["sin"]]
== labels_class["sin"][not_masks["sin"]]
)
letter_correct_mask = torch.logical_and(
torch.logical_and(correct_sin, correct_dagesh), correct_nikud
)
all_nikud_types_letter_level_correct += torch.sum(
letter_correct_mask[not_mask_all_or]
)
letter_correct_mask[~not_mask_all_or] = True
total_correct_count, total_words_num = calc_num_correct_words(
inputs.cpu(), letter_correct_mask
)
words_count += total_words_num
correct_words_count += total_correct_count
letters_count += not_mask_all_or.sum()
nikud_letter_level_correct += torch.sum(correct_nikud[not_mask_all_or])
dagesh_letter_level_correct += torch.sum(correct_dagesh[not_mask_all_or])
sin_letter_level_correct += torch.sum(correct_sin[not_mask_all_or])
for i, name in enumerate(CLASSES_LIST):
index_labels = np.unique(true_labels[name])
cm = confusion_matrix(
true_labels[name], predicted_labels_2_report[name], labels=index_labels
)
vowel_label = [Nikud.id_2_label[name][l] for l in index_labels]
unique_vowels_names = [
Nikud.sign_2_name[int(vowel)] for vowel in vowel_label if vowel != "WITHOUT"
]
if "WITHOUT" in vowel_label:
unique_vowels_names += ["WITHOUT"]
cm_df = pd.DataFrame(cm, index=unique_vowels_names, columns=unique_vowels_names)
# Display confusion matrix
plt.figure(figsize=(10, 8))
sns.heatmap(cm_df, annot=True, cmap="Blues", fmt="d")
plt.title("Confusion Matrix")
plt.xlabel("True Label")
plt.ylabel("Predicted Label")
if plots_folder is None:
plt.show()
else:
plt.savefig(os.path.join(plots_folder, f"Confusion_Matrix_{name}.jpg"))
all_nikud_types_letter_level_correct = (
all_nikud_types_letter_level_correct / letters_count
)
all_nikud_types_word_level_correct = correct_words_count / words_count
nikud_letter_level_correct = nikud_letter_level_correct / letters_count
dagesh_letter_level_correct = dagesh_letter_level_correct / letters_count
sin_letter_level_correct = sin_letter_level_correct / letters_count
print("\n")
print(f"nikud_letter_level_correct = {nikud_letter_level_correct}")
print(f"dagesh_letter_level_correct = {dagesh_letter_level_correct}")
print(f"sin_letter_level_correct = {sin_letter_level_correct}")
print(f"word_level_correct = {all_nikud_types_word_level_correct}")
return all_nikud_types_word_level_correct, all_nikud_types_letter_level_correct
|