code stringlengths 17 6.64M |
|---|
def extract_features_wrapper(paths, path2gt, model='vggish', save_as=False):
'Wrapper function for extracting features (MusiCNN, VGGish or OpenL3) per batch.\n If a save_as string argument is passed, the features wiil be saved in \n the specified file.\n '
if (model == 'vggish'):
featur... |
def load_path2gt(paths_file, config):
' Given the path, construct the ground truth vectors.\n This function heavily relies on path2gt_datasets(.),\n where the relation between the path and ground truth\n are defined.\n '
paths = list()
path2gt = dict()
path2onehot = dict()
... |
def label2onehot(label, num_classes):
' Convert class label to one hot vector.\n Example: label2onehot(label=2, num_classes=5) > array([0., 0., 1., 0., 0.])\n '
onehot = np.zeros(num_classes)
onehot[label] = 1
return onehot
|
def path2gt_datasets(path, dataset):
' Given the audio path, it returns the ground truth label.\n Define HERE a new dataset to employ this code with other data.\n '
if (dataset == 'GTZAN'):
if ('blues' in path):
return 0
elif ('classical' in path):
return 1
... |
def matrix_visualization(matrix, title=None):
' Visualize 2D matrices like spectrograms or feature maps.\n '
plt.figure()
plt.imshow(np.flipud(matrix.T), interpolation=None)
plt.colorbar()
if (title != None):
plt.title(title)
plt.show()
|
def wavefile_to_waveform(wav_file, features_type):
(data, sr) = sf.read(wav_file)
if (features_type == 'vggish'):
tmp_name = (str(int((np.random.rand(1) * 1000000))) + '.wav')
sf.write(tmp_name, data, sr, subtype='PCM_16')
(sr, wav_data) = wavfile.read(tmp_name)
os.remove(tmp_n... |
def waveform_to_examples(data, sample_rate):
'Converts audio waveform into an array of examples for VGGish.\n\n Args:\n data: np.array of either one dimension (mono) or two dimensions\n (multi-channel, with the outer dimension representing channels).\n Each sample is generally expected to lie in the... |
def wavfile_to_examples(wav_file):
'Convenience wrapper around waveform_to_examples() for a common WAV format.\n\n Args:\n wav_file: String path to a file, or a file-like object. The file\n is assumed to contain WAV audio data with signed 16-bit PCM samples.\n\n Returns:\n See waveform_to_examples.\n ... |
def define_vggish_slim(training=False):
"Defines the VGGish TensorFlow model.\n\n All ops are created in the current default graph, under the scope 'vggish/'.\n\n The input is a placeholder named 'vggish/input_features' of type float32 and\n shape [batch_size, num_frames, num_bands] where batch_size is variabl... |
def load_vggish_slim_checkpoint(session, checkpoint_path):
'Loads a pre-trained VGGish-compatible checkpoint.\n\n This function can be used as an initialization function (referred to as\n init_fn in TensorFlow documentation) which is called in a Session after\n initializating all variables. When used as an ini... |
def data_loader(data_name, miss_rate):
'Loads datasets and introduce missingness.\n \n Args:\n - data_name: letter, spam, or mnist\n - miss_rate: the probability of missing components\n \n Returns:\n data_x: original data\n miss_data_x: data with missing values\n data_m: indicator matrix for ... |
def main(args):
'Main function for UCI letter and spam datasets.\n \n Args:\n - data_name: letter or spam\n - miss_rate: probability of missing components\n - batch:size: batch size\n - hint_rate: hint rate\n - alpha: hyperparameter\n - iterations: iterations\n \n Returns:\n - imputed_d... |
def vime_self(x_unlab, p_m, alpha, parameters):
'Self-supervised learning part in VIME.\n \n Args:\n x_unlab: unlabeled feature\n p_m: corruption probability\n alpha: hyper-parameter to control the weights of feature and mask losses\n parameters: epochs, batch_size\n \n Returns:\n encoder: Re... |
def MinMaxScaler(data):
'Min Max normalizer.\n \n Args:\n - data: original data\n \n Returns:\n - norm_data: normalized data\n '
numerator = (data - np.min(data, 0))
denominator = (np.max(data, 0) - np.min(data, 0))
norm_data = (numerator / (denominator + 1e-07))
return norm_data
|
def sine_data_generation(no, seq_len, dim):
'Sine data generation.\n \n Args:\n - no: the number of samples\n - seq_len: sequence length of the time-series\n - dim: feature dimensions\n \n Returns:\n - data: generated data\n '
data = list()
for i in range(no):
temp = list()
... |
def real_data_loading(data_name, seq_len):
'Load and preprocess real-world datasets.\n \n Args:\n - data_name: stock or energy\n - seq_len: sequence length\n \n Returns:\n - data: preprocessed data.\n '
assert (data_name in ['stock', 'energy'])
if (data_name == 'stock'):
ori_data =... |
def main(args):
'Main function for timeGAN experiments.\n \n Args:\n - data_name: sine, stock, or energy\n - seq_len: sequence length\n - Network parameters (should be optimized for different datasets)\n - module: gru, lstm, or lstmLN\n - hidden_dim: hidden dimensions\n - num_layer: numb... |
def discriminative_score_metrics(ori_data, generated_data):
'Use post-hoc RNN to classify original data and synthetic data\n \n Args:\n - ori_data: original data\n - generated_data: generated synthetic data\n \n Returns:\n - discriminative_score: np.abs(classification accuracy - 0.5)\n '
tf.re... |
class ML_ISTA(nn.Module):
def __init__(self, T):
super(ML_ISTA, self).__init__()
self.T = T
self.W1 = nn.Parameter(torch.randn(32, 3, 4, 4), requires_grad=True)
self.strd1 = 2
self.W2 = nn.Parameter(torch.randn(64, 32, 4, 4), requires_grad=True)
self.strd2 = 2
... |
class ML_FISTA(nn.Module):
def __init__(self, T):
super(ML_FISTA, self).__init__()
self.T = T
self.W1 = nn.Parameter(torch.randn(32, 3, 4, 4), requires_grad=True)
self.strd1 = 2
self.W2 = nn.Parameter(torch.randn(64, 32, 4, 4), requires_grad=True)
self.strd2 = 2
... |
class ML_LISTA_NET(nn.Module):
def __init__(self, T):
super(ML_LISTA_NET, self).__init__()
self.T = T
self.W1 = nn.Parameter(torch.randn(32, 3, 4, 4), requires_grad=True)
self.strd1 = 2
self.W2 = nn.Parameter(torch.randn(64, 32, 4, 4), requires_grad=True)
self.strd... |
class LBP_NET(nn.Module):
def __init__(self, T):
super(LBP_NET, self).__init__()
self.T = T
self.W1 = nn.Parameter(torch.randn(32, 3, 4, 4), requires_grad=True)
self.strd1 = 2
self.W2 = nn.Parameter(torch.randn(64, 32, 4, 4), requires_grad=True)
self.strd2 = 2
... |
class All_Free(nn.Module):
def __init__(self):
super(All_Free, self).__init__()
m1 = 32
m2 = 64
m3 = 128
self.W1_1 = nn.Parameter(((0.1 / np.sqrt((3 * 16))) * torch.randn(32, 3, 4, 4)), requires_grad=True)
self.W1_2 = nn.Parameter(((0.1 / np.sqrt((3 * 16))) * torch... |
class ML_ISTA_NET(nn.Module):
def __init__(self, m1, m2, m3, T):
super(ML_ISTA_NET, self).__init__()
self.T = T
self.W1 = nn.Parameter(torch.randn(m1, 1, 6, 6), requires_grad=True)
self.strd1 = 2
self.W2 = nn.Parameter(torch.randn(m2, m1, 6, 6), requires_grad=True)
... |
class ML_FISTA_NET(nn.Module):
def __init__(self, m1, m2, m3, T):
super(ML_FISTA_NET, self).__init__()
self.T = T
self.W1 = nn.Parameter(torch.randn(m1, 1, 6, 6), requires_grad=True)
self.strd1 = 2
self.W2 = nn.Parameter(torch.randn(m2, m1, 6, 6), requires_grad=True)
... |
class ML_LISTA_NET(nn.Module):
def __init__(self, m1, m2, m3, T):
super(ML_LISTA_NET, self).__init__()
self.T = T
self.B1 = nn.Parameter(torch.randn(m1, 1, 6, 6), requires_grad=True)
self.B2 = nn.Parameter(torch.randn(m2, m1, 6, 6), requires_grad=True)
self.B3 = nn.Paramet... |
class LBP_NET(nn.Module):
def __init__(self, m1, m2, m3, T):
super(LBP_NET, self).__init__()
self.T = T
self.W1 = nn.Parameter(torch.randn(m1, 1, 6, 6), requires_grad=True)
self.strd1 = 2
self.W2 = nn.Parameter(torch.randn(m2, m1, 6, 6), requires_grad=True)
self.st... |
class All_Free(nn.Module):
def __init__(self, m1, m2, m3):
super(All_Free, self).__init__()
self.W1_1 = nn.Parameter(((0.1 / np.sqrt(36)) * torch.randn(m1, 1, 6, 6)), requires_grad=True)
self.W1_2 = nn.Parameter(((0.1 / np.sqrt(36)) * torch.randn(m1, 1, 6, 6)), requires_grad=True)
... |
def permutation_test(tokens, key, n, k, vocab_size, n_runs=100):
rng = mersenne_rng(key)
xi = np.array([rng.rand() for _ in range((n * vocab_size))], dtype=np.float32).reshape(n, vocab_size)
test_result = detect(tokens, n, k, xi)
p_val = 0
for run in range(n_runs):
xi_alternative = np.rand... |
def detect(tokens, n, k, xi, gamma=0.0):
m = len(tokens)
n = len(xi)
A = np.empty(((m - (k - 1)), n))
for i in range((m - (k - 1))):
for j in range(n):
A[i][j] = levenshtein(tokens[i:(i + k)], xi[((j + np.arange(k)) % n)], gamma)
return np.min(A)
|
def main(args):
with open(args.document, 'r') as f:
text = f.read()
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer)
tokens = tokenizer.encode(text, return_tensors='pt', truncation=True, max_length=2048).numpy()[0]
t0 = time.time()
pval = permutation_test(tokens, args.key, args.n,... |
class mersenne_rng(object):
def __init__(self, seed=5489):
self.state = ([0] * 624)
self.f = 1812433253
self.m = 397
self.u = 11
self.s = 7
self.b = 2636928640
self.t = 15
self.c = 4022730752
self.l = 18
self.index = 624
self... |
def substitution_attack(tokens, p, vocab_size, distribution=None):
if (distribution is None):
distribution = (lambda x: (torch.ones(size=(len(tokens), vocab_size)) / vocab_size))
idx = torch.randperm(len(tokens))[:int((p * len(tokens)))]
new_probs = distribution(tokens)
samples = torch.multino... |
def deletion_attack(tokens, p):
idx = torch.randperm(len(tokens))[:int((p * len(tokens)))]
keep = torch.ones(len(tokens), dtype=torch.bool)
keep[idx] = False
tokens = tokens[keep]
return tokens
|
def insertion_attack(tokens, p, vocab_size, distribution=None):
if (distribution is None):
distribution = (lambda x: (torch.ones(size=(len(tokens), vocab_size)) / vocab_size))
idx = torch.randperm(len(tokens))[:int((p * len(tokens)))]
new_probs = distribution(tokens)
samples = torch.multinomia... |
def permutation_test(tokens, vocab_size, n, k, seed, test_stat, n_runs=100, max_seed=100000):
generator = torch.Generator()
generator.manual_seed(int(seed))
test_result = test_stat(tokens=tokens, n=n, k=k, generator=generator, vocab_size=vocab_size)
p_val = 0
for run in range(n_runs):
pi =... |
def fast_permutation_test(tokens, vocab_size, n, k, seed, test_stat, null_results):
generator = torch.Generator()
generator.manual_seed(int(seed))
test_result = test_stat(tokens=tokens, n=n, k=k, generator=generator, vocab_size=vocab_size)
p_val = (torch.searchsorted(null_results, test_result, right=T... |
def phi(tokens, n, k, generator, key_func, vocab_size, dist, null=False, normalize=False):
if null:
tokens = torch.unique(tokens, return_inverse=True, sorted=False)[1]
eff_vocab_size = (torch.max(tokens) + 1)
else:
eff_vocab_size = vocab_size
(xi, pi) = key_func(generator, n, vocab... |
def adjacency(tokens, xi, dist, k):
m = len(tokens)
n = len(xi)
A = torch.empty(size=((m - (k - 1)), n))
for i in range((m - (k - 1))):
for j in range(n):
A[i][j] = dist(tokens[i:(i + k)], xi[((j + torch.arange(k)) % n)])
return A
|
def gumbel_key_func(generator, n, vocab_size, eff_vocab_size=None):
if (eff_vocab_size is None):
eff_vocab_size = vocab_size
pi = torch.arange(eff_vocab_size)
xi = torch.rand((n, eff_vocab_size), generator=generator)
return (xi, pi)
|
def gumbel_sampling(probs, pi, xi):
return torch.argmax((xi ** (1 / torch.gather(probs, 1, pi))), axis=1).unsqueeze((- 1))
|
def gumbel_score(tokens, xi):
xi_samp = torch.gather(xi, (- 1), tokens.unsqueeze((- 1))).squeeze()
return (- torch.sum(torch.log((1 / (1 - xi_samp)))))
|
def gumbel_edit_score(tokens, xi, gamma):
return gumbel_levenshtein(tokens.numpy(), xi.numpy(), gamma)
|
class Categories():
'\n Work with aliases from ISO 15924.\n https://en.wikipedia.org/wiki/ISO_15924#List_of_codes\n '
fpath = os.path.join(DATA_LOCATION, 'categories.json')
@classmethod
def _get_ranges(cls, categories):
'\n :return: iter: (start code, end code)\n :rtype... |
class Languages():
fpath = os.path.join(DATA_LOCATION, 'languages.json')
@classmethod
def get_alphabet(cls, languages):
'\n :return: set of chars in alphabet by languages list\n :rtype: set\n '
with open(cls.fpath, encoding='utf-8') as f:
data = json.load(... |
class Homoglyphs():
def __init__(self, categories=None, languages=None, alphabet=None, strategy=STRATEGY_IGNORE, ascii_strategy=STRATEGY_IGNORE, ascii_range=ASCII_RANGE):
if (strategy not in (STRATEGY_LOAD, STRATEGY_IGNORE, STRATEGY_REMOVE)):
raise ValueError('Invalid strategy')
self.... |
def normalization_strategy_lookup(strategy_name: str) -> object:
if (strategy_name == 'unicode'):
return UnicodeSanitizer()
elif (strategy_name == 'homoglyphs'):
return HomoglyphCanonizer()
elif (strategy_name == 'truecase'):
return TrueCaser()
|
class HomoglyphCanonizer():
'Attempts to detect homoglyph attacks and find a consistent canon.\n\n This function does so on a per-ISO-category level. Language-level would also be possible (see commented code).\n '
def __init__(self):
self.homoglyphs = None
def __call__(self, homoglyphed_st... |
class UnicodeSanitizer():
'Regex-based unicode sanitzer. Has different levels of granularity.\n\n * ruleset="whitespaces" - attempts to remove only whitespace unicode characters\n * ruleset="IDN.blacklist" - does its best to remove unusual unicode based on Network.IDN.blacklist characters\n * rulese... |
class TrueCaser():
'True-casing, is a capitalization normalization that returns text to its original capitalization.\n\n This defends against attacks that wRIte TeXt lIkE spOngBoB.\n\n Here, a simple POS-tagger is used.\n '
uppercase_pos = ['PROPN']
def __init__(self, backend='spacy'):
i... |
class WatermarkBase():
def __init__(self, vocab: list[int]=None, gamma: float=0.5, delta: float=2.0, seeding_scheme: str='simple_1', hash_key: int=15485863, select_green_tokens: bool=True):
self.vocab = vocab
self.vocab_size = len(vocab)
self.gamma = gamma
self.delta = delta
... |
class WatermarkLogitsProcessor(WatermarkBase, LogitsProcessor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _calc_greenlist_mask(self, scores: torch.FloatTensor, greenlist_token_ids) -> torch.BoolTensor:
green_tokens_mask = torch.zeros_like(scores)
for ... |
class WatermarkDetector(WatermarkBase):
def __init__(self, *args, device: torch.device=None, tokenizer: Tokenizer=None, z_threshold: float=4.0, normalizers: list[str]=['unicode'], ignore_repeated_bigrams: bool=False, **kwargs):
super().__init__(*args, **kwargs)
assert device, 'Must pass device'
... |
def transform_key_func(generator, n, vocab_size, eff_vocab_size=None):
pi = torch.randperm(vocab_size, generator=generator)
xi = torch.rand((n, 1), generator=generator)
return (xi, pi)
|
def transform_sampling(probs, pi, xi):
cdf = torch.cumsum(torch.gather(probs, 1, pi), 1)
return torch.gather(pi, 1, torch.searchsorted(cdf, xi))
|
def transform_score(tokens, xi):
return torch.pow(torch.linalg.norm((tokens - xi.squeeze()), ord=1), 1)
|
def transform_edit_score(tokens, xi, gamma=1):
return transform_levenshtein(tokens.numpy(), xi.squeeze().numpy(), gamma)
|
class BaseArgs():
'\n Arguments for data, model, and checkpoints.\n '
def __init__(self):
(self.is_train, self.split) = (None, None)
self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
self.parser.add_argument('--n_workers', type=int, defaul... |
class TestArgs(BaseArgs):
'\n Arguments for testing.\n '
def __init__(self):
super(TestArgs, self).__init__()
self.is_train = False
self.split = 'val'
self.parser.add_argument('--batch_size', type=int, default=1, help='batch size')
self.parser.add_argument('--which_e... |
class TrainArgs(BaseArgs):
'\n Arguments specific for training.\n '
def __init__(self):
super(TrainArgs, self).__init__()
self.is_train = True
self.split = 'train'
self.parser.add_argument('--batch_size', type=int, default=4, help='batch size per gpu')
self.parser.ad... |
def make_dataset(root, is_train):
if is_train:
folder = 'balls_n4_t60_ex50000'
else:
folder = 'balls_n4_t60_ex2000'
dataset = np.load(os.path.join(root, folder, 'dataset_info.npy'))
return dataset
|
class BouncingBalls(data.Dataset):
'\n Bouncing balls dataset.\n '
def __init__(self, root, is_train, n_frames_input, n_frames_output, image_size, transform=None, return_positions=False):
super(BouncingBalls, self).__init__()
self.n_frames = (n_frames_input + n_frames_output)
self.d... |
def get_data_loader(opt):
if (opt.dset_name == 'moving_mnist'):
transform = transforms.Compose([vtransforms.ToTensor()])
dset = MovingMNIST(opt.dset_path, opt.is_train, opt.n_frames_input, opt.n_frames_output, opt.num_objects, transform)
elif (opt.dset_name == 'bouncing_balls'):
transf... |
def get_model(opt):
if (opt.model == 'crop'):
model = DDPAE(opt)
else:
raise NotImplementedError
model.setup_training()
model.initialize_weights()
return model
|
class ImageDecoder(nn.Module):
'\n Decode images from vectors. Similar structure as DCGAN.\n '
def __init__(self, input_size, n_channels, ngf, n_layers, activation='tanh'):
super(ImageDecoder, self).__init__()
ngf = (ngf * (2 ** (n_layers - 2)))
layers = [nn.ConvTranspose2d(input_si... |
class ImageEncoder(nn.Module):
'\n Encodes images. Similar structure as DCGAN.\n '
def __init__(self, n_channels, output_size, ngf, n_layers):
super(ImageEncoder, self).__init__()
layers = [nn.Conv2d(n_channels, ngf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True)]
for i in ra... |
def build(is_train, tb_dir=None):
'\n Parse arguments, setup logger and tensorboardX directory.\n '
(opt, log) = (args.TrainArgs().parse() if is_train else args.TestArgs().parse())
os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpus
os.makedirs(opt.ckpt_path, exist_ok=True)
torch.manual_seed(666)
... |
class Logger():
'\n Logger to write logs to file.\n '
def __init__(self, ckpt_path, name='train'):
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(message)s', datefmt=blue('[%Y-%m-%d,%H:%M:%S]'))
fh = logging.... |
def to_numpy(array):
'\n :param array: Variable, GPU tensor, or CPU tensor\n :return: numpy\n '
if isinstance(array, np.ndarray):
return array
if isinstance(array, torch.autograd.Variable):
array = array.data
if array.is_cuda:
array = array.cpu()
return array.numpy()
|
def blue(string):
return (('\x1b[94m' + string) + '\x1b[0m')
|
def prompt_yes_no(question):
'\n Prompt user to type yes or no.\n '
i = input((question + ' [y/n]: '))
if ((len(i) > 0) and ((i[0] == 'y') or (i[0] == 'Y'))):
return True
else:
return False
|
class Visualizer():
def __init__(self, tb_path):
self.tb_path = tb_path
if os.path.exists(tb_path):
if prompt_yes_no('{} already exists. Proceed?'.format(tb_path)):
os.system('rm -r {}'.format(tb_path))
else:
exit(0)
self.writer = Su... |
def main():
TARGET_DIR = 'depth_benchmark'
(K_RAW, K_DEPTH) = (DATA_PATHS['kitti_raw'], DATA_PATHS['kitti_depth'])
print(f'-> Exporting Kitti Benchmark from "{K_DEPTH}" to "{K_RAW}"...')
ROOT = (K_RAW / TARGET_DIR)
ROOT.mkdir(exist_ok=True)
for seq in kr.SEQS:
(ROOT / seq).mkdir(exist_... |
def process_dataset(src_dir: Path, dst_dir: Path, use_hints: bool=True, use_benchmark: bool=True, overwrite: bool=False) -> None:
'Process the entire Kitti Raw Sync datsets.'
(HINTS_DIR, BENCHMARK_DIR) = ('depth_hints', 'depth_benchmark')
if (not (path := (dst_dir / 'splits')).is_dir()):
shutil.co... |
def process_sequence(src_dir: Path, dst_dir: Path, overwrite: bool=False) -> None:
'Process a full Kitti Raw sequence: e.g. kitti_raw_sync/2011_09_26.'
print(f'-> Processing sequence "{src_dir}"')
for src_path in sorted(src_dir.iterdir()):
if src_path.is_file():
continue
dst_pa... |
def process_drive(src_dir: Path, dst_dir: Path, overwrite: bool=False) -> None:
'Process a full Kitti Raw sequence: e.g. kitti_raw_sync/2011_09_26/2011_09_26_drive_0005.'
print(f' -> Processing drive "{src_dir}"')
for src_path in sorted(src_dir.iterdir()):
dst_path = (dst_dir / src_path.name)
... |
def process_dir(src_dir: Path, dst_dir: Path, overwrite: bool=False) -> None:
'Processes a data directory within a given drive.\n\n Cases:\n - Base dataset: images_00, images_01, velodyne_points, oxts (/data & /timestamps for each)\n - Depth hints: images_02, images_03\n - Depth benchmark:... |
def export_calibration(src_seq: Path, dst_seq: Path, overwrite: bool=False) -> None:
'Exports sequence calibration information as a LabelDatabase of arrays.'
dst_dir = (dst_seq / 'calibration')
if ((not overwrite) and dst_dir.is_dir()):
print(f' -> Skipping calib "{dst_dir}"')
return
e... |
def export_images(src_dir: Path, dst_dir: Path) -> None:
'Export images as an ImageDatabase.'
image_paths = {file.stem: file for file in sorted(src_dir.iterdir())}
write_image_database(image_paths, dst_dir)
|
def export_oxts(src_dir: Path, dst_dir: Path) -> None:
'Export OXTS dicts as a LabelDatabase.'
data = {file.stem: kr.load_oxts(file) for file in sorted(src_dir.iterdir())}
write_label_database(data, dst_dir)
|
def export_velodyne(src_dir: Path, dst_dir: Path) -> None:
'Export Velodyne points as a LabelDatabase of arrays.'
data = {file.stem: kr.load_velo(file) for file in sorted(src_dir.iterdir())}
write_label_database(data, dst_dir)
|
def export_hints(src_dir: Path, dst_dir: Path) -> None:
'Export depth hints as a LabelDatabase of arrays.'
data = {file.stem: np.load(file) for file in sorted(src_dir.iterdir())}
write_array_database(data, dst_dir)
|
def save(file: Path, **kwargs) -> None:
'Save a list of arrays as a npz file.'
print(f'''
-> Saving to "{file}"...''')
np.savez_compressed(file, **kwargs)
|
def export_kitti(depth_split: str, mode: str, use_velo_depth: bool=False, save_stem: Optional[str]=None, overwrite: bool=False) -> None:
"Export the ground truth LiDAR depth images for a given Kitti test split.\n\n :param depth_split: (str) Kitti depth split to load.\n :param mode: (str) Split mode to use. ... |
def save(file: Path, **kwargs) -> None:
'Save a list of arrays as a npz file.'
print(f'-> Saving to "{file}"...')
np.savez_compressed(file, **kwargs)
|
def export_syns(mode, save_stem: Optional[str]=None, overwrite: bool=False) -> None:
'Export the ground truth LiDAR depth images for SYNS.\n\n :param save_stem: (Optional[str]) Exported depth file stem (i.e. no suffix).\n :param overwrite: (bool) If `True`, overwrite existing exported files.\n '
prin... |
def main():
device = ops.get_device('cpu')
root = MODEL_ROOTS[(- 1)]
(exp, ckpt_name) = ('benchmark', 'last')
files = sorted((root / exp).glob(f'**/{ckpt_name}.ckpt'))
for f in files:
n = str(f).replace(str(root), '')
is_training = (f.parent / 'training').is_file()
is_finis... |
def load_dfs(files: dict[(str, Sequence[Path])]):
df = pd.json_normalize([io.load_yaml(f) for fs in files.values() for f in fs])
df.index = [f'{k}' for (k, fs) in files.items() for (i, _) in enumerate(fs)]
return df
|
def load_dfs(files: dict[(str, Sequence[Path])]):
dfs = [pd.json_normalize(io.load_yaml(f)) for fs in files.values() for f in fs]
df = pd.concat(dfs)
models = [f'{k}' for (k, fs) in files.items() for _ in fs]
df.index = pd.MultiIndex.from_product([models, dfs[0].index], names=['Model', 'Item'])
re... |
def save_metrics(file: Path, metrics: Sequence[Metrics]):
'Helper to save metrics. If any strings are present, save metrics separately. Otherwise save means.'
print(f'''
-> Saving results to "{file}"...''')
file.parent.mkdir(exist_ok=True, parents=True)
use_mean = all((isinstance(v, float) for v in me... |
def compute_eval_metrics(preds: NDArray, mode: str, cfg_file: Path) -> Sequence[Metrics]:
'Compute evaluation metrics from network predictions.\n Predictions must be unscaled (see `compute_eval_preds`).\n\n :param preds: (NDArray) (b, h, w) Precomputed unscaled network predictions.\n :param mode: (str) E... |
def save_preds(file: Path, preds: NDArray) -> None:
'Helper to save network predictions to a NPZ file. Required for submitted to the challenge.'
file.parent.mkdir(exist_ok=True, parents=True)
print(f'-> Saving network predictions to "{file}"...')
np.savez_compressed(file, pred=preds)
|
def compute_eval_preds(ckpt_file: Union[(str, Path)], cfg: dict, overwrite: bool=False) -> NDArray:
'Compute network predictions required for evaluation.\n\n The confing in `cfg_dataset` is equivalent to that used by the `Trainer`.\n Note that in most cases, additional outputs, such as depth or edges can be... |
def load_dfs(d):
df = pd.json_normalize([load_yaml(f) for fs in d.values() for f in fs])
df.index = [f'{m}' for (m, fs) in d.items() for (i, _) in enumerate(fs)]
return df
|
def main():
pd.set_option('display.max_rows', None, 'display.max_columns', None)
root = MODEL_ROOTS[(- 1)]
exp = 'benchmark'
split = 'eigen_benchmark'
mode = '*'
ckpt_name = 'best'
res = 'results'
fname = f'kitti_{split}_{ckpt_name}_{mode}.yaml'
metric_type = ([(- 1), (- 1), (- 1),... |
def main():
parser = ArgumentParser(description='Monocular depth trainer.')
parser.add_argument('--cfg-file', '-c', required=True, type=Path, help='Path to YAML config file to load.')
parser.add_argument('--cfg-default', '-d', default=None, type=Path, help='Default YAML config file to overwrite.')
par... |
def main():
parser = ArgumentParser(description='Monocular depth trainer.')
parser.add_argument('--cfg-file', '-c', required=True, type=Path, help='Path to YAML config file to load.')
parser.add_argument('--cfg-default', '-d', default=None, type=Path, help='Default YAML config file to overwrite.')
par... |
def get_augmentations(strong=True):
if strong:
tfm = TrivialAugmentWide()
else:
tfm = ka.ColorJitter(brightness=(0.8, 1.2), contrast=(0.8, 1.2), saturation=(0.8, 1.2), hue=((- 0.1), 0.1), p=1.0, same_on_batch=True, keepdim=True)
return tfm
|
class BaseDataset(ABC, Dataset):
'Base dataset class that all others should inherit from.\n\n The idea is to provide a common structure and format for data to follow. Additionally, provide some nice\n functionality and automation for the more boring stuff. Datasets are defined as providing the following dic... |
@register('kitti_lmdb')
class KittiRawLMDBDataset(KittiRawDataset):
"Kitti Depth based on the kitti_raw_sync dataset.\n\n LMDB variant of KittiRawDataset. This is designed to be a drop-in replacement that can help with IO load.\n As such, we only need to provide wrappers around the loading functions in the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.