Download Test/embeddings.py from FelixOtt/gnss_federated_learning: direct link, hf CLI and curl.
- Browser
- Download file 5.18 kB
-
https://huggingface.co/datasets/FelixOtt/gnss_federated_learning/resolve/main/Test/embeddings.py
- Command line
-
hf download hf://datasets/FelixOtt/gnss_federated_learning/Test/embeddings.py
-
curl -L -o embeddings.py https://huggingface.co/datasets/FelixOtt/gnss_federated_learning/resolve/main/Test/embeddings.py
5.18 kB
| import sys | |
| import os | |
| import numpy as np | |
| import torch | |
| from torch import nn | |
| from tqdm import tqdm | |
| from torch.utils.data import DataLoader | |
| import torch.optim as optim | |
| from itertools import chain, combinations | |
| import utilities_raw as utilities # Assuming utilities_raw is in the same directory as this script | |
| from torchvision.models import resnet18 | |
| from easyfsl.methods import PrototypicalNetworks | |
| # | |
| def main(strategy, run_no,station_num): | |
| # Modify these paths based on the strategy and run_no | |
| if station_num ==0: | |
| folder = f"./workspace/Jammer_detection/Src/federated_darcy/{strategy}/model/" | |
| #folder = f"./workspace/Jammer_detection/Src/federated_darcy/Pytorch_federated_manual/{strategy}/model/" | |
| elif station_num==11: | |
| folder = f"./workspace/Jammer_detection/Src/federated_darcy/Pytorch_federated_manual/{strategy}/model/" | |
| elif station_num == 12: | |
| folder = "./workspace/Jammer_detection/Src/outputs/2023-12-11/16-17-23/model_global_500/" | |
| startweight = "./workspace/Jammer_detection/Src/outputs/2023-12-11/16-17-23/model_global_500/model_weights314epoch75.h5" | |
| else: | |
| folder = f"./workspace/Jammer_detection/Src/federated_darcy/{strategy}/local_models/station_{station_num}_models/" | |
| result_folder = f"{folder}/embtsne_{run_no}/" | |
| if station_num != 12: | |
| startweight = f"{folder}round--{run_no}_weights.h5" | |
| torch.autograd.set_detect_anomaly(True) | |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| print(device) | |
| norm_data = "./workspace/Jammer_detection/Datasets/norm_vals.npy" | |
| batchSize = 40 | |
| time_size = 243 | |
| dp_base = "./workspace/Jammer_detection/Datasets/data/" | |
| split_file = "./workspace/Jammer_detection/Datasets/train_test_splits/test_files_0.8_0.8_0.8_0.8_0.8_0.8_0.0_0.8_0.8_0.8_0.8_0.8_split4.txt" | |
| if not os.path.exists(result_folder): | |
| os.makedirs(result_folder) | |
| # startweight = f"{folder}round--{run_no}_weights.h5" | |
| print(startweight) | |
| # Create Test data lists | |
| print("Test File: ", split_file) | |
| with open(split_file, "r") as f: | |
| test_info = f.readlines() | |
| test_info = np.array([x.split("\n")[0].split("\t") for x in test_info]) | |
| test_list_raw = test_info[:, 0] | |
| test_classes = test_info[:, 1].astype(int) | |
| test_list = [] | |
| for tlr in test_list_raw: | |
| ms = int(tlr.split("_")[-1][-5:]) | |
| test_list.append([dp_base + tlr.split("_")[0], ms]) | |
| model =resnet18(pretrained=False) | |
| model.fc = nn.Identity() | |
| few_shot_classifier = PrototypicalNetworks(model).to(device) | |
| few_shot_classifier.load_state_dict(torch.load(startweight, map_location=device)) | |
| few_shot_classifier.eval() | |
| save_file_all_vals = f"{result_folder}/emb_" | |
| save_file_all_vals_ind = f"{result_folder}/ylabels_" | |
| results = [] | |
| # for ai, add_class in enumerate(additional_classes): | |
| # print("Dealing with classes: ", ai, add_class) | |
| # cur_classes = np.concatenate([old_classes, add_class]) | |
| # cur_classes.sort() | |
| # cur_support_list_files = [] | |
| # cur_support_list_classes = [] | |
| # for ci, cc in enumerate(cur_classes): | |
| # cur_support_list_files.extend(support_list[cc]) | |
| # cur_support_list_classes.extend([ci] * len(support_list[cc])) | |
| # cur_support_list = [cur_support_list_files, cur_support_list_classes] | |
| # # Prepare support images | |
| # support_images, support_labels = utilities.get_support_data(cur_support_list, time_size, norm=norm_data) | |
| # support_images = torch.tensor(support_images).to(device) | |
| # support_labels = torch.tensor(support_labels).to(device) | |
| # few_shot_classifier.process_support_set(support_images, support_labels) | |
| datagen = utilities.gen_data_batch_test(test_list, test_classes, time_size, batchSize, norm=norm_data) | |
| pred = [] | |
| lab = [] | |
| inds = [] | |
| bcount = 0 | |
| for X_batch, Y_batch, ind_batch in datagen: | |
| if bcount % 100 == 0: | |
| print("Dealing with batch: %d" % bcount) | |
| bcount += 1 | |
| inputs = torch.tensor(X_batch).to(device) | |
| out = few_shot_classifier.backbone(inputs).float() | |
| pred_x = out.detach().cpu().numpy() | |
| print(pred_x.shape) | |
| pred.extend(pred_x) | |
| lab.extend(Y_batch) | |
| inds.extend(ind_batch) | |
| del inputs, out | |
| pred = np.array(pred) | |
| lab = np.array(lab) | |
| inds = np.array(inds) | |
| np.save(save_file_all_vals + ".npy", pred) | |
| np.save(save_file_all_vals_ind + ".npy", lab) | |
| if __name__ == "__main__": | |
| if len(sys.argv) != 4: | |
| print("Usage: python script.py <strategy> <run_no>") | |
| sys.exit(1) | |
| strategy = sys.argv[1] | |
| run_no = sys.argv[2] | |
| station_no = sys.argv[3] | |
| try: | |
| run_no = int(run_no) | |
| station_num = int(station_no) | |
| except ValueError: | |
| print("Error: run_no must be an integer.") | |
| sys.exit(1) | |
| # # main(strategy, run_no,station_num) | |
| # rounds = [11, 12,13, 14, 15]#[1, 2, 3, 4, 5]#[6, 7, 8, 9, 10] # List of rounds | |
| # for round_num in rounds: | |
| # main(strategy, round_num, station_num) | |
| main(strategy, run_no, station_num) |