code stringlengths 17 6.64M |
|---|
def test_dfa_models(model_architectures):
for (arch, input_size) in model_architectures:
check_model(models.dfa.__dict__[arch], input_size)
|
def test_usf_models(model_architectures):
for (arch, input_size) in model_architectures:
check_model(models.usf.__dict__[arch], input_size)
|
def test_brsf_models(model_architectures):
for (arch, input_size) in model_architectures:
check_model(models.brsf.__dict__[arch], input_size)
|
def test_frsf_models(model_architectures):
for (arch, input_size) in model_architectures:
check_model(models.frsf.__dict__[arch], input_size)
|
def test_biomodule_convert(dummy_net_constructor, mode_types):
for mode in mode_types:
dummy_net = dummy_net_constructor()
if (mode == 'dfa'):
with pytest.raises(ValueError, match='Model `output_dim` is required for Direct Feedback Alignment \\(dfa\\) mode'):
BioModule(... |
def test_module_converter_convert_dummy_net(dummy_net_constructor, mode_types):
for mode in mode_types:
dummy_net = dummy_net_constructor()
layers_to_convert = {str(type(dummy_net.conv1)): 1, str(type(dummy_net.fc)): 1}
w1 = dummy_net.conv1.weight.data
w2 = dummy_net.fc.weight.data... |
def test_module_converter_convert_dummy_net_copy_weights(dummy_net_constructor, mode_types):
for mode in mode_types:
dummy_net = dummy_net_constructor()
layers_to_convert = {str(type(dummy_net.conv1)): 1, str(type(dummy_net.fc)): 1}
w1 = dummy_net.conv1.weight.data
w2 = dummy_net.f... |
def test_module_converter_convert_dummy_net_layer_config(dummy_net_constructor, mode_types):
for mode in mode_types:
dummy_net = dummy_net_constructor()
layers_to_convert = {str(type(dummy_net.conv1)): 1, str(type(dummy_net.fc)): 1}
w1 = dummy_net.conv1.weight.data
w2 = dummy_net.f... |
def EmbedWord2Vec(walks, dimension):
time_start = time.time()
print('Creating embeddings.')
model = Word2Vec(walks, size=dimension, window=5, min_count=0, sg=1, workers=32, iter=1)
node_ids = model.wv.index2word
node_embeddings = model.wv.vectors
print('Embedding generation runtime: ', (time.t... |
def EmbedPoincare(relations, epochs, dimension):
model = PoincareModel(relations, size=dimension, workers=32)
model.train(epochs)
node_ids = model.index2entity
node_embeddings = model.vectors
return (node_ids, node_embeddings)
|
def TraverseAndSelect(length, num_walks, hyperedges, vertexMemberships, alpha=1.0, beta=0):
walksTAS = []
for hyperedge_index in hyperedges:
hyperedge = hyperedges[hyperedge_index]
walk_hyperedge = []
for _ in range(num_walks):
curr_vertex = random.choice(hyperedge['members... |
def SubsampleAndTraverse(length, num_walks, hyperedges, vertexMemberships, alpha=1.0, beta=0):
walksSAT = []
for hyperedge_index in hyperedges:
hyperedge = hyperedges[hyperedge_index]
walk_vertex = []
curr_vertex = random.choice(hyperedge['members'])
for _ in range(num_walks):
... |
def getFeaturesTrainingData():
i = 0
lists = []
labels = []
for vertex in G.nodes:
vertex_embedding_list = []
lists.append({'f': vertex_features[vertex].tolist()})
labels.append(vertex_labels[vertex])
X_unshuffled = []
for hlist in lists:
x = np.zeros((feature_d... |
def getTrainingData():
i = 0
lists = []
labels = []
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
for vertex in hyperedge['members']:
i += 1
if ((i % 100000) == 0):
print(i)
try:
ver... |
def getMLPTrainingData():
i = 0
lists = []
labels = []
maxi = 0
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
lists.append({'h': hyperedge_embeddings[hyperedge_ids.index(h)].tolist(), 'f': vertex_features[h].tolist()})
label = np.zeros((n... |
def getDSTrainingData():
i = 0
lists = []
labels = []
maxi = 0
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
for vertex in hyperedge['members']:
i += 1
if ((i % 100000) == 0):
print(i)
try:
... |
def hyperedgesTrain(X_train, Y_train, num_epochs):
deephyperedges_transductive_model.load_weights((('models/' + dataset_name) + '/deephyperedges_transductive_model.h5'))
history = deephyperedges_transductive_model.fit(X_train, Y_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, validation_split=0... |
def MLPTrain(X_MLP_transductive_train, Y_MLP_transductive_train, num_epochs):
MLP_transductive_model.load_weights((('models/' + dataset_name) + '/MLP_transductive_model.h5'))
history = MLP_transductive_model.fit(X_MLP_transductive_train, Y_MLP_transductive_train, epochs=num_epochs, batch_size=batch_size, shuf... |
def DeepSetsTrain(X_deepset_transductive_train, Y_deepset_transductive_train, num_epochs):
deepsets_transductive_model.load_weights((('models/' + dataset_name) + '/deepsets_transductive_model.h5'))
history = deepsets_transductive_model.fit(X_deepset_transductive_train, Y_deepset_transductive_train, epochs=num... |
def testModel(model, X_tst, Y_tst):
from sklearn.metrics import classification_report, accuracy_score
target_names = ['Neural Networks', 'Case Based', 'Reinforcement Learning', 'Probabilistic Methods', 'Genetic Algorithms', 'Rule Learning', 'Theory']
y_pred = model.predict(X_tst, batch_size=16, verbose=0)... |
def RunAllTests(percentTraining, num_times, num_epochs):
for i in range(num_times):
print('percent: ', percentTraining, ', iteration: ', (i + 1), ', model: deep hyperedges')
(X, Y) = getTrainingData()
(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, train_size=percentTraining, t... |
def getFeaturesTrainingData():
i = 0
lists = []
labels = []
for vertex in G.nodes:
vertex_embedding_list = []
lists.append({'f': vertex_features[vertex].tolist()})
labels.append(vertex_labels[vertex])
X_unshuffled = []
for hlist in lists:
x = np.zeros((feature_d... |
def getTrainingData():
i = 0
lists = []
labels = []
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
for vertex in hyperedge['members']:
i += 1
if ((i % 100000) == 0):
print(i)
try:
ver... |
def getMLPTrainingData():
i = 0
lists = []
labels = []
maxi = 0
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
lists.append({'h': hyperedge_embeddings[hyperedge_ids.index(h)].tolist(), 'f': vertex_features[h].tolist()})
label = np.zeros((n... |
def getDSTrainingData():
i = 0
lists = []
labels = []
maxi = 0
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
for vertex in hyperedge['members']:
i += 1
if ((i % 100000) == 0):
print(i)
try:
... |
def hyperedgesTrain(X_train, Y_train):
deephyperedges_transductive_model.load_weights((('models/' + dataset_name) + '/deephyperedges_transductive_model.h5'))
history = deephyperedges_transductive_model.fit(X_train, Y_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, validation_split=0, verbose=0)... |
def MLPTrain(X_MLP_transductive_train, Y_MLP_transductive_train):
MLP_transductive_model.load_weights((('models/' + dataset_name) + '/MLP_transductive_model.h5'))
history = MLP_transductive_model.fit(X_MLP_transductive_train, Y_MLP_transductive_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, va... |
def DeepSetsTrain(X_deepset_transductive_train, Y_deepset_transductive_train):
deepsets_transductive_model.load_weights((('models/' + dataset_name) + '/deepsets_transductive_model.h5'))
history = deepsets_transductive_model.fit(X_deepset_transductive_train, Y_deepset_transductive_train, epochs=num_epochs, bat... |
def testModel(model, X_tst, Y_tst):
from sklearn.metrics import classification_report, accuracy_score
target_names = target_names = ['Type-1 Diabetes', 'Type-2 Diabetes', 'Type-3 Diabetes']
y_pred = model.predict(X_tst, batch_size=16, verbose=0)
finals_pred = []
finals_test = []
for p in y_pre... |
def RunAllTests(percentTraining, num_times=10):
for i in range(num_times):
print('percent: ', percentTraining, ', iteration: ', (i + 1), ', model: deep hyperedges')
(X, Y) = getTrainingData()
(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, train_size=percentTraining, test_size=... |
def smooth(scalars, weight):
last = scalars[0]
smoothed = list()
for point in scalars:
smoothed_val = ((last * weight) + ((1 - weight) * point))
smoothed.append(smoothed_val)
last = smoothed_val
return smoothed
|
def plot(deephyperedges_directory, MLP_directory, deepsets_directory, metric, dataset):
dhe_metrics = pd.read_csv(deephyperedges_directory)
x = []
y = []
for (index, row) in dhe_metrics.iterrows():
x.append(float(row['Step']))
y.append(float(row['Value']))
mlp_metrics = pd.read_csv... |
def plotAll(dataset):
metric = 'run-.-tag-categorical_accuracy.csv'
deephyperedges_directory = ((('images/paper/' + dataset) + '/deephyperedges/') + metric)
MLP_directory = ((('images/paper/' + dataset) + '/MLP/') + metric)
deepsets_directory = ((('images/paper/' + dataset) + '/deepsets/') + metric)
... |
class Boco():
def __init__(self, name):
self.name = name
def validate(self):
assert self.computeLoss, 'You need to specify a function to compute the loss'
|
class Neumann(Boco):
def __init__(self, sampler, name='neumann'):
super().__init__(name)
self.vars = sampler.vars
self.sampler = sampler
def sample(self, n_samples=None):
return self.sampler.sample(n_samples)
def validate(self, inputs, outputs):
super().validate(... |
class Periodic(Boco):
def __init__(self, sampler, sampler1, sampler2, name='periodic'):
super().__init__(name)
self.sampler = sampler
self.sampler1 = sampler1
self.sampler2 = sampler2
inputs1 = tuple(self.sampler1.sample(1).keys())
inputs2 = tuple(self.sampler2.sam... |
class Dataset(torch.utils.data.Dataset):
def __init__(self, data, device='cpu'):
mesh = np.stack(np.meshgrid(*data), (- 1)).reshape((- 1), len(data))
self.X = torch.from_numpy(mesh).float().to(device)
def __len__(self):
return len(self.X)
def __getitem__(self, ix):
retur... |
class Mesh():
def __init__(self, data, device='cpu'):
assert isinstance(data, dict), 'you must pass a dict with your data'
(self.vars, data) = (tuple(data.keys()), data.values())
self.dataset = Dataset(data, device)
self.device = device
def build_dataloader(self, batch_size=N... |
class History():
def __init__(self, precision=5):
self.history = {}
self.current = {}
self.precision = precision
def add(self, d):
for (name, metric) in d.items():
if (not (name in self.history)):
self.history[name] = []
self.history[na... |
class Sine(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return torch.sin(x)
|
def block(i, o):
fc = torch.nn.Linear(i, o)
return torch.nn.Sequential(Sine(), torch.nn.Linear(i, o))
|
class MLP(torch.nn.Module):
def __init__(self, inputs, outputs, layers, neurons):
super().__init__()
fc_in = torch.nn.Linear(inputs, neurons)
fc_hidden = [block(neurons, neurons) for layer in range((layers - 1))]
fc_out = block(neurons, outputs)
self.mlp = torch.nn.Sequent... |
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
|
class PDE():
def __init__(self, inputs, outputs):
if isinstance(inputs, str):
inputs = tuple(inputs)
if isinstance(outputs, str):
outputs = tuple(outputs)
checkIsListOfStr(inputs)
checkIsListOfStr(outputs)
checkUnique(inputs)
checkUnique(out... |
class BaseSampler():
def __init__(self, data, n_samples=1, device='cpu'):
assert isinstance(data, dict), 'you must pass a dict with your data'
self.device = device
self.data = data
self.vars = tuple(data.keys())
self.n_samples = n_samples
def _sample(self, n_samples=N... |
class RandomSampler(BaseSampler):
def __init__(self, data, n_samples=1, device='cpu'):
super().__init__(data, n_samples, device)
for (var, lims) in data.items():
if isinstance(lims, list):
assert (len(lims) == 2), 'you must pass a list with the min and max limits'
... |
def checkIsListOfStr(l):
'Make sure that l is a list containing only strings'
if isinstance(l, tuple):
for i in l:
if (not isinstance(i, str)):
raise Exception((str(i) + ' must be a string'))
|
def checkUnique(l):
'Make sure that l does not contain repeated elements'
for (i, item1) in enumerate(l):
for (j, item2) in enumerate(l):
if ((i != j) and (item1 == item2)):
raise Exception(('Repeated item ' + str(item1)))
|
def checkNoRepeated(l1, l2):
'Make sure there are no repeated elements in both lists'
for i in l1:
if (i in l2):
raise Exception(('Repeated item ' + str(i)))
|
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_ddad(mode, save_stem: ty.N[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 '
print(f'... |
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_diode(mode: str, scene: str, save_stem: ty.N[str]=None, overwrite: bool=False) -> None:
"Export the ground truth LiDAR depth images for SYNS.\n\n :param mode: (str) Split mode to use. {'val'}\n :param scene: (str) Scene type to use. {'outdoor', 'indoor'}\n :param save_stem: (Optional[str]) Exp... |
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_mannequin(mode: str, save_stem: ty.N[str]=None, overwrite: bool=False) -> None:
'Export the ground truth LiDAR depth images for SYNS.\n\n :param mode: (str) Split mode to use.\n :param save_stem: (Optional[str]) Exported depth file stem (i.e. no suffix).\n :param overwrite: (bool) If `True`, o... |
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_nyud(mode: str, save_stem: str, overwrite: bool=False) -> None:
"Export the ground truth LiDAR depth images for NYUD.\n\n :param mode: (str) Split mode to use. {'test'}\n :param save_stem: (str) Exported depth file stem (i.e. no suffix).\n :param overwrite: (bool) If `True`, overwrite existing... |
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_sintel(mode, save_stem: str=None, overwrite: bool=False) -> None:
'Export the ground-truth synthetic depth images for Sintel.\n\n :param mode: (str) Split mode to use.\n :param save_stem: (str) Exported depth file stem (i.e. no suffix).\n :param overwrite: (bool) If `True`, overwrite existing ... |
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_tum(mode: str, save_stem: str, overwrite: bool=False) -> None:
'Export the ground-truth depth maps for TUM.\n\n :param mode: (str) Split mode to use.\n :param save_stem: (str) Exported depth file stem (i.e. no suffix).\n :param overwrite: (bool) If `True`, overwrite existing exported files.\n ... |
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 dataset.'
(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 process_dataset(src_dir: Path, dst_dir: Path, overwrite: bool=False) -> None:
'Process the entire MannequinChallenge dataset.'
print(f"-> Copying splits directory '{(dst_dir / 'splits')}'...")
shutil.copytree((src_dir / 'splits'), (dst_dir / 'splits'), dirs_exist_ok=True)
for mode in ('train', 'va... |
def process_mode(src_dir: Path, dst_dir: Path, overwrite: bool=False) -> None:
'Process a full MannequinChallenge mode, e.g. train or val.'
calibs = {d.stem: mc.load_info(dst_dir.stem, d.stem) for d in tqdm(src_dir.iterdir())}
export_intrinsics(src_dir, (dst_dir / 'intrinsics'), calibs, overwrite)
exp... |
def export_intrinsics(src_dir: Path, dst_dir: Path, calibs: dict[(str, dict)], overwrite: bool=False) -> None:
'Create camera intrinsics LMDB.'
if ((not overwrite) and dst_dir.is_dir()):
print(f"-> Intrinsics already exist for dir '{src_dir.stem}'")
return
all_Ks = {}
for (k, v) in tqd... |
def export_shapes(src_dir: Path, dst_dir: Path, calibs: dict[(str, dict)], overwrite: bool=False) -> None:
'Create image shapes LMDB.'
if ((not overwrite) and dst_dir.is_dir()):
print(f"-> Shapes already exist for dir '{src_dir.stem}'")
return
all_shapes = {}
for (k, v) in tqdm(calibs.... |
def export_poses(src_dir: Path, dst_dir: Path, calibs: dict[(str, dict)], overwrite: bool=False) -> None:
'Create camera poses LMDB.'
if ((not overwrite) and dst_dir.is_dir()):
print(f"-> Poses already exist for dir '{src_dir.stem}'")
return
print(f'-> Exporting poses for dir {src_dir.stem... |
def export_images(src_dir: Path, dst_dir: Path, overwrite: bool=False) -> None:
'Create images LMDB.'
if ((not overwrite) and dst_dir.is_dir()):
print(f"-> Images already exist for dir '{src_dir.stem}'")
return
print(f"-> Exporting images for dir '{src_dir.stem}'")
files = {f'{d.stem}/... |
def process_dataset(overwrite=False):
(src, dst) = (PATHS['slow_tv'], PATHS['slow_tv_lmdb'])
print(f"-> Copying splits directory '{(dst / 'splits')}'...")
shutil.copytree((src / 'splits'), (dst / 'splits'), dirs_exist_ok=True)
export_intrinsics(dst, overwrite)
args = [((src / seq), dst, overwrite)... |
def export_seq(path: Path, save_root: Path, overwrite: bool=False) -> None:
'Convert SlowTV video into an LMDB.'
seq = path.stem
out_dir = (save_root / seq)
if ((not overwrite) and out_dir.is_dir()):
print(f'-> Skipping directory "{out_dir}"...')
return
print(f'-> Export LMDB for d... |
def export_intrinsics(save_root: Path, overwrite: bool=False) -> None:
'Export SlowTV intrinsics as an LMDB.'
out_dir = (save_root / 'calibs')
if ((not overwrite) and out_dir.is_dir()):
print(f'-> Skipping LMDB calibrations...')
return
print(f"""-> Exporting intrinsics "{(save_root / '... |
def read_array(path):
with open(path, 'rb') as fid:
(width, height, channels) = np.genfromtxt(fid, delimiter='&', max_rows=1, usecols=(0, 1, 2), dtype=int)
fid.seek(0)
num_delimiter = 0
byte = fid.read(1)
while True:
if (byte == b'&'):
num_delimi... |
def export_split(split, src, dst, overwrite=False):
print(f'-> Exporting "{split}" split...')
dst = (dst / split)
io.mkdirs(dst)
seqs = io.get_dirs((src / split))
dsts = [(dst / s.stem) for s in seqs]
ovs = [overwrite for _ in seqs]
with Pool(8) as p:
for _ in tqdm(p.imap_unordered... |
def export_seq(args):
try:
(src, dst, overwrite) = args
depth_dir = (dst / 'depths')
if ((not overwrite) and depth_dir.is_dir()):
print(f'-> Skipping "{src.parent.stem}" sequence "{src.stem}"...')
return
print(f'-> Exporting "{src.parent.stem}" sequence "{sr... |
def main(root):
dst = (root / 'colmap')
io.mkdirs(dst)
splits = ['test']
fails = {}
for s in tqdm(splits):
fails[s] = export_split(s, root, dst, overwrite=False)
print(fails)
|
def main(src, dst):
TARGET_DIR = 'depth_benchmark'
(K_DEPTH, K_RAW) = (src, dst)
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_ok=True)
for mode in ('train',... |
def loadmat(file):
'Conflict with specific matfile versions?'
f = h5py.File(file)
arr = {k: np.array(v) for (k, v) in f.items()}
return arr
|
def export_split(mode, idxs, data, dst):
img_dir = ((dst / mode) / 'rgb')
depth_dir = ((dst / mode) / 'depth')
split_file = ((dst / 'splits') / f'{mode}_files.txt')
io.mkdirs(img_dir, depth_dir, split_file.parent)
with open(split_file, 'w') as f:
for i in tqdm(idxs):
i -= 1
... |
def main(dst):
data_file = (dst / 'nyu_depth_v2_labeled.mat')
split_file = (dst / 'splits.mat')
data = loadmat(data_file)
splits = sio.loadmat(split_file)
export_split('train', splits['trainNdxs'].squeeze(), data, dst)
export_split('test', splits['testNdxs'].squeeze(), data, dst)
data_file... |
def save_settings(**kwargs):
io.write_yaml(((PATHS['slow_tv'] / 'splits') / 'config.yaml'), kwargs)
|
def export_scene(args):
(vid_file, cat) = args
seq = vid_file.stem
seq_dir = (PATHS['slow_tv'] / seq)
stv.extract_frames(vid_file, save_dir=seq_dir, fps=fps, trim_start=trim, n_keep=n_keep, per_interval=per_interval, overwrite=overwrite)
seeds = [42, 195, 335, 558, 724]
for seed in seeds:
... |
def main(args):
if write_settings:
save_settings(fps=fps, trim=trim, data_scale=data_scale, n_keep=n_keep, per_interval=per_interval, p_train=p_train, val_skip=val_skip, n_colmap_imgs=n_colmap_imgs, colmap_interval=colmap_interval)
cats = stv.load_categories(subcats=False)
video_files = io.get_fil... |
def main(dst):
print(f'-> Copying splits to "{dst}"...')
shutil.copytree((REPO_ROOT / 'api/data/splits'), dst, dirs_exist_ok=True)
(dst / FILE.name).unlink()
|
def save_metrics(file: Path, metrics: ty.U[(Metrics, ty.S[Metrics])]):
'Helper to save metrics.'
LOGGER.info(f'Saving results to "{file}"...')
file.parent.mkdir(exist_ok=True, parents=True)
write_yaml(file, metrics, mkdir=True)
|
def compute_eval_metrics(preds: ty.A, cfg_file: Path, align_mode: ty.U[(str, float)], nproc: ty.N[int]=None, max_items: ty.N[int]=None) -> tuple[(Metrics, ty.S[Metrics])]:
'Compute evaluation metrics from scaleless network disparities (see `compute_eval_preds`).\n\n :param preds: (NDArray) (b, h, w) Precompute... |
def save_preds(file: Path, preds: ty.A) -> None:
'Helper to save network predictions to a NPZ file. Required for submitted to the challenge.'
io.mkdirs(file.parent)
logging.info(f"Saving network predictions to '{file}'...")
np.savez_compressed(file, pred=preds)
|
def compute_preds(cfg: dict, ckpt: str, cfg_model: ty.N[list[Path]], device: ty.N[str], overwrite: bool) -> ty.A:
'Compute predictions for a given dataset and network cfg.\n\n `ckpt` can be provided as:\n - Path: Path to a pretrained checkpoint trained using the benchmark repository.\n - Name: Na... |
def get_models(root: Path, exp: str, dataset: str, ckpt: str='last', mode: str='*', res: str='results', models: ty.N[list[str]]=None, tag: str='') -> tuple[(dict[(str, list[Path])], list[str])]:
"Find all models and files associated with a particular experiment.\n NOTE: Parameters can use regex expressions, bu... |
def load_dfs(files: dict[(str, list[Path])]) -> pd.DataFrame:
'Load dict of YAML files into a single dataframe.\n\n :param files: (dict[str, list[Path]]) List of files for each model.\n :return: (DataFrame) Loaded dataframe, index based on the model key and a potential item number.\n '
dfs = [pd.json... |
def filter_df(df: pd.DataFrame) -> tuple[(pd.DataFrame, ty.S[int])]:
'Preprocess dataframe to include only AbsRel and (F-Score or delta) metrics.'
(metrics, metric_type) = (['AbsRel'], [(- 1)])
(delta, delta_legacy) = ('$\\delta_{.25}$', '$\\delta < 1.25$')
(f, f_legacy) = ('F-Score (10)', 'F-Score')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.