File size: 47,012 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 |
"""The DataProvider class serve as a helper module for retriving subject model data"""
from abc import ABC, abstractmethod
import os
import gc
import time
from singleVis.utils import *
from singleVis.eval.evaluate import evaluate_inv_accu
"""
DataContainder module
1. prepare data
2. estimate boundary
3. provide data
"""
class DataProviderAbstractClass(ABC):
def __init__(self, content_path, model, epoch_start, epoch_end, epoch_period):
self.mode = "abstract"
self.content_path = content_path
self.model = model
self.s = epoch_start
self.e = epoch_end
self.p = epoch_period
@property
@abstractmethod
def train_num(self):
pass
@property
@abstractmethod
def test_num(self):
pass
@abstractmethod
def _meta_data(self):
pass
@abstractmethod
def _estimate_boundary(self):
pass
def update_interval(self, epoch_s, epoch_e):
self.s = epoch_s
self.e = epoch_e
class DataProvider(DataProviderAbstractClass):
def __init__(self, content_path, model, epoch_start, epoch_end, epoch_period, device, classes, epoch_name, verbose=1):
self.content_path = content_path
self.model = model
self.s = epoch_start
self.e = epoch_end
self.p = epoch_period
self.DEVICE = device
self.classes = classes
self.verbose = verbose
self.epoch_name = epoch_name
self.model_path = os.path.join(self.content_path, "Model")
if verbose:
print("Finish initialization...")
@property
def train_num(self):
with open(os.path.join(self.content_path, "Model", "{}_{}".format(self.epoch_name, self.s), "index.json"), "r") as f:
idxs = json.load(f)
return len(idxs)
@property
def test_num(self):
testing_data_path = os.path.join(self.content_path, "Testing_data")
testing_data = torch.load(os.path.join(testing_data_path, "testing_dataset_data.pth"),
map_location="cpu")
test_num = len(testing_data)
del testing_data
gc.collect()
return test_num
def _meta_data(self):
raise NotImplementedError
def _estimate_boundary(self):
raise NotImplementedError
class NormalDataProvider(DataProvider):
def __init__(self, content_path, model, epoch_start, epoch_end, epoch_period, device, classes, epoch_name, verbose=1):
super().__init__(content_path, model, epoch_start, epoch_end, epoch_period, device, classes, epoch_name, verbose)
self.mode = "normal"
@property
def representation_dim(self):
train_data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, self.s), "train_data.npy")
try:
train_data = np.load(train_data_loc)
repr_dim = np.prod(train_data.shape[1:])
return repr_dim
except Exception as e:
return None
def _meta_data(self):
time_inference = list()
training_data_path = os.path.join(self.content_path, "Training_data")
training_data = torch.load(os.path.join(training_data_path, "training_dataset_data.pth"),
map_location="cpu")
training_data = training_data.to(self.DEVICE)
testing_data_path = os.path.join(self.content_path, "Testing_data")
testing_data = torch.load(os.path.join(testing_data_path, "testing_dataset_data.pth"),
map_location="cpu")
testing_data = testing_data.to(self.DEVICE)
for n_epoch in range(self.s, self.e + 1, self.p):
t_s = time.time()
# make it possible to choose a subset of testing data for testing
test_index_file = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, n_epoch), "test_index.json")
if os.path.exists(test_index_file):
test_index = load_labelled_data_index(test_index_file)
else:
test_index = range(len(testing_data))
testing_data = testing_data[test_index]
model_location = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, n_epoch), "subject_model.pth")
self.model.load_state_dict(torch.load(model_location, map_location=torch.device("cpu")))
self.model = self.model.to(self.DEVICE)
self.model.eval()
repr_model = self.feature_function(n_epoch)
# repr_model = torch.nn.Sequential(*(list(self.model.children())[:self.split]))
# training data clustering
data_pool_representation = batch_run(repr_model, training_data)
location = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, n_epoch), "train_data.npy")
np.save(location, data_pool_representation)
# test data
test_data_representation = batch_run(repr_model, testing_data)
location = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, n_epoch), "test_data.npy")
np.save(location, test_data_representation)
t_e = time.time()
time_inference.append(t_e-t_s)
if self.verbose > 0:
print("Finish inferencing data for Epoch {:d}...".format(n_epoch))
print(
"Average time for inferencing data: {:.4f}".format(sum(time_inference) / len(time_inference)))
# save result
save_dir = os.path.join(self.model_path, "time.json")
if not os.path.exists(save_dir):
evaluation = dict()
else:
f = open(save_dir, "r")
evaluation = json.load(f)
f.close()
evaluation["data_inference"] = round(sum(time_inference) / len(time_inference), 3)
with open(save_dir, 'w') as f:
json.dump(evaluation, f)
del training_data
del testing_data
gc.collect()
def _estimate_boundary(self, num, l_bound):
'''
Preprocessing data. This process includes find_border_points and find_border_centers
save data for later training
'''
time_borders_gen = list()
training_data_path = os.path.join(self.content_path, "Training_data")
training_data = torch.load(os.path.join(training_data_path, "training_dataset_data.pth"),
map_location="cpu")
training_data = training_data.to(self.DEVICE)
for n_epoch in range(self.s, self.e + 1, self.p):
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, n_epoch), "index.json")
index = load_labelled_data_index(index_file)
training_data = training_data[index]
# model_location = os.path.join(self.model_path, "Epoch_{:d}".format(n_epoch), "subject_model.pth")
# self.model.load_state_dict(torch.load(model_location, map_location=torch.device("cpu")))
# self.model = self.model.to(self.DEVICE)
# self.model.eval()
# repr_model = torch.nn.Sequential(*(list(self.model.children())[:self.split]))
repr_model = self.feature_function(n_epoch)
t0 = time.time()
confs = batch_run(self.model, training_data)
preds = np.argmax(confs, axis=1).squeeze()
# TODO how to choose the number of boundary points?
num_adv_eg = num
border_points, _, _ = get_border_points(model=self.model, input_x=training_data, confs=confs, predictions=preds, device=self.DEVICE, l_bound=l_bound, num_adv_eg=num_adv_eg, lambd=0.05, verbose=0)
t1 = time.time()
time_borders_gen.append(round(t1 - t0, 4))
# get gap layer data
border_points = border_points.to(self.DEVICE)
border_centers = batch_run(repr_model, border_points)
location = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, n_epoch), "border_centers.npy")
np.save(location, border_centers)
location = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, n_epoch), "ori_border_centers.npy")
np.save(location, border_points.cpu().numpy())
num_adv_eg = num
border_points, _, _ = get_border_points(model=self.model, input_x=training_data, confs=confs, predictions=preds, device=self.DEVICE, l_bound=l_bound, num_adv_eg=num_adv_eg, lambd=0.05, verbose=0)
# get gap layer data
border_points = border_points.to(self.DEVICE)
border_centers = batch_run(repr_model, border_points)
location = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, n_epoch), "test_border_centers.npy")
np.save(location, border_centers)
location = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, n_epoch), "test_ori_border_centers.npy")
np.save(location, border_points.cpu().numpy())
if self.verbose > 0:
print("Finish generating borders for Epoch {:d}...".format(n_epoch))
print(
"Average time for generate border points: {:.4f}".format(sum(time_borders_gen) / len(time_borders_gen)))
# save result
save_dir = os.path.join(self.model_path, "time.json")
if not os.path.exists(save_dir):
evaluation = dict()
else:
f = open(save_dir, "r")
evaluation = json.load(f)
f.close()
evaluation["data_B_gene"] = round(sum(time_borders_gen) / len(time_borders_gen), 3)
with open(save_dir, 'w') as f:
json.dump(evaluation, f)
def initialize(self, num, l_bound):
self._meta_data()
self._estimate_boundary(num, l_bound)
def train_representation(self, epoch):
# load train data
train_data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch), "train_data.npy")
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch), "index.json")
index = load_labelled_data_index(index_file)
try:
train_data = np.load(train_data_loc)
train_data = train_data[index]
except Exception as e:
print("no train data saved for Epoch {}".format(epoch))
train_data = None
return train_data
def train_labels(self, epoch):
# load train data
training_data_loc = os.path.join(self.content_path, "Training_data", "training_dataset_label.pth")
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch), "index.json")
index = load_labelled_data_index(index_file)
try:
training_labels = torch.load(training_data_loc, map_location="cpu")
# print(len(training_labels))
# print(len(index))
# # training_labels = training_labels[index]
training_labels = np.array(training_labels)
except Exception as e:
print("no train labels saved for Epoch {}".format(epoch))
training_labels = None
return training_labels
def test_representation(self, epoch):
data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch), "test_data.npy")
try:
test_data = np.load(data_loc)
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch), "test_index.json")
if os.path.exists(index_file):
index = load_labelled_data_index(index_file)
test_data = test_data[index]
except Exception as e:
print("no test data saved for Epoch {}".format(epoch))
test_data = None
# max_x = self.max_norm(epoch)
return test_data
def test_labels(self, epoch):
# load train data
testing_data_loc = os.path.join(self.content_path, "Testing_data", "testing_dataset_label.pth")
try:
testing_labels = torch.load(testing_data_loc).to(device="cpu")
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch), "test_index.json")
print(index_file)
if os.path.exists(index_file):
idxs = load_labelled_data_index(index_file)
# testing_labels = testing_labels[idxs]
testing_labels = torch.zeros(len(idxs))
except Exception as e:
print("no test labels saved for Epoch {}".format(epoch))
testing_labels = None
return testing_labels.cpu().numpy()
def border_representation(self, epoch):
border_centers_loc = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch),
"border_centers.npy")
try:
border_centers = np.load(border_centers_loc)
except Exception as e:
print("no border points saved for Epoch {}".format(epoch))
border_centers = np.array([])
return border_centers
def test_border_representation(self, epoch):
border_centers_loc = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch),
"test_border_centers.npy")
try:
border_centers = np.load(border_centers_loc)
except Exception as e:
print("no border points saved for Epoch {}".format(epoch))
border_centers = np.array([])
return border_centers
def max_norm(self, epoch):
train_data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch), "train_data.npy")
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch), "index.json")
index = load_labelled_data_index(index_file)
try:
train_data = np.load(train_data_loc)
train_data = train_data[index]
max_x = np.linalg.norm(train_data, axis=1).max()
except Exception as e:
print("no train data saved for Epoch {}".format(epoch))
max_x = None
return max_x
def prediction_function(self, epoch):
model_location = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch), "subject_model.pth")
self.model.load_state_dict(torch.load(model_location, map_location=torch.device("cpu")),strict=False)
self.model.to(self.DEVICE)
self.model.eval()
pred_fn = self.model.prediction
return pred_fn
def feature_function(self, epoch):
model_location = os.path.join(self.model_path, "{}_{:d}".format(self.epoch_name, epoch), "subject_model.pth")
self.model.load_state_dict(torch.load(model_location, map_location=torch.device("cpu")),strict=False)
self.model = self.model.to(self.DEVICE)
self.model.eval()
fea_fn = self.model.feature
return fea_fn
def get_pred(self, epoch, data):
'''
get the prediction score for data in epoch_id
:param data: numpy.ndarray
:param epoch_id:
:return: pred, numpy.ndarray
'''
prediction_func = self.prediction_function(epoch)
data = torch.from_numpy(data)
data = data.to(self.DEVICE)
pred = batch_run(prediction_func, data)
return pred
def training_accu(self, epoch):
data = self.train_representation(epoch)
labels = self.train_labels(epoch)
pred = self.get_pred(epoch, data).argmax(-1)
val = evaluate_inv_accu(labels, pred)
return val
def testing_accu(self, epoch):
data = self.test_representation(epoch)
labels = self.test_labels(epoch)
test_index_file = os.path.join(self.model_path, "{}_{}".format(self.epoch_name, epoch), "test_index.json")
if os.path.exists(test_index_file):
index = load_labelled_data_index(test_index_file)
labels = labels[index]
pred = self.get_pred(epoch, data).argmax(-1)
val = evaluate_inv_accu(labels, pred)
return val
def is_deltaB(self, epoch, data):
"""
check wheter input vectors are lying on delta-boundary or not
:param epoch_id:
:param data: numpy.ndarray
:return: numpy.ndarray, boolean, True stands for is_delta_boundary
"""
preds = self.get_pred(epoch, data)
border = is_B(preds)
return border
def checkpoint_path(self, epoch):
path = os.path.join(self.model_path, "{}_{}".format(self.epoch_name, epoch))
return path
class ActiveLearningDataProvider(DataProvider):
def __init__(self, content_path, model, base_epoch_start, device, classes, iteration_name="Iteration",verbose=1):
# dummy input as epoch_end and epoch_period
super().__init__(content_path, model, base_epoch_start, base_epoch_start, 1, device, classes, iteration_name, verbose)
self.mode = "al"
self.iteration_name = iteration_name
@property
def pool_num(self):
return len(self.train_labels_all())
def label_num(self, iteration):
return len(self.get_labeled_idx(iteration))
def representation_dim(self, iteration):
train_data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "train_data.npy")
try:
train_data = np.load(train_data_loc)
repr_dim = np.prod(train_data.shape[1:])
return repr_dim
except Exception as e:
return None
def get_labeled_idx(self, iteration):
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "index.json")
lb_idxs = np.array(load_labelled_data_index(index_file))
return lb_idxs
def get_unlabeled_idx(self, pool_num, lb_idx):
tot_idx = np.arange(pool_num)
# !Noted that tot need to be the first arguement
ulb_idx = np.setdiff1d(tot_idx, lb_idx)
return ulb_idx
def _meta_data(self, iteration):
training_data_path = os.path.join(self.content_path, "Training_data")
training_data = torch.load(os.path.join(training_data_path, "training_dataset_data.pth"),
map_location="cpu")
training_data = training_data.to(self.DEVICE)
testing_data_path = os.path.join(self.content_path, "Testing_data")
testing_data = torch.load(os.path.join(testing_data_path, "testing_dataset_data.pth"),
map_location="cpu")
testing_data = testing_data.to(self.DEVICE)
t_s = time.time()
repr_model = self.feature_function(iteration)
# training data clustering
data_pool_representation = batch_run(repr_model, training_data)
location = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "train_data.npy")
np.save(location, data_pool_representation)
# test data
test_data_representation = batch_run(repr_model, testing_data)
location = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "test_data.npy")
np.save(location, test_data_representation)
t_e = time.time()
if self.verbose > 0:
print("Finish inferencing data for Iteration {:d} in {:.2f} seconds...".format(iteration, t_e-t_s))
# save result
save_dir = os.path.join(self.model_path, "time_al.json")
if not os.path.exists(save_dir):
evaluation = dict()
else:
f = open(save_dir, "r")
evaluation = json.load(f)
f.close()
if "data_inference" not in evaluation.keys():
evaluation["data_inference"] = dict()
evaluation["data_inference"][str(iteration)] = round(t_e - t_s, 3)
with open(save_dir, 'w') as f:
json.dump(evaluation, f)
del training_data
del testing_data
gc.collect()
def _estimate_boundary(self, iteration, num, l_bound):
'''
Preprocessing data. This process includes find_border_points and find_border_centers
save data for later training
'''
training_data_path = os.path.join(self.content_path, "Training_data")
training_data = torch.load(os.path.join(training_data_path, "training_dataset_data.pth"),
map_location="cpu")
training_data = training_data.to(self.DEVICE)
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "index.json")
index = load_labelled_data_index(index_file)
training_data = training_data[index]
repr_model = self.feature_function(iteration)
t0 = time.time()
confs = batch_run(self.model, training_data)
preds = np.argmax(confs, axis=1).squeeze()
# TODO how to choose the number of boundary points?
num_adv_eg = num
border_points, _, _ = get_border_points(model=self.model, input_x=training_data, confs=confs, predictions=preds, device=self.DEVICE, l_bound=l_bound, num_adv_eg=num_adv_eg, lambd=0.05, verbose=0)
t1 = time.time()
# get gap layer data
border_points = border_points.to(self.DEVICE)
border_centers = batch_run(repr_model, border_points)
location = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "border_centers.npy")
np.save(location, border_centers)
location = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "ori_border_centers.npy")
np.save(location, border_points.cpu().numpy())
num_adv_eg = num
border_points, _, _ = get_border_points(model=self.model, input_x=training_data, confs=confs, predictions=preds, device=self.DEVICE, l_bound=l_bound, num_adv_eg=num_adv_eg, lambd=0.05, verbose=0)
# get gap layer data
border_points = border_points.to(self.DEVICE)
border_centers = batch_run(repr_model, border_points)
location = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "test_border_centers.npy")
np.save(location, border_centers)
location = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_nameiteration), "test_ori_border_centers.npy")
np.save(location, border_points.cpu().numpy())
if self.verbose > 0:
print("Finish generating borders for Iteration {:d} in {:.2f} seconds ...".format(iteration, t1-t0))
# save result
save_dir = os.path.join(self.model_path, "time_al.json")
if not os.path.exists(save_dir):
evaluation = dict()
else:
f = open(save_dir, "r")
evaluation = json.load(f)
f.close()
if "data_B_gene" not in evaluation.keys():
evaluation["data_B_gene"] = dict()
evaluation["data_B_gene"][str(iteration)] = round(t1-t0, 3)
with open(save_dir, 'w') as f:
json.dump(evaluation, f)
def initialize_iteration(self, iteration, num, l_bound):
self._meta_data(iteration)
self._estimate_boundary(iteration, num, l_bound)
def train_representation(self, iteration):
# load labelled train data
train_data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "train_data.npy")
try:
idxs = self.get_labeled_idx(iteration)
train_data = np.load(train_data_loc)[idxs]
except Exception as e:
print("no train data saved for Iteration {}".format(iteration))
train_data = None
return train_data
def train_labels(self, epoch):
# load train data
training_data_loc = os.path.join(self.content_path, "Training_data", "training_dataset_label.pth")
try:
idxs = self.get_labeled_idx(epoch)
training_labels = torch.load(training_data_loc, map_location="cpu")[idxs]
except Exception as e:
print("no train labels saved for Iteration {}".format(epoch))
training_labels = None
return training_labels.numpy()
def train_representation_ulb(self, iteration):
# load train data
train_data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "train_data.npy")
lb_idxs = self.get_labeled_idx(iteration)
try:
train_data = np.load(train_data_loc)
ulb_idxs = self.get_unlabeled_idx(len(train_data), lb_idxs)
train_data = train_data[ulb_idxs]
except Exception as e:
print("no train data saved for Iteration {}".format(iteration))
train_data = None
return train_data
def train_labels_ulb(self, epoch):
# load train data
training_data_loc = os.path.join(self.content_path, "Training_data", "training_dataset_label.pth")
lb_idxs = self.get_labeled_idx(epoch)
try:
training_labels = torch.load(training_data_loc, map_location="cpu")
ulb_idxs = self.get_unlabeled_idx(len(training_labels), lb_idxs)
training_labels = training_labels[ulb_idxs]
except Exception as e:
print("no train labels saved for Iteration {}".format(epoch))
training_labels = None
return training_labels.numpy()
def train_representation_all(self, iteration):
# load train data
train_data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "train_data.npy")
try:
train_data = np.load(train_data_loc)
except Exception as e:
print("no train data saved for Iteration {}".format(iteration))
train_data = None
return train_data
def train_labels_all(self):
# load train data
training_data_loc = os.path.join(self.content_path, "Training_data", "training_dataset_label.pth")
try:
training_labels = torch.load(training_data_loc, map_location="cpu")
except Exception as e:
print("no train labels saved")
training_labels = None
return training_labels.numpy()
def test_representation(self, epoch):
data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, epoch), "test_data.npy")
try:
test_data = np.load(data_loc)
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, epoch), "test_index.json")
if os.path.exists(index_file):
index = load_labelled_data_index(index_file)
test_data = test_data[index]
except Exception as e:
print("no test data saved for Iteration {}".format(epoch))
test_data = None
# max_x = self.max_norm(epoch)
return test_data
def test_labels(self, epoch):
# load train data
testing_data_loc = os.path.join(self.content_path, "Testing_data", "testing_dataset_label.pth")
try:
testing_labels = torch.load(testing_data_loc, map_location="cpu").numpy()
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, epoch), "test_index.json")
if os.path.exists(index_file):
idxs = load_labelled_data_index(index_file)
testing_labels = testing_labels[idxs]
except Exception as e:
print("no test labels saved for Iteration {}".format(epoch))
testing_labels = None
return testing_labels
def border_representation(self, epoch):
border_centers_loc = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, epoch),
"border_centers.npy")
try:
border_centers = np.load(border_centers_loc)
except Exception as e:
print("no border points saved for Iteration {}".format(epoch))
border_centers = np.array([])
return border_centers
def test_border_representation(self, epoch):
border_centers_loc = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, epoch),
"test_border_centers.npy")
try:
border_centers = np.load(border_centers_loc)
except Exception as e:
print("no border points saved for Epoch {}".format(epoch))
border_centers = np.array([])
return border_centers
def max_norm(self, epoch):
train_data = self.train_representation(epoch)
max_x = np.linalg.norm(train_data, axis=1).max()
return max_x
def prediction_function(self, iteration):
model_location = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "subject_model.pth")
self.model.load_state_dict(torch.load(model_location, map_location=torch.device("cpu")))
self.model.to(self.DEVICE)
self.model.eval()
pred_fn = self.model.prediction
return pred_fn
def feature_function(self, epoch):
model_location = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, epoch), "subject_model.pth")
self.model.load_state_dict(torch.load(model_location, map_location=torch.device("cpu")))
self.model.to(self.DEVICE)
self.model.eval()
fea_fn = self.model.feature
return fea_fn
def get_pred(self, iteration, data):
'''
get the prediction score for data in epoch_id
:param data: numpy.ndarray
:param epoch_id:
:return: pred, numpy.ndarray
'''
prediction_func = self.prediction_function(iteration)
data = torch.from_numpy(data)
data = data.to(self.DEVICE)
pred = batch_run(prediction_func, data)
return pred
def training_accu(self, epoch):
data = self.train_representation_lb(epoch)
labels = self.train_labels_lb(epoch)
pred = self.get_pred(epoch, data).argmax(1)
val = evaluate_inv_accu(labels, pred)
return val
def testing_accu(self, epoch):
data = self.test_representation(epoch)
labels = self.test_labels(epoch)
pred = self.get_pred(epoch, data).argmax(1)
val = evaluate_inv_accu(labels, pred)
return val
def is_deltaB(self, epoch, data):
"""
check wheter input vectors are lying on delta-boundary or not
:param epoch_id:
:param data: numpy.ndarray
:return: numpy.ndarray, boolean, True stands for is_delta_boundary
"""
preds = self.get_pred(epoch, data)
border = is_B(preds)
return border
def checkpoint_path(self, epoch):
path = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, epoch))
return path
class DenseActiveLearningDataProvider(ActiveLearningDataProvider):
def __init__(self, content_path, model, base_epoch_start, epoch_num, device, classes, iteration_name="Iteration", epoch_name="Epoch", verbose=1):
super().__init__(content_path, model, base_epoch_start, device, classes, iteration_name, verbose)
self.mode = "dense_al"
self.epoch_num = epoch_num
self.s = 1
self.p = 1
self.e = epoch_num
self.epoch_name = epoch_name
def representation_dim(self):
train_data_loc = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, self.s), "{}_{:d}".format(self.epoch_name, self.epoch_num), "train_data.npy")
try:
train_data = np.load(train_data_loc)
repr_dim = np.prod(train_data.shape[1:])
return repr_dim
except Exception as e:
return None
def _meta_data(self, iteration):
time_inference = list()
training_data_path = os.path.join(self.content_path, "Training_data")
training_data = torch.load(os.path.join(training_data_path, "training_dataset_data.pth"),
map_location="cpu")
training_data = training_data.to(self.DEVICE)
testing_data_path = os.path.join(self.content_path, "Testing_data")
testing_data = torch.load(os.path.join(testing_data_path, "testing_dataset_data.pth"),
map_location="cpu")
testing_data = testing_data.to(self.DEVICE)
t_s = time.time()
# make it possible to choose a subset of testing data for testing
test_index_file = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "test_index.json")
if os.path.exists(test_index_file):
test_index = load_labelled_data_index(test_index_file)
else:
test_index = range(len(testing_data))
testing_data = testing_data[test_index]
for n_epoch in range(1, self.epoch_num+1, 1):
repr_model = self.feature_function(iteration, n_epoch)
# training data clustering
data_pool_representation = batch_run(repr_model, training_data)
location = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, n_epoch), "train_data.npy")
np.save(location, data_pool_representation)
# test data
test_data_representation = batch_run(repr_model, testing_data)
location = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, n_epoch), "test_data.npy")
np.save(location, test_data_representation)
t_e = time.time()
time_inference.append(t_e-t_s)
if self.verbose > 0:
print("Finish inferencing data for Iteration {:d}...".format(iteration))
print(
"Average time for inferencing data: {:.4f}...".format(sum(time_inference) / len(time_inference)))
# save result
save_dir = os.path.join(self.model_path, "SV_time.json")
if not os.path.exists(save_dir):
evaluation = dict()
else:
f = open(save_dir, "r")
evaluation = json.load(f)
f.close()
evaluation["data_inference"] = round(sum(time_inference) / len(time_inference), 3)
with open(save_dir, 'w') as f:
json.dump(evaluation, f)
del training_data
del testing_data
gc.collect()
def _estimate_boundary(self, iteration, num, l_bound):
'''
Preprocessing data. This process includes find_border_points and find_border_centers
save data for later training
'''
time_borders_gen = list()
training_data_path = os.path.join(self.content_path, "Training_data")
training_data = torch.load(os.path.join(training_data_path, "training_dataset_data.pth"),
map_location="cpu")
training_data = training_data.to(self.DEVICE)
for n_epoch in range(1, self.epoch_num+1, 1):
index_file = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "index.json")
index = load_labelled_data_index(index_file)
training_data = training_data[index]
repr_model = self.feature_function(iteration, n_epoch)
t0 = time.time()
confs = batch_run(self.model, training_data)
preds = np.argmax(confs, axis=1).squeeze()
# TODO how to choose the number of boundary points?
num_adv_eg = num
border_points, _, _ = get_border_points(model=self.model, input_x=training_data, confs=confs, predictions=preds, device=self.DEVICE, l_bound=l_bound, num_adv_eg=num_adv_eg, lambd=0.05, verbose=0)
t1 = time.time()
time_borders_gen.append(round(t1 - t0, 4))
# get gap layer data
border_points = border_points.to(self.DEVICE)
border_centers = batch_run(repr_model, border_points)
location = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, n_epoch), "border_centers.npy")
np.save(location, border_centers)
location = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, n_epoch), "ori_border_centers.npy")
np.save(location, border_points.cpu().numpy())
num_adv_eg = num
border_points, _, _ = get_border_points(model=self.model, input_x=training_data, confs=confs, predictions=preds, device=self.DEVICE, l_bound=l_bound, num_adv_eg=num_adv_eg, lambd=0.05, verbose=0)
# get gap layer data
border_points = border_points.to(self.DEVICE)
border_centers = batch_run(repr_model, border_points)
location = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_nanme, n_epoch), "test_border_centers.npy")
np.save(location, border_centers)
location = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, n_epoch), "test_ori_border_centers.npy")
np.save(location, border_points.cpu().numpy())
if self.verbose > 0:
print("Finish generating borders for Epoch {:d}...".format(n_epoch))
print(
"Average time for generate border points for each iteration: {:.4f}".format(sum(time_borders_gen) / len(time_borders_gen)))
# save result
save_dir = os.path.join(self.model_path, "SV_time.json")
if not os.path.exists(save_dir):
evaluation = dict()
else:
f = open(save_dir, "r")
evaluation = json.load(f)
f.close()
evaluation["data_B_gene"] = round(sum(time_borders_gen) / len(time_borders_gen), 3)
with open(save_dir, 'w') as f:
json.dump(evaluation, f)
def train_representation(self, iteration, epoch):
# load train data
train_data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "{}_{}".format(self.epoch_name, epoch), "train_data.npy")
lb_idxs = self.get_labeled_idx(iteration)
try:
train_data = np.load(train_data_loc)[lb_idxs]
except Exception as e:
print("no train data saved for Iteration {}".format(iteration))
train_data = None
return train_data
def train_representation_all(self, iteration, epoch):
# load train data
train_data_loc = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, epoch), "train_data.npy")
try:
train_data = np.load(train_data_loc)
except Exception as e:
print("no train data saved for Iteration {} Epoch {}".format(iteration, epoch))
train_data = None
return train_data
def train_representation_ulb(self, iteration, epoch):
# load train data
train_data_loc = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "{}_{}".format(self.epoch_name, epoch), "train_data.npy")
lb_idxs = self.get_labeled_idx(iteration)
try:
train_data = np.load(train_data_loc)
pool_num = len(train_data)
ulb_idx = self.get_unlabeled_idx(pool_num=pool_num, lb_idx=lb_idxs)
train_data = train_data[ulb_idx]
except Exception as e:
print("no train data saved for Iteration {}".format(iteration))
train_data = None
return train_data
def train_labels_ulb(self, iteration):
# load train data
training_data_loc = os.path.join(self.content_path, "Training_data", "training_dataset_label.pth")
lb_idxs = self.get_labeled_idx(iteration)
try:
training_labels = torch.load(training_data_loc, map_location="cpu")
ulb_idxs = self.get_unlabeled_idx(len(training_labels), lb_idxs)
training_labels = training_labels[ulb_idxs]
except Exception as e:
print("no train labels saved for Iteration {}".format(iteration))
training_labels = None
return training_labels.numpy()
def train_labels(self, iteration):
# load labelled train labels
training_data_loc = os.path.join(self.content_path, "Training_data", "training_dataset_label.pth")
index_file = os.path.join(self.model_path, "{}_{:d}".format(self.iteration_name, iteration), "index.json")
lb_idxs = np.array(load_labelled_data_index(index_file))
try:
training_labels = torch.load(training_data_loc, map_location="cpu")
training_labels = training_labels[lb_idxs]
except Exception as e:
print("no train labels saved for Iteration {}".format(iteration))
training_labels = None
return training_labels.numpy()
def train_labels_all(self):
# load train data
training_data_loc = os.path.join(self.content_path, "Training_data", "training_dataset_label.pth")
try:
training_labels = torch.load(training_data_loc, map_location="cpu")
except Exception as e:
print("no train labels saved")
training_labels = None
return training_labels.numpy()
def test_representation(self, iteration, epoch):
data_loc = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{}".format(self.epoch_name, epoch), "test_data.npy")
try:
test_data = np.load(data_loc)
index_file = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "test_index.json")
if os.path.exists(index_file):
index = load_labelled_data_index(index_file)
test_data = test_data[index]
except Exception as e:
print("no test data saved for Iteration {} Epoch {}".format(iteration, epoch))
test_data = None
return test_data
def border_representation(self, iteration, epoch):
border_centers_loc = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, epoch),
"border_centers.npy")
try:
border_centers = np.load(border_centers_loc)
except Exception as e:
print("no border points saved for Epoch {}".format(epoch))
border_centers = np.array([])
return border_centers
def test_border_representation(self, iteration, epoch):
border_centers_loc = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, epoch),
"test_border_centers.npy")
try:
border_centers = np.load(border_centers_loc)
except Exception as e:
print("no border points saved for Iteration {} Epoch {}".format(iteration, epoch))
border_centers = np.array([])
return border_centers
def max_norm(self, iteration, epoch):
train_data_loc = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, epoch), "train_data.npy")
index_file = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "index.json")
index = load_labelled_data_index(index_file)
try:
train_data = np.load(train_data_loc)
train_data = train_data[index]
max_x = np.linalg.norm(train_data, axis=1).max()
except Exception as e:
print("no train data saved for Iteration {} Epoch {}".format(iteration, epoch))
max_x = None
return max_x
def prediction_function(self, iteration, epoch):
model_location = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, epoch), "subject_model.pth")
self.model.load_state_dict(torch.load(model_location, map_location=torch.device("cpu")))
self.model.to(self.DEVICE)
self.model.eval()
pred_fn = self.model.prediction
return pred_fn
def feature_function(self, iteration, epoch):
model_location = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{:d}".format(self.epoch_name, epoch), "subject_model.pth")
self.model.load_state_dict(torch.load(model_location, map_location=torch.device("cpu")))
self.model = self.model.to(self.DEVICE)
self.model.eval()
fea_fn = self.model.feature
return fea_fn
def get_pred(self, iteration, epoch, data):
'''
get the prediction score for data in epoch_id
:param data: numpy.ndarray
:param epoch_id:
:return: pred, numpy.ndarray
'''
prediction_func = self.prediction_function(iteration, epoch)
data = torch.from_numpy(data)
data = data.to(self.DEVICE)
pred = batch_run(prediction_func, data)
return pred
def training_accu(self, iteration, epoch):
data = self.train_representation_lb(iteration, epoch)
labels = self.train_labels_lb(iteration)
pred = self.get_pred(iteration, epoch, data).argmax(-1)
val = evaluate_inv_accu(labels, pred)
return val
def testing_accu(self, iteration, epoch):
data = self.test_representation(epoch)
labels = self.test_labels(epoch)
test_index_file = os.path.join(self.model_path,"{}_{}".format(self.iteration_name, iteration), "{}_{}".format(self.epoch_name, epoch), "test_index.json")
if os.path.exists(test_index_file):
index = load_labelled_data_index(test_index_file)
labels = labels[index]
pred = self.get_pred(epoch, data).argmax(-1)
val = evaluate_inv_accu(labels, pred)
return val
def is_deltaB(self, iteration, epoch, data):
"""
check wheter input vectors are lying on delta-boundary or not
:param epoch_id:
:param data: numpy.ndarray
:return: numpy.ndarray, boolean, True stands for is_delta_boundary
"""
preds = self.get_pred(iteration, epoch, data)
border = is_B(preds)
return border
def single_checkpoint_path(self, iteration, epoch):
path = os.path.join(self.model_path, "{}_{}".format(self.iteration_name, iteration), "{}_{}".format(self.epoch_name, epoch))
return path
|