File size: 46,940 Bytes
f291f4a |
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 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 |
from abc import ABC, abstractmethod
import os
import time
import gc
import json
from tqdm import tqdm
import torch
from singleVis.losses import PositionRecoverLoss
from torch.utils.data import DataLoader, WeightedRandomSampler
import copy
import numpy as np
from singleVis.custom_weighted_random_sampler import CustomWeightedRandomSampler, CustomWeightedRandomSamplerVis
from singleVis.spatial_edge_constructor import ActiveLearningEpochSpatialEdgeConstructor
from singleVis.edge_dataset import DVIDataHandler
torch.manual_seed(0) # 使用固定的种子
torch.cuda.manual_seed_all(0)
"""
1. construct a spatio-temporal complex
2. construct an edge-dataset
3. train the network
Trainer should contains
1. train_step function
2. early stop
3. ...
"""
class TrainerAbstractClass(ABC):
@abstractmethod
def __init__(self, *args, **kwargs):
pass
@property
@abstractmethod
def loss(self):
pass
@abstractmethod
def reset_optim(self):
pass
@abstractmethod
def update_edge_loader(self):
pass
@abstractmethod
def update_vis_model(self):
pass
@abstractmethod
def update_optimizer(self):
pass
@abstractmethod
def update_lr_scheduler(self):
pass
@abstractmethod
def train_step(self):
pass
@abstractmethod
def train(self):
pass
@abstractmethod
def load(self):
pass
@abstractmethod
def save(self):
pass
@abstractmethod
def record_time(self):
pass
class ActiveLearningEdgeLoader(DataLoader):
def __init__(self, dataset, weights, batch_size=32, **kwargs):
# Create a WeightedRandomSampler to select samples based on weights
sampler = WeightedRandomSampler(weights, len(dataset))
super().__init__(dataset, batch_size=batch_size, sampler=sampler, **kwargs)
class SingleVisTrainer(TrainerAbstractClass):
def __init__(self, model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE):
self.model = model
self.criterion = criterion
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
self.DEVICE = DEVICE
self.edge_loader = edge_loader
self._loss = 100.0
@property
def loss(self):
return self._loss
def reset_optim(self, optim, lr_s):
self.optimizer = optim
self.lr_scheduler = lr_s
print("Successfully reset optimizer!")
def update_edge_loader(self, edge_loader):
del self.edge_loader
gc.collect()
self.edge_loader = edge_loader
def update_vis_model(self, model):
self.model.load_state_dict(model.state_dict())
def update_optimizer(self, optimizer):
self.optimizer = optimizer
def update_lr_scheduler(self, lr_scheduler):
self.lr_scheduler = lr_scheduler
def train_step(self):
self.model.to(device=self.DEVICE)
self.model.train()
all_loss = []
umap_losses = []
recon_losses = []
t = tqdm(self.edge_loader, leave=True, total=len(self.edge_loader))
# for data in self.edge_loader:
for data in t:
edge_to, edge_from, a_to, a_from = data
edge_to = edge_to.to(device=self.DEVICE, dtype=torch.float32)
edge_from = edge_from.to(device=self.DEVICE, dtype=torch.float32)
a_to = a_to.to(device=self.DEVICE, dtype=torch.float32)
a_from = a_from.to(device=self.DEVICE, dtype=torch.float32)
outputs = self.model(edge_to, edge_from)
umap_l, recon_l, loss = self.criterion(edge_to, edge_from, a_to, a_from, outputs)
all_loss.append(loss.mean().item())
umap_losses.append(umap_l.mean().item())
recon_losses.append(recon_l.mean().item())
# ===================backward====================
self.optimizer.zero_grad()
loss.mean().backward()
self.optimizer.step()
self._loss = sum(all_loss) / len(all_loss)
self.model.eval()
print('umap:{:.4f}\trecon_l:{:.4f}\tloss:{:.4f}'.format(sum(umap_losses) / len(umap_losses),
sum(recon_losses) / len(recon_losses),
sum(all_loss) / len(all_loss)))
return self.loss
def train(self, PATIENT, MAX_EPOCH_NUMS):
patient = PATIENT
time_start = time.time()
for epoch in range(MAX_EPOCH_NUMS):
print("====================\nepoch:{}\n===================".format(epoch+1))
prev_loss = self.loss
loss = self.train_step()
self.lr_scheduler.step()
# early stop, check whether converge or not
if prev_loss - loss < 5E-3:
if patient == 0:
break
else:
patient -= 1
else:
patient = PATIENT
time_end = time.time()
time_spend = time_end - time_start
print("Time spend: {:.2f} for training vis model...".format(time_spend))
def load(self, file_path):
"""
save all parameters...
:param name:
:return:
"""
save_model = torch.load(file_path, map_location="cpu")
self._loss = save_model["loss"]
self.model.load_state_dict(save_model["state_dict"])
self.model.to(self.DEVICE)
print("Successfully load visualization model...")
def save(self, save_dir, file_name):
"""
save all parameters...
:param name:
:return:
"""
save_model = {
"loss": self.loss,
"state_dict": self.model.state_dict(),
"optimizer": self.optimizer.state_dict()}
save_path = os.path.join(save_dir, file_name + '.pth')
torch.save(save_model, save_path)
print("Successfully save visualization model...")
def record_time(self, save_dir, file_name, key, t):
# save result
save_file = os.path.join(save_dir, file_name+".json")
if not os.path.exists(save_file):
evaluation = dict()
else:
f = open(save_file, "r")
evaluation = json.load(f)
f.close()
evaluation[key] = round(t, 3)
with open(save_file, 'w') as f:
json.dump(evaluation, f)
class HybridVisTrainer(SingleVisTrainer):
def __init__(self, model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE):
super().__init__(model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE)
def train_step(self):
self.model = self.model.to(device=self.DEVICE)
self.model.train()
all_loss = []
umap_losses = []
recon_losses = []
smooth_losses = []
t = tqdm(self.edge_loader, leave=True, total=len(self.edge_loader))
for data in t:
edge_to, edge_from, a_to, a_from, embedded_to, coeffi_to = data
edge_to = edge_to.to(device=self.DEVICE, dtype=torch.float32)
edge_from = edge_from.to(device=self.DEVICE, dtype=torch.float32)
a_to = a_to.to(device=self.DEVICE, dtype=torch.float32)
a_from = a_from.to(device=self.DEVICE, dtype=torch.float32)
embedded_to = embedded_to.to(device=self.DEVICE, dtype=torch.float32)
coeffi_to = coeffi_to.to(device=self.DEVICE, dtype=torch.float32)
outputs = self.model(edge_to, edge_from)
umap_l, recon_l, smooth_l, loss = self.criterion(edge_to, edge_from, a_to, a_from, embedded_to, coeffi_to, outputs)
all_loss.append(loss.item())
umap_losses.append(umap_l.item())
recon_losses.append(recon_l.item())
smooth_losses.append(smooth_l.item())
# ===================backward====================
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
self._loss = sum(all_loss) / len(all_loss)
self.model.eval()
print('umap:{:.4f}\trecon_l:{:.4f}\tsmooth_l:{:.4f}\tloss:{:.4f}'.format(sum(umap_losses) / len(umap_losses),
sum(recon_losses) / len(recon_losses),
sum(smooth_losses) / len(smooth_losses),
sum(all_loss) / len(all_loss)))
return self.loss
def record_time(self, save_dir, file_name, operation, seg, t):
# save result
save_file = os.path.join(save_dir, file_name+".json")
if not os.path.exists(save_file):
evaluation = dict()
else:
f = open(save_file, "r")
evaluation = json.load(f)
f.close()
if operation not in evaluation.keys():
evaluation[operation] = dict()
evaluation[operation][str(seg)] = round(t, 3)
with open(save_file, 'w') as f:
json.dump(evaluation, f)
def disable_grad(model):
for param in model.parameters():
param.requires_grad = False
# retrain with full data every RE_TRAINING_INTERVAL epochs
RE_TRAINING_INTERVAL = 10
class ActiveLearningTrainer(SingleVisTrainer):
def __init__(self, model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE):
self.model = model
self.model = self.model.to(device=DEVICE)
self.criterion = criterion
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
self.DEVICE = DEVICE
self.edge_loader = edge_loader
self._loss = 100.0
class DVIALTrainer(SingleVisTrainer):
def __init__(self, model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE):
super().__init__(model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE)
self.is_first_active_learning = True # Add this line
def evaluate_loss(self):
print("evluating")
# This method calculates the loss of each sample in the dataset.
# It returns a list of losses and updates the edge loader with the inverse of these losses as weights.
losses = []
# Ensure the model is in evaluation mode
self.model.eval()
with torch.no_grad():
for data in self.edge_loader:
edge_to, edge_from, a_to, a_from = data
edge_to = edge_to.to(device=self.DEVICE, dtype=torch.float32)
edge_from = edge_from.to(device=self.DEVICE, dtype=torch.float32)
a_to = a_to.to(device=self.DEVICE, dtype=torch.float32)
a_from = a_from.to(device=self.DEVICE, dtype=torch.float32)
outputs = self.model(edge_to, edge_from)
_, _,_, loss = self.criterion(edge_to, edge_from, a_to, a_from, self.model, outputs)
losses.append(loss.item())
# We use the inverse of the loss as the weight, so the samples with higher loss will have higher chance to be selected.
weights = 1.0 / torch.tensor(losses, dtype=torch.float32)
# Normalize the weights so they sum to 1
weights = weights / weights.sum()
# Update the edge loader
new_loader = ActiveLearningEdgeLoader(self.edge_loader.dataset, weights, batch_size=self.edge_loader.batch_size)
return losses,new_loader
def train_step(self, edge_loader ):
self.model = self.model.to(device=self.DEVICE)
self.model.train()
all_loss = []
umap_losses = []
recon_losses = []
temporal_losses = []
t = tqdm(edge_loader, leave=True, total=len(edge_loader))
for data in t:
edge_to, edge_from, a_to, a_from = data
edge_to = edge_to.to(device=self.DEVICE, dtype=torch.float32)
edge_from = edge_from.to(device=self.DEVICE, dtype=torch.float32)
a_to = a_to.to(device=self.DEVICE, dtype=torch.float32)
a_from = a_from.to(device=self.DEVICE, dtype=torch.float32)
outputs = self.model(edge_to, edge_from)
umap_l, recon_l, temporal_l, loss = self.criterion(edge_to, edge_from, a_to, a_from, self.model, outputs)
all_loss.append(loss.mean().item())
umap_losses.append(umap_l.item())
recon_losses.append(recon_l.item())
temporal_losses.append(temporal_l.mean().item())
# ===================backward====================
self.optimizer.zero_grad()
loss.mean().backward()
self.optimizer.step()
self._loss = sum(all_loss) / len(all_loss)
self.model.eval()
print('umap:{:.4f}\trecon_l:{:.4f}\ttemporal_l:{:.4f}\tloss:{:.4f}'.format(sum(umap_losses) / len(umap_losses),
sum(recon_losses) / len(recon_losses),
sum(temporal_losses) / len(temporal_losses),
sum(all_loss) / len(all_loss)))
return self.loss
def run_epoch(self, epoch, is_active_learning=False, is_full_data=False):
print("====================\nepoch:{}\n===================".format(epoch+1))
start_time = time.time()
if is_active_learning and is_full_data == False:
_, current_loader = self.evaluate_loss()
# Adjust learning rate for active learning
if self.is_first_active_learning:
print("change learning rate")
for param_group in self.optimizer.param_groups:
param_group['lr'] *= 0.1 # or set to any value you want
self.is_first_active_learning = False
prev_loss = self.loss
if is_full_data:
print("full data")
loss = self.train_step(self.edge_loader) # use DVITrainer's train_step
else:
loss = self.train_step(current_loader) # use DVITrainer's train_step
self.lr_scheduler.step()
elapsed_time = time.time() - start_time
print("Epoch completed in: {:.2f} seconds".format(elapsed_time))
return prev_loss, loss
def train(self, PATIENT, MAX_EPOCH_NUMS):
print("ininin in dvi")
patient = PATIENT
time_start = time.time()
# Pretraining
for epoch in range(10):
print("Pretraining")
_, _ = self.run_epoch(epoch, is_active_learning=False,is_full_data=True )
for epoch in range(MAX_EPOCH_NUMS):
print("In active learning")
# is_full_data = (epoch % 3 == 0) # retrain with full data every RE_TRAINING_INTERVAL epochs
prev_loss, loss = self.run_epoch(epoch, is_active_learning=True, is_full_data=False)
# Early stop, check whether converge or not
if abs(prev_loss - loss) < 5E-3:
if patient == 0:
break
else:
patient -= 1
else:
patient = PATIENT
time_end = time.time()
time_spend = time_end - time_start
print("Time spend: {:.2f} for training vis model...".format(time_spend))
def record_time(self, save_dir, file_name, operation, iteration, t):
# save result
save_file = os.path.join(save_dir, file_name+".json")
if not os.path.exists(save_file):
evaluation = dict()
else:
f = open(save_file, "r")
evaluation = json.load(f)
f.close()
if operation not in evaluation.keys():
evaluation[operation] = dict()
evaluation[operation][iteration] = round(t, 3)
with open(save_file, 'w') as f:
json.dump(evaluation, f)
class DVITrainer(SingleVisTrainer):
def __init__(self, model, criterion, optimizer, lr_scheduler, edge_loader,DEVICE):
super().__init__(model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE)
def train_step(self):
self.model = self.model.to(device=self.DEVICE)
self.model.train()
all_loss = []
umap_losses = []
recon_losses = []
temporal_losses = []
t = tqdm(self.edge_loader, leave=True, total=len(self.edge_loader))
for data in t:
edge_to, edge_from, a_to, a_from = data
edge_to = edge_to.to(device=self.DEVICE, dtype=torch.float32)
edge_from = edge_from.to(device=self.DEVICE, dtype=torch.float32)
a_to = a_to.to(device=self.DEVICE, dtype=torch.float32)
a_from = a_from.to(device=self.DEVICE, dtype=torch.float32)
outputs = self.model(edge_to, edge_from)
umap_l, recon_l, temporal_l, loss = self.criterion(edge_to, edge_from, a_to, a_from, self.model, outputs)
loss_new = loss
# + 1 * radius_loss + orthogonal_loss
# + distance_order_loss
all_loss.append(loss.mean().item())
umap_losses.append(umap_l.mean().item())
recon_losses.append(recon_l.mean().item())
temporal_losses.append(temporal_l.mean().item())
# ===================backward====================
self.optimizer.zero_grad()
loss_new.mean().backward()
self.optimizer.step()
self._loss = sum(all_loss) / len(all_loss)
self.model.eval()
print('umap:{:.4f}\trecon_l:{:.4f}\ttemporal_l:{:.4f}\tloss:{:.4f}'.format(sum(umap_losses) / len(umap_losses),
sum(recon_losses) / len(recon_losses),
sum(temporal_losses) / len(temporal_losses),
sum(all_loss) / len(all_loss)))
return self.loss
# def radius_loss(self,embeddings, center, alpha=1.0):
# """
# Radius loss function.
# Args:
# embeddings: the 2D embeddings, tensor of shape (N, 2)
# center: the center of the circle in the 2D space, tensor of shape (2,)
# alpha: a coefficient for the radius loss, controlling its importance.
# Returns:
# A scalar tensor representing the radius loss.
# """
# radii = torch.norm(embeddings - center, dim=1)
# normalized_radii = torch.nn.functional.normalize(radii, dim=0, p=2)
# normalized_mean_radii = torch.mean(normalized_radii)
# return alpha * normalized_mean_radii
def radius_loss(self, embeddings, center, alpha=1.0):
"""
Modified radius loss function that tries to maximize the average distance.
Args:
embeddings: the 2D embeddings, tensor of shape (N, 2)
center: the center of the circle in the 2D space, tensor of shape (2,)
alpha: a coefficient for the radius loss, controlling its importance.
Returns:
A scalar tensor representing the radius loss.
"""
radii = torch.norm(embeddings - center, dim=1)
normalized_radii = torch.nn.functional.normalize(radii, dim=0, p=2)
normalized_mean_radii = torch.mean(normalized_radii)
return -alpha * normalized_mean_radii
def orthogonal_loss(self, embeddings, beta=0.001):
"""
Orthogonal loss function that tries to decorrelate the embeddings.
Args:
embeddings: the 2D embeddings, tensor of shape (N, 2)
beta: a coefficient for the orthogonal loss, controlling its importance.
Returns:
A scalar tensor representing the orthogonal loss.
"""
gram_matrix = torch.mm(embeddings, embeddings.t())
identity = torch.eye(embeddings.shape[0]).to(embeddings.device)
loss = torch.norm(gram_matrix - identity)
return beta * loss
def distance_order_loss(self,high_embeddings, low_embeddings, high_center, low_center, beta=0.001):
"""
Distance order preserving loss function.
Args:
high_embeddings: the high-dimensional embeddings, tensor of shape (N, D)
low_embeddings: the 2D embeddings, tensor of shape (N, 2)
high_center: the center of the sphere in the high-dimensional space, tensor of shape (D,)
low_center: the center of the circle in the 2D space, tensor of shape (2,)
beta: a coefficient for the distance order loss, controlling its importance.
Returns:
A scalar tensor representing the distance order loss.
"""
high_distances = torch.norm(high_embeddings - high_center, dim=1)
low_distances = torch.norm(low_embeddings - low_center, dim=1)
high_order = torch.argsort(high_distances)
low_order = torch.argsort(low_distances)
high_order = high_order.float()
low_order = low_order.float()
# loss = torch.norm(high_order - low_order)
loss = torch.norm(high_order - low_order) / high_order.shape[0]
# loss = torch.sigmoid(torch.norm(high_order - low_order) / high_order.shape[0])
return beta * loss
def record_time(self, save_dir, file_name, operation, iteration, t):
# save result
save_file = os.path.join(save_dir, file_name+".json")
if not os.path.exists(save_file):
evaluation = dict()
else:
f = open(save_file, "r")
evaluation = json.load(f)
f.close()
if operation not in evaluation.keys():
evaluation[operation] = dict()
evaluation[operation][iteration] = round(t, 3)
with open(save_file, 'w') as f:
json.dump(evaluation, f)
class DVIActiveLearningTrainer(SingleVisTrainer):
def __init__(self, model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE):
super().__init__(model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE)
def train_step(self):
self.model = self.model.to(device=self.DEVICE)
self.model.train()
all_loss = []
umap_losses = []
recon_losses = []
temporal_losses = []
t = tqdm(self.edge_loader, leave=True, total=len(self.edge_loader))
for data in t:
edge_to, edge_from, a_to, a_from = data
edge_to = edge_to.to(device=self.DEVICE, dtype=torch.float32)
edge_from = edge_from.to(device=self.DEVICE, dtype=torch.float32)
a_to = a_to.to(device=self.DEVICE, dtype=torch.float32)
a_from = a_from.to(device=self.DEVICE, dtype=torch.float32)
outputs = self.model(edge_to, edge_from)
umap_l, recon_l, temporal_l, loss = self.criterion(edge_to, edge_from, a_to, a_from, self.model, outputs)
all_loss.append(loss.mean().item())
umap_losses.append(umap_l.mean().item())
recon_losses.append(recon_l.mean().item())
temporal_losses.append(temporal_l.mean().item())
# ===================backward====================
self.optimizer.zero_grad()
loss.mean().backward()
self.optimizer.step()
self._loss = sum(all_loss) / len(all_loss)
self.model.eval()
print('umap:{:.4f}\trecon_l:{:.4f}\ttemporal_l:{:.4f}\tloss:{:.4f}'.format(sum(umap_losses) / len(umap_losses),
sum(recon_losses) / len(recon_losses),
sum(temporal_losses) / len(temporal_losses),
sum(all_loss) / len(all_loss)))
return self.loss
def record_time(self, save_dir, file_name, operation, iteration, t):
# save result
save_file = os.path.join(save_dir, file_name+".json")
if not os.path.exists(save_file):
evaluation = dict()
else:
f = open(save_file, "r")
evaluation = json.load(f)
f.close()
if operation not in evaluation.keys():
evaluation[operation] = dict()
evaluation[operation][iteration] = round(t, 3)
with open(save_file, 'w') as f:
json.dump(evaluation, f)
class TVITrainer(SingleVisTrainer):
def __init__(self, model, criterion, optimizer, lr_scheduler, edge_loader, adv_edge_loader, DEVICE):
super().__init__(model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE)
self.adv_edge_loader = adv_edge_loader # adversarial data loader
def disable_grad(self, model):
for param in model.parameters():
param.requires_grad = False
def enable_grad(self, model):
for param in model.parameters():
param.requires_grad = True
def train_step(self):
self.model = self.model.to(device=self.DEVICE)
self.model.train()
all_loss = []
umap_losses = []
recon_losses = []
temporal_losses = []
t = tqdm(self.edge_loader, leave=True, total=len(self.edge_loader))
self.enable_grad(self.model.encoder)# Freeze encoder parameters
print("enable")
for data in t:
edge_to, edge_from, a_to, a_from = data
edge_to = edge_to.to(device=self.DEVICE, dtype=torch.float32)
edge_from = edge_from.to(device=self.DEVICE, dtype=torch.float32)
a_to = a_to.to(device=self.DEVICE, dtype=torch.float32)
a_from = a_from.to(device=self.DEVICE, dtype=torch.float32)
outputs = self.model(edge_to, edge_from)
umap_l, recon_l, temporal_l, loss = self.criterion(edge_to, edge_from, a_to, a_from, self.model, outputs)
all_loss.append(loss.mean().item())
umap_losses.append(umap_l.item())
recon_losses.append(recon_l.item())
temporal_losses.append(temporal_l.mean().item())
self.optimizer.zero_grad()
loss.mean().backward()
self.optimizer.step()
# Use adversarial data for decoder
# for param in self.model.encoder.parameters():
# param.requires_grad = False # Freeze encoder parameters
# for param in self.model.decoder.parameters():
# param.requires_grad = True # Unfreeze decoder parameters
adv_t = tqdm(self.adv_edge_loader, leave=True, total=len(self.adv_edge_loader))
# adv_t = iter(self.adv_edge_loader)
self.disable_grad(self.model.encoder)# Freeze encoder parameters
print("disable")
for adv_data in adv_t:
adv_edge_to, adv_edge_from, adv_a_to, adv_a_from = adv_data
adv_edge_to = adv_edge_to.to(device=self.DEVICE, dtype=torch.float32)
adv_edge_from = adv_edge_from.to(device=self.DEVICE, dtype=torch.float32)
adv_a_to = adv_a_to.to(device=self.DEVICE, dtype=torch.float32)
adv_a_from = adv_a_from.to(device=self.DEVICE, dtype=torch.float32)
adv_outputs = self.model(adv_edge_to, adv_edge_from)
adv_umap_l, adv_recon_l, adv_temporal_l, adv_loss = self.criterion(adv_edge_to, adv_edge_from, adv_a_to, adv_a_from, self.model, adv_outputs)
# Only update decoder
self.optimizer.zero_grad()
adv_loss.mean().backward()
self.optimizer.step()
self._loss = sum(all_loss) / len(all_loss)
self.model.eval()
print('umap:{:.4f}\trecon_l:{:.4f}\ttemporal_l:{:.4f}\tloss:{:.4f}'.format(sum(umap_losses) / len(umap_losses),
sum(recon_losses) / len(recon_losses),
sum(temporal_losses) / len(temporal_losses),
sum(all_loss) / len(all_loss)))
return self._loss
def record_time(self, save_dir, file_name, operation, iteration, t):
# save result
save_file = os.path.join(save_dir, file_name+".json")
if not os.path.exists(save_file):
evaluation = dict()
else:
f = open(save_file, "r")
evaluation = json.load(f)
f.close()
if operation not in evaluation.keys():
evaluation[operation] = dict()
evaluation[operation][iteration] = round(t, 3)
with open(save_file, 'w') as f:
json.dump(evaluation, f)
class DVIReFineTrainer(SingleVisTrainer):
def __init__(self, model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE,data, disable_encoder_grad=False, **kwargs):
super().__init__(model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE, **kwargs)
self.disable_encoder_grad = disable_encoder_grad
self.data = data
def train(self, PATIENT, MAX_EPOCH_NUMS):
patient = PATIENT
print("patient",patient)
time_start = time.time()
for epoch in range(MAX_EPOCH_NUMS):
print("====================\nepoch:{}\n===================".format(epoch+1))
prev_loss = self.loss
loss = self.train_step()
self.lr_scheduler.step()
# early stop, check whether converge or not
if prev_loss - loss < 5E-3:
if patient == 0:
break
else:
patient -= 1
else:
patient = PATIENT
time_end = time.time()
time_spend = time_end - time_start
print("Time spend: {:.2f} for training vis model...".format(time_spend))
def train_step(self):
self.model = self.model.to(device=self.DEVICE)
####### disable encoder
if self.disable_encoder_grad == True:
disable_grad(self.model.encoder)
self.model.train()
all_loss = []
umap_losses = []
recon_losses = []
temporal_losses = []
recoverposition_losses = []
# loss_fn = PositionRecoverLoss()
t = tqdm(self.edge_loader, leave=True, total=len(self.edge_loader))
for data in t:
edge_to, edge_from, a_to, a_from = data
edge_to = edge_to.to(device=self.DEVICE, dtype=torch.float32)
edge_from = edge_from.to(device=self.DEVICE, dtype=torch.float32)
a_to = a_to.to(device=self.DEVICE, dtype=torch.float32)
a_from = a_from.to(device=self.DEVICE, dtype=torch.float32)
outputs = self.model(edge_to, edge_from)
umap_l, recon_l, temporal_l, loss = self.criterion(edge_to, edge_from, a_to, a_from, self.model, outputs)
data = torch.Tensor(self.data).to(self.DEVICE)
new_emb = self.model.encoder(data).to(self.DEVICE)
grid_high = self.model.decoder(torch.Tensor(new_emb).to(self.DEVICE))
pos_recover_loss_fn = PositionRecoverLoss(self.DEVICE)
pos_loss = pos_recover_loss_fn(torch.Tensor(grid_high).to(self.DEVICE), torch.Tensor(self.data).to(self.DEVICE))
all_loss.append(loss.mean().item())
umap_losses.append(umap_l.item())
recon_losses.append(recon_l.item())
temporal_losses.append(temporal_l.mean().item())
recoverposition_losses.append(pos_loss.mean().item())
# ===================backward====================
recoverposition_loss = sum(recoverposition_losses) / len(recoverposition_losses)
loss_new = loss + 1 * recoverposition_loss
self.optimizer.zero_grad()
loss_new.mean().backward()
# pos_loss.mean().backward()
self.optimizer.step()
self._loss = sum(all_loss) / len(all_loss)
self.model.eval()
print('umap:{:.4f}\trecon_l:{:.4f}\ttemporal_l:{:.4f}\tloss:{:.4f}\tecoverposition_losses:{}'.format(sum(umap_losses) / len(umap_losses),
sum(recon_losses) / len(recon_losses),
sum(temporal_losses) / len(temporal_losses),
sum(all_loss) / len(all_loss), sum(recoverposition_losses) / len(all_loss)))
return self.loss
def record_time(self, save_dir, file_name, operation, iteration, t):
# save result
save_file = os.path.join(save_dir, file_name+".json")
if not os.path.exists(save_file):
evaluation = dict()
else:
f = open(save_file, "r")
evaluation = json.load(f)
f.close()
if operation not in evaluation.keys():
evaluation[operation] = dict()
evaluation[operation][iteration] = round(t, 3)
with open(save_file, 'w') as f:
json.dump(evaluation, f)
class OriginDVITrainer(SingleVisTrainer):
def __init__(self, model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE):
super().__init__(model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE)
def train_step(self):
self.model = self.model.to(device=self.DEVICE)
self.model.train()
all_loss = []
umap_losses = []
recon_losses = []
temporal_losses = []
t = tqdm(self.edge_loader, leave=True, total=len(self.edge_loader))
for data in t:
edge_to, edge_from, a_to, a_from = data
edge_to = edge_to.to(device=self.DEVICE, dtype=torch.float32)
edge_from = edge_from.to(device=self.DEVICE, dtype=torch.float32)
a_to = a_to.to(device=self.DEVICE, dtype=torch.float32)
a_from = a_from.to(device=self.DEVICE, dtype=torch.float32)
outputs = self.model(edge_to, edge_from)
umap_l, recon_l, temporal_l, loss = self.criterion(edge_to, edge_from, a_to, a_from, self.model, outputs)
all_loss.append(loss.mean().item())
umap_losses.append(umap_l.item())
recon_losses.append(recon_l.item())
temporal_losses.append(temporal_l.mean().item())
# ===================backward====================
self.optimizer.zero_grad()
loss.mean().backward()
self.optimizer.step()
self._loss = sum(all_loss) / len(all_loss)
self.model.eval()
print('umap:{:.4f}\trecon_l:{:.4f}\ttemporal_l:{:.4f}\tloss:{:.4f}'.format(sum(umap_losses) / len(umap_losses),
sum(recon_losses) / len(recon_losses),
sum(temporal_losses) / len(temporal_losses),
sum(all_loss) / len(all_loss)))
return self.loss
def record_time(self, save_dir, file_name, operation, iteration, t):
# save result
save_file = os.path.join(save_dir, file_name+".json")
if not os.path.exists(save_file):
evaluation = dict()
else:
f = open(save_file, "r")
evaluation = json.load(f)
f.close()
if operation not in evaluation.keys():
evaluation[operation] = dict()
evaluation[operation][iteration] = round(t, 3)
with open(save_file, 'w') as f:
json.dump(evaluation, f)
class DVIALMODITrainer(SingleVisTrainer):
def __init__(self, model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE, grid_high_mask, high_bom, high_rad, iteration, data_provider, prev_model, S_N_EPOCHS, B_N_EPOCHS, N_NEIGHBORS,vis_error_indices=None, **kwargs):
super().__init__(model, criterion, optimizer, lr_scheduler, edge_loader, DEVICE, **kwargs)
self.is_first_active_learning = True # Add this line
self.grid_high_mask = grid_high_mask
self.high_bom = high_bom
self.high_rad = high_rad
self.iteration = iteration
self.data_provider = data_provider
self.prev_model = prev_model
self.S_N_EPOCHS = S_N_EPOCHS
self.B_N_EPOCHS = B_N_EPOCHS
self.N_NEIGHBORS = N_NEIGHBORS
self.vis_error_indices = vis_error_indices
def al_loader(self):
print("evluating")
# This method calculates the loss of each sample in the dataset.
# It returns a list of losses and updates the edge loader with the inverse of these losses as weights.
losses = []
# Ensure the model is in evaluation mode
self.model.eval()
# 检查grid_high_mask的类型
if isinstance(self.grid_high_mask, torch.Tensor):
# 将Tensor转换为ndarray
self.grid_high_mask = self.grid_high_mask.cpu().detach().numpy()
grid_pred = self.data_provider.get_pred(self.iteration, self.grid_high_mask).argmax(axis=1)
self.grid_high_mask = torch.tensor(self.grid_high_mask).to(device=self.DEVICE, dtype=torch.float32)
grid_second_high_mask = self.model(self.grid_high_mask,self.grid_high_mask)['recon'][0]
grid_second_high_mask = grid_second_high_mask.cpu().detach().numpy()
grid_second_pred = self.data_provider.get_pred(self.iteration, grid_second_high_mask).argmax(axis=1)
error_indices = [i for i in range(len(grid_pred)) if grid_pred[i] != grid_second_pred[i]]
grid_high_error = [self.grid_high_mask[i] for i in error_indices]
# 获取阈值
threshold = self.high_rad[0] // 2
# 筛选出半径小于阈值的点的索引
filtered_indices = np.where(self.high_rad < threshold)
# 根据索引获取对应位置的center
filtered_centers = self.high_bom[filtered_indices]
filtered_radius = self.high_rad[filtered_indices]
cluster_points = []
uncluster_points = []
# 遍历每个点
for point in grid_high_error:
point = point.cpu().detach().numpy()
# 计算点到所有center的距离
distances = np.linalg.norm(point - filtered_centers, axis=1)
# 找到最近center的索引
closest_center_index = np.argmin(distances)
# 判断最近center的距离是否小于对应center的半径
if distances[closest_center_index] < filtered_radius[closest_center_index]:
# 满足条件的点
cluster_points.append(point)
else:
# 不满足条件的点
uncluster_points.append(point)
cluster_points = np.array(cluster_points)
uncluster_points = np.array(uncluster_points)
al_spatial_cons = ActiveLearningEpochSpatialEdgeConstructor(self.data_provider, self.iteration, self.S_N_EPOCHS, self.B_N_EPOCHS, self.N_NEIGHBORS, cluster_points, uncluster_points, self.high_bom)
al_edge_to, al_edge_from, al_probs, al_feature_vectors, al_attention = al_spatial_cons.construct()
al_probs = al_probs / (al_probs.max()+1e-3)
eliminate_zeros = al_probs>5e-2 #1e-3
al_edge_to = al_edge_to[eliminate_zeros]
al_edge_from = al_edge_from[eliminate_zeros]
al_probs = al_probs[eliminate_zeros]
dataset = DVIDataHandler(al_edge_to, al_edge_from, al_feature_vectors, al_attention)
n_samples = int(np.sum(self.S_N_EPOCHS * al_probs) // 1)
# chose sampler based on the number of dataset
if len(al_edge_to) > pow(2,24):
sampler = CustomWeightedRandomSampler(al_probs, n_samples, replacement=True)
else:
sampler = WeightedRandomSampler(al_probs, n_samples, replacement=True)
new_loader = DataLoader(dataset, batch_size=2000, sampler=sampler, num_workers=8, prefetch_factor=10)
if self.vis_error_indices:
lens_edge = len(al_edge_from)
new_edge_to = []
new_edge_from = []
new_feature = []
new_attention = []
new_probs = []
mapping = {}
for i in range(lens_edge):
if al_edge_from[i] in self.vis_error_indices or al_edge_to[i] in self.vis_error_indices:
new_edge_to.append(al_edge_to[i])
new_edge_from.append(al_edge_from[i])
new_probs.append(al_probs[i])
new_edge_from = np.array(new_edge_from)
new_edge_to = np.array(new_edge_to)
# new_feature = np.array(new_feature)
# new_attention = np.array(new_attention)
new_probs = np.array(new_probs)
dataset = DVIDataHandler(new_edge_to, new_edge_from, al_feature_vectors, al_attention)
n_samples = int(np.sum(self.S_N_EPOCHS * new_probs) // 1)
# since new probs have the same ordering as new edge to/from, so higher prob asociated with
# edges, higher chance of that index being selected, so higher chance of that edges with this index being selected
# neg_probs = 1-new_probs
if lens_edge > pow(2,24):
sampler = CustomWeightedRandomSampler(new_probs, n_samples, replacement=True)
else:
sampler = WeightedRandomSampler(new_probs, n_samples, replacement=True)
#todo change batch size
new_loader = DataLoader(dataset, batch_size=2000, sampler=sampler, num_workers=8, prefetch_factor=10)
# new_loader = ActiveLearningEdgeLoader(current_loader.dataset, weights, batch_size=current_loader.batch_size)
return losses, new_loader
def train_step(self, edge_loader):
self.model = self.model.to(device=self.DEVICE)
self.model.train()
all_loss = []
umap_losses = []
recon_losses = []
temporal_losses = []
t = tqdm(edge_loader, leave=True, total=len(edge_loader))
for data in t:
edge_to, edge_from, a_to, a_from = data
edge_to = edge_to.to(device=self.DEVICE, dtype=torch.float32)
edge_from = edge_from.to(device=self.DEVICE, dtype=torch.float32)
a_to = a_to.to(device=self.DEVICE, dtype=torch.float32)
a_from = a_from.to(device=self.DEVICE, dtype=torch.float32)
outputs = self.model(edge_to, edge_from)
umap_l, recon_l, temporal_l, loss = self.criterion(edge_to, edge_from, a_to, a_from, self.model, outputs)
all_loss.append(loss.mean().item())
umap_losses.append(umap_l.mean().item())
recon_losses.append(recon_l.mean().item())
temporal_losses.append(temporal_l.mean().item())
self.optimizer.zero_grad()
loss.mean().backward()
self.optimizer.step()
self._loss = sum(all_loss) / len(all_loss)
self.model.eval()
print('umap:{:.4f}\trecon_l:{:.4f}\ttemporal_l:{:.4f}\tloss:{:.4f}'.format(sum(umap_losses) / len(umap_losses),
sum(recon_losses) / len(recon_losses),
sum(temporal_losses) / len(temporal_losses),
sum(all_loss) / len(all_loss)))
return self.loss
def run_epoch(self, epoch, current_loader, is_active_learning=False, is_full_data=False):
print("====================\nepoch:{}\n===================".format(epoch+1))
start_time = time.time()
if is_active_learning and is_full_data == False:
_, current_loader = self.al_loader()
# Adjust learning rate for active learning
if self.is_first_active_learning:
print("change learning rate")
for param_group in self.optimizer.param_groups:
param_group['lr'] *= 0.1 # or set to any value you want
self.is_first_active_learning = False
prev_loss = self.loss
if is_full_data:
print("full data")
loss = self.train_step(self.edge_loader) # use DVITrainer's train_step
else:
loss = self.train_step(current_loader) # use DVITrainer's train_step
self.lr_scheduler.step()
elapsed_time = time.time() - start_time
print("Epoch completed in: {:.2f} seconds".format(elapsed_time))
return prev_loss, loss, current_loader
def train(self, PATIENT, MAX_EPOCH_NUMS):
start_flag = 1
if start_flag:
current_loader = self.edge_loader
start_flag = 0
print("ininin in dvi")
patient = PATIENT
time_start = time.time()
# Pretraining
# for epoch in range(10):
# print("Pretraining")
# _, _, current_loader= self.run_epoch(epoch, current_loader, is_active_learning=False,is_full_data=True)
for epoch in range(MAX_EPOCH_NUMS):
print("In active learning")
# is_full_data = (epoch % 3 == 0) # retrain with full data every RE_TRAINING_INTERVAL epochs
prev_loss, loss, current_loader = self.run_epoch(epoch, current_loader, is_active_learning=True, is_full_data=False)
# Early stop, check whether converge or not
if abs(prev_loss - loss) < 5E-3:
if patient == 0:
break
else:
patient -= 1
else:
patient = PATIENT
time_end = time.time()
time_spend = time_end - time_start
print("Time spend: {:.2f} for training vis model...".format(time_spend))
self.prev_model.load_state_dict(self.model.state_dict())
for param in self.prev_model.parameters():
param.requires_grad = False
w_prev = dict(self.prev_model.named_parameters())
def record_time(self, save_dir, file_name, operation, iteration, t):
# save result
save_file = os.path.join(save_dir, file_name+".json")
if not os.path.exists(save_file):
evaluation = dict()
else:
f = open(save_file, "r")
evaluation = json.load(f)
f.close()
if operation not in evaluation.keys():
evaluation[operation] = dict()
evaluation[operation][iteration] = round(t, 3)
with open(save_file, 'w') as f:
json.dump(evaluation, f) |