Download utilities.py from FelixOtt/gnss_pseudo_labeling: direct link, hf CLI and curl.
- Browser
- Download file 15.3 kB
-
https://huggingface.co/datasets/FelixOtt/gnss_pseudo_labeling/resolve/main/utilities.py
- Command line
-
hf download hf://datasets/FelixOtt/gnss_pseudo_labeling/utilities.py
-
curl -L -o utilities.py https://huggingface.co/datasets/FelixOtt/gnss_pseudo_labeling/resolve/main/utilities.py
15.3 kB
| import numpy as np | |
| import random | |
| import torch | |
| from torch.utils.data import Dataset | |
| from torchvision.transforms import v2 | |
| class custom_dataset(Dataset): | |
| def __init__(self, file_list, label_list, data_types_list, norm_dict, norm=True, time_size=243, augment=False, flipping=0.5, noise=0.5, noise_max_amp=0.1, zooming=0.5, zoom_min_max=[0.7, 1.0], cropping=0.5, intensity_mul=0.5, intensity_min_max=[0.8, 1.2], ret_y_type=torch.long): | |
| self.use_norm = norm | |
| self.time_size = time_size | |
| self.norm_dict = norm_dict | |
| self.files = file_list | |
| self.labels = label_list | |
| self.data_types = data_types_list | |
| self.indices = np.arange(len(self.files)).astype(int) | |
| self.augment = augment | |
| self.flipping = flipping | |
| self.noise = noise | |
| self.noise_max_amp = noise_max_amp | |
| self.zooming = zooming | |
| self.zoom_min_max = zoom_min_max | |
| self.cropping = cropping | |
| self.intensity_mul = intensity_mul | |
| self.intensity_min_max = intensity_min_max | |
| self.ret_y_type = ret_y_type | |
| def __getitem__(self, item: int): | |
| cur_dtype = self.data_types[item] | |
| cur_y_data = self.labels[item] | |
| if cur_dtype <= 1: | |
| cur_x_data = np.load(self.files[item]) | |
| if self.use_norm: | |
| cur_x_data -= self.norm_dict[cur_dtype][0] | |
| cur_x_data /= self.norm_dict[cur_dtype][1] | |
| if self.augment: | |
| cur_x_data, zz, zs, org_size = augment_data(cur_x_data, flipping=self.flipping, noise=self.noise, noise_max_amp=self.noise_max_amp, zooming=self.zooming, zoom_min_max=self.zoom_min_max, cropping=self.cropping, intensity_mul=self.intensity_mul, intensity_min_max=self.intensity_min_max) | |
| cur_x_data = torch.from_numpy(np.repeat(cur_x_data[None, :, :], 3, axis=0).astype("float32")) | |
| if zz is not None: | |
| cur_x_data = v2.Resize(size=org_size)(cur_x_data[:, zs[0]: zs[0] + zz[0], zs[1]: zs[1] + zz[1]]) | |
| return cur_x_data, torch.tensor(cur_y_data, dtype=self.ret_y_type) | |
| return torch.from_numpy(np.repeat(cur_x_data[None, :, :], 3, axis=0).astype("float32")), torch.tensor(cur_y_data, dtype=self.ret_y_type) | |
| elif cur_dtype == 2 or cur_dtype == 3: | |
| cur_x_data = (np.load(self.files[item])[:, 256:-256]).transpose((1, 0)) | |
| if self.use_norm: | |
| cur_x_data -= self.norm_dict[cur_dtype][0] | |
| cur_x_data /= self.norm_dict[cur_dtype][1] | |
| if len(cur_x_data[0]) != 34: | |
| cur_x_data = np.concatenate([np.tile(cur_x_data, (1, 7)), cur_x_data[:, :5], np.zeros((512, 21))], axis=1) | |
| else: | |
| cur_x_data = np.concatenate([np.tile(cur_x_data, (1, 7)), cur_x_data[:, :5]], axis=1) | |
| if self.augment: | |
| cur_x_data, zz, zs, org_size = augment_data(cur_x_data, flipping=self.flipping, noise=self.noise, noise_max_amp=self.noise_max_amp, zooming=self.zooming, zoom_min_max=self.zoom_min_max, cropping=self.cropping, intensity_mul=self.intensity_mul, intensity_min_max=self.intensity_min_max) | |
| cur_x_data = torch.from_numpy(np.repeat(cur_x_data[None, :, :], 3, axis=0).astype("float32")) | |
| if zz is not None: | |
| cur_x_data = v2.Resize(size=org_size)(cur_x_data[:, zs[0]: zs[0] + zz[0], zs[1]: zs[1] + zz[1]]) | |
| return cur_x_data, torch.tensor(cur_y_data, dtype=self.ret_y_type) | |
| return torch.from_numpy(np.repeat(cur_x_data[None, :, :], 3, axis=0).astype("float32")), torch.tensor(cur_y_data, dtype=self.ret_y_type) | |
| elif cur_dtype == 4: | |
| cur_x_data = np.load(self.files[item])[:, :243] | |
| if self.use_norm: | |
| cur_x_data -= self.norm_dict[cur_dtype][0] | |
| cur_x_data /= self.norm_dict[cur_dtype][1] | |
| if self.augment: | |
| cur_x_data, zz, zs, org_size = augment_data(cur_x_data, flipping=self.flipping, noise=self.noise, noise_max_amp=self.noise_max_amp, zooming=self.zooming, zoom_min_max=self.zoom_min_max, cropping=self.cropping, intensity_mul=self.intensity_mul, intensity_min_max=self.intensity_min_max) | |
| cur_x_data = torch.from_numpy(np.repeat(cur_x_data[None, :, :], 3, axis=0).astype("float32")) | |
| if zz is not None: | |
| cur_x_data = v2.Resize(size=org_size)(cur_x_data[:, zs[0]: zs[0] + zz[0], zs[1]: zs[1] + zz[1]]) | |
| return cur_x_data, torch.tensor(cur_y_data, dtype=self.ret_y_type) | |
| return torch.from_numpy(np.repeat(cur_x_data[None, :, :], 3, axis=0).astype("float32")), torch.tensor(cur_y_data, dtype=self.ret_y_type) | |
| else: | |
| cur_x_data = np.load(self.files[item]).astype("float") | |
| if self.use_norm: | |
| cur_x_data -= self.norm_dict[cur_dtype][0] | |
| cur_x_data /= self.norm_dict[cur_dtype][1] | |
| if self.augment: | |
| cur_x_data, zz, zs, org_size = augment_data(cur_x_data, flipping=self.flipping, noise=self.noise, noise_max_amp=self.noise_max_amp, zooming=self.zooming, zoom_min_max=self.zoom_min_max, cropping=self.cropping, intensity_mul=self.intensity_mul, intensity_min_max=self.intensity_min_max) | |
| cur_x_data = torch.from_numpy(cur_x_data.transpose((2, 0, 1)).astype("float32")) | |
| if zz is not None: | |
| cur_x_data = v2.Resize(size=org_size)(cur_x_data[:, zs[0]: zs[0] + zz[0], zs[1]: zs[1] + zz[1]]) | |
| return cur_x_data, torch.tensor(cur_y_data, dtype=self.ret_y_type) | |
| return torch.from_numpy(cur_x_data.transpose((2, 0, 1)).astype("float32")), torch.tensor(cur_y_data, dtype=self.ret_y_type) | |
| def __len__(self) -> int: | |
| return len(self.labels) | |
| def pseudo_labeling(all_preds, itr, temp_nl=2, kappa_n=0.005, kappa_p=0.05, tau_n=0.05, tau_p=0.70, class_blnc=1, num_classes=9): | |
| all_preds_edit = all_preds - np.max(all_preds, axis=2)[:, :, None] | |
| preds_softmax = np.exp(all_preds_edit)/np.sum(np.exp(all_preds_edit), axis=2)[:, :, None] | |
| preds_softmax_neg = np.exp(all_preds_edit/temp_nl)/np.sum(np.exp(all_preds_edit/temp_nl), axis=2)[:, :, None] | |
| preds_std = np.std(preds_softmax, axis=0) | |
| preds_std_neg = np.std(preds_softmax_neg, axis=0) | |
| preds_softmax = np.mean(preds_softmax, axis=0) | |
| preds_softmax_neg = np.mean(preds_softmax_neg, axis=0) | |
| max_value = np.max(preds_softmax, axis=1) | |
| max_idx = np.argmax(preds_softmax, axis=1) | |
| max_std = preds_std[np.arange(len(preds_std)), max_idx] | |
| nl_mask = ((preds_std_neg < kappa_n) * (preds_softmax_neg < tau_n)) * 1 | |
| for enum, item in enumerate(max_idx): | |
| nl_mask[enum, item] = 0 | |
| selected_idx = (max_value >= tau_p) * (max_std < kappa_p) | |
| pseudo_maxstd = max_std[selected_idx] | |
| pseudo_target = max_idx[selected_idx] | |
| pseudo_idx = np.where(selected_idx)[0].tolist() | |
| if itr < class_blnc - 1: | |
| min_count = 5000000 #arbitary large value | |
| for class_idx in range(num_classes): | |
| class_len = len(np.where(pseudo_target==class_idx)[0]) | |
| if class_len < min_count: | |
| min_count = class_len | |
| min_count = max(25, min_count) #this 25 is used to avoid degenarate cases when the minimum count for a certain class is very low | |
| blnc_idx_list = [] | |
| for class_idx in range(num_classes): | |
| current_class_idx = np.where(pseudo_target==class_idx) | |
| if len(np.where(pseudo_target==class_idx)[0]) > 0: | |
| current_class_maxstd = pseudo_maxstd[current_class_idx] | |
| sorted_maxstd_idx = np.argsort(current_class_maxstd) | |
| current_class_idx = current_class_idx[0][sorted_maxstd_idx[:min_count]] #select the samples with lowest uncertainty | |
| blnc_idx_list.extend(current_class_idx) | |
| blnc_idx_list = np.array(blnc_idx_list) | |
| pseudo_target = pseudo_target[blnc_idx_list] | |
| pseudo_idx = pseudo_idx[blnc_idx_list] | |
| pseudo_nl_mask = [] | |
| pseudo_nl_idx = [] | |
| for i in range(len(preds_softmax)): | |
| if i not in pseudo_idx and sum(nl_mask[i]) > 0: | |
| pseudo_nl_mask.append(nl_mask[i]) | |
| pseudo_nl_idx.append(i) | |
| pseudo_nl_mask = np.array(pseudo_nl_mask) | |
| return pseudo_idx, pseudo_target, pseudo_nl_idx, pseudo_nl_mask # pseudo_idx: Indices of pseudo labeled data with lables in pseudo_target; pseudo_nl_idx: Indices with nl pseudo labeled data with lables as mask in pseudo_nl_mask | |
| def get_dataset(data_files, norm_dict, norm=True, time_size=243, class_limit=-1): | |
| print("Files: ", data_files) | |
| dp_base = "../" | |
| file_list = [] | |
| label_list = [] | |
| data_types_list = [] | |
| for data_file in data_files: | |
| class_counts = np.zeros(9) | |
| cd_type = int(data_file.split("_")[-2]) | |
| with open(data_file, "r") as f: | |
| data_info = f.readlines() | |
| data_info = np.array([x.split("\n")[0].split("\t") for x in data_info]) | |
| x_files = [] | |
| y_labels = [] | |
| for x in data_info: | |
| cur_y_lab = int(x[1]) | |
| if class_limit != -1 and class_counts[cur_y_lab] >= class_limit: | |
| continue | |
| class_counts[cur_y_lab] += 1 | |
| x_files.append(dp_base + x[0]) | |
| y_labels.append(cur_y_lab) | |
| file_list.extend(x_files) | |
| label_list.extend(y_labels) | |
| data_types_list.extend([cd_type] * len(x_files)) | |
| return custom_dataset(file_list, label_list, data_types_list, norm_dict, norm=norm, time_size=time_size) | |
| def get_dataset_files(data_files, norm_dict, norm=False, time_size=243, augment=False, flipping=0.5, noise=0.5, noise_max_amp=0.1, zooming=0.5, zoom_min_max=[0.7, 1.0], cropping=0.5, intensity_mul=0.5, intensity_min_max=[0.8, 1.2]): | |
| return custom_dataset([x[0] for x in data_files], [x[1] for x in data_files], [x[2] for x in data_files], norm_dict, norm=norm, time_size=time_size, augment=augment, flipping=flipping, noise=noise, noise_max_amp=noise_max_amp, zooming=zooming, zoom_min_max=zoom_min_max, cropping=cropping, intensity_mul=intensity_mul, intensity_min_max=intensity_min_max) | |
| def get_dataset_files_neg(data_files, norm_dict, norm=False, time_size=243, augment=False, flipping=0.5, noise=0.5, noise_max_amp=0.1, zooming=0.5, zoom_min_max=[0.7, 1.0], cropping=0.5, intensity_mul=0.5, intensity_min_max=[0.8, 1.2]): | |
| return custom_dataset([x[0] for x in data_files], [x[1] for x in data_files], [x[2] for x in data_files], norm_dict, norm=norm, time_size=time_size, augment=augment, flipping=flipping, noise=noise, noise_max_amp=noise_max_amp, zooming=zooming, zoom_min_max=zoom_min_max, cropping=cropping, intensity_mul=intensity_mul, intensity_min_max=intensity_min_max, ret_y_type=torch.float32) | |
| def get_lab_unlab(data_files, class_limit=-1, random_seed=0, labeled_perc=0.1, grouped_shuffle=1): | |
| print("Files: ", data_files) | |
| dp_base = "../" | |
| labeled_list = [] | |
| unlabeled_list = [] | |
| for data_file in data_files: | |
| class_counts = np.zeros(9) | |
| cd_type = int(data_file.split("_")[-2]) | |
| with open(data_file, "r") as f: | |
| data_info = f.readlines() | |
| data_info = np.array([x.split("\n")[0].split("\t") for x in data_info]) | |
| x_files = [] | |
| y_labels = [] | |
| for x in data_info: | |
| cur_y_lab = int(x[1]) | |
| if class_limit != -1 and class_counts[cur_y_lab] >= class_limit: | |
| continue | |
| class_counts[cur_y_lab] += 1 | |
| x_files.append(dp_base + x[0]) | |
| y_labels.append(cur_y_lab) | |
| comb_list = [[x_files[ci], y_labels[ci], cd_type] for ci in range(len(x_files))] | |
| if grouped_shuffle != 1: | |
| comb_list_inds = np.arange(int(len(comb_list) / grouped_shuffle)) | |
| else: | |
| comb_list_inds = np.arange(len(comb_list)) | |
| random.Random(random_seed).shuffle(comb_list_inds) | |
| labeled_count = (class_counts * labeled_perc + 1).astype(int) | |
| cur_class_counts = np.zeros(9) | |
| for ci, cli in enumerate(comb_list_inds): | |
| if grouped_shuffle != 1: | |
| cl = comb_list[cli * grouped_shuffle] | |
| else: | |
| cl = comb_list[cli] | |
| cur_class = cl[1] | |
| if cur_class_counts[cur_class] < labeled_count[cur_class]: | |
| if grouped_shuffle != 1: | |
| labeled_list.extend([cl for cl in comb_list[cli * grouped_shuffle: (cli + 1) * grouped_shuffle]]) | |
| else: | |
| labeled_list.append(cl) | |
| else: | |
| if grouped_shuffle != 1: | |
| unlabeled_list.extend([cl for cl in comb_list[cli * grouped_shuffle: (cli + 1) * grouped_shuffle]]) | |
| else: | |
| unlabeled_list.append(cl) | |
| if grouped_shuffle != 1: | |
| cur_class_counts[cur_class] += grouped_shuffle | |
| else: | |
| cur_class_counts[cur_class] += 1 | |
| return labeled_list, unlabeled_list | |
| def get_pseudo_labels(all_preds, threshold): | |
| all_preds_edit = all_preds - np.max(all_preds, axis=2)[:, :, None] | |
| preds_softmax = np.exp(all_preds_edit)/np.sum(np.exp(all_preds_edit), axis=2)[:, :, None] | |
| preds_argmax = np.argmax(all_preds_edit, axis=-1) | |
| preds_mean = np.mean(preds_softmax, axis=0) | |
| mask = np.ones(preds_argmax[0].shape).astype(bool) | |
| for mi in range(1, len(all_preds_edit)): | |
| mask = mask * (preds_argmax[0] == preds_argmax[mi]) | |
| preds_mean_arg = np.array([preds_mean[i, x] for i, x in enumerate(preds_argmax[0])]) | |
| mask_thresh = preds_mean_arg > threshold | |
| ret_inds = np.where(mask * mask_thresh)[0] | |
| return np.array([[r, preds_argmax[0, r]] for r in ret_inds]) | |
| def augment_data(data_in, flipping=0.5, noise=0.5, noise_max_amp=0.1, zooming=0.5, zoom_min_max=[0.7, 1.0], cropping=0.5, intensity_mul=0.5, intensity_min_max=[0.8, 1.2]): | |
| yx_shape = data_in.shape | |
| flip = np.random.random() < flipping | |
| if flip: | |
| flip_type = np.random.randint(1, 4) | |
| if flip_type == 1: | |
| data_in = data_in[:, ::-1] | |
| elif flip_type == 2: | |
| data_in = data_in[:, ::-1] | |
| else: | |
| data_in = data_in[::-1, ::-1] | |
| add_noise = np.random.random() < noise | |
| if add_noise: | |
| data_in += (np.random.random(size=yx_shape) * 2 - 1) * noise_max_amp | |
| mult_intensity = np.random.random() < intensity_mul | |
| if mult_intensity: | |
| data_in *= (np.random.random() * (intensity_min_max[1] - intensity_min_max[0]) + intensity_min_max[0]) | |
| data_in[data_in < 0] = 0.0 | |
| data_in[data_in > 1] = 1.0 | |
| zoom = np.random.random() < zooming | |
| crop = np.random.random() < cropping | |
| if zoom or crop: | |
| zoom_xy = ((np.random.random(2) * (zoom_min_max[1] - zoom_min_max[0]) + zoom_min_max[0]) * yx_shape[:2]).astype(int) | |
| zoom_starts = (np.random.random(2) * (yx_shape[:2] - zoom_xy)).astype(int) | |
| else: | |
| zoom_xy = None | |
| zoom_starts = None | |
| if not zoom and crop: | |
| crop_mask = np.zeros(yx_shape) | |
| crop_mask[zoom_starts[0]: zoom_starts[0] + zoom_xy[0], zoom_starts[1]: zoom_starts[1] + zoom_xy[1]] = 1.0 | |
| data_in *= crop_mask | |
| zoom_xy = None | |
| zoom_starts = None | |
| return data_in, zoom_xy, zoom_starts, yx_shape[:2] | |