repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
coocmap
coocmap-main/experiments/test_accvdim.py
import os import subprocess from dataclasses import dataclass import lzma import wandb import argparse import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # from baselines import VecMap os.environ['WANDB_IGNORE_GLOBS'] = 'lan1/*,lan2/*' os.environ["OMP_NU...
9,329
34.340909
136
py
coocmap
coocmap-main/experiments/test_dropclip.py
import os import subprocess from dataclasses import dataclass import lzma import wandb import argparse import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # from baselines import VecMap os.environ['WANDB_IGNORE_GLOBS'] = 'lan1/*,lan2/*' os.environ["OMP_NU...
9,111
34.317829
136
py
coocmap
coocmap-main/experiments/test_accvsize.py
import os import subprocess from dataclasses import dataclass import lzma import wandb import argparse import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # from baselines import VecMap os.environ['WANDB_IGNORE_GLOBS'] = 'lan1/*,lan2/*' os.environ["OMP_NU...
6,921
32.439614
136
py
coocmap
coocmap-main/experiments/test_coocmap.py
import os from dataclasses import dataclass import wandb import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # experimental parameters defaults = dict( lan1='./europarl-v7.hu-en.en', lan2='./europarl-v7.hu-en.hu', eval='en-hu', size1=20, ...
5,771
32.172414
136
py
coocmap
coocmap-main/experiments/test_matching.py
import os import subprocess from dataclasses import dataclass import lzma import wandb import argparse import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # from baselines import VecMap os.environ['WANDB_IGNORE_GLOBS'] = 'lan1/*,lan2/*' os.environ["OMP_NU...
6,598
29.836449
136
py
coocmap
coocmap-main/experiments/test_accvsize_cooc.py
import os import subprocess from dataclasses import dataclass import lzma import wandb import argparse import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # from baselines import VecMap os.environ['WANDB_IGNORE_GLOBS'] = 'lan1/*,lan2/*' os.environ["OMP_NU...
9,439
33.578755
136
py
MateriAppsInstaller
MateriAppsInstaller-master/docs/sphinx/en/source/conf.py
# -*- coding: utf-8 -*- # # MateriApps-Installer documentation build configuration file, created by # sphinx-quickstart on Sun May 1 14:29:22 2020. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated...
5,684
28.455959
79
py
MateriAppsInstaller
MateriAppsInstaller-master/docs/sphinx/ja/source/conf.py
# -*- coding: utf-8 -*- # # MateriApps-Installer documentation build configuration file, created by # sphinx-quickstart on Sun May 1 14:29:22 2020. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated...
5,686
28.466321
79
py
MateriAppsInstaller
MateriAppsInstaller-master/misc/make_readme.py
#!/usr/bin/python # coding: utf-8 import h5py import glob import os import re dirs_apps = [x for x in glob.glob("./*") if os.path.isdir(x)] dict_apps = {} #get app name for dir_name in dirs_apps: dict_apps[dir_name[2:]] = dir_name print(dict_apps) apps_table = {"komega":"Kω","alps":"ALPS","xtapp":"xTAPP", ...
1,555
34.363636
99
py
MateriAppsInstaller
MateriAppsInstaller-master/misc/make_rst.py
#!/usr/bin/python # coding: utf-8 import h5py import glob import os import re import subprocess path_to_sphinx = "../docs/sphinx/en/source/appendix/" dirs_apps = [x for x in glob.glob("./*") if os.path.isdir(x)] dirs_apps.sort() print(dirs_apps) cwd_path = os.getcwd() path_to_sphinx = os.path.join(cwd_path, path_to_...
1,536
28
89
py
MateriAppsInstaller
MateriAppsInstaller-master/misc/make_rst_ja.py
#!/usr/bin/python # coding: utf-8 import h5py import glob import os import re import subprocess path_to_sphinx_ja = "../docs/sphinx/ja/source/appendix/" dirs_apps = [x for x in glob.glob("./*") if os.path.isdir(x)] dirs_apps.sort() print(dirs_apps) cwd_path = os.getcwd() path_to_sphinx_ja = os.path.join(cwd_path, pa...
1,546
28.188679
92
py
MateriAppsInstaller
MateriAppsInstaller-master/misc/get_info_ja.py
import requests from bs4 import BeautifulSoup import re import time import h5py def get_retry(url, retry_times, errs): for t in range(retry_times + 1): r = requests.get(url) if t < retry_times: if r.status_code in errs: time.sleep(2) continue retu...
2,705
40
127
py
MateriAppsInstaller
MateriAppsInstaller-master/misc/make_readme_ja.py
#!/usr/bin/python # coding: utf-8 import h5py import glob import os import re dirs_apps = [x for x in glob.glob("./*") if os.path.isdir(x)] dict_apps = {} #get app name for dir_name in dirs_apps: dict_apps[dir_name[2:]] = dir_name print(dict_apps) apps_table = {"alps":"ALPS","xtapp":"xTAPP", "komega":"Kω", ...
1,591
34.377778
99
py
MateriAppsInstaller
MateriAppsInstaller-master/misc/get_info.py
import requests from bs4 import BeautifulSoup import re import time import h5py def get_retry(url, retry_times, errs): for t in range(retry_times + 1): r = requests.get(url) if t < retry_times: if r.status_code in errs: time.sleep(2) continue retu...
2,664
41.301587
127
py
harmonic
harmonic-main/setup.py
import sys import os import shutil import setuptools from setuptools import setup, Extension from Cython.Distutils import build_ext from Cython.Build import cythonize import numpy # clean previous build for root, dirs, files in os.walk("./harmonic/", topdown=False): for name in dirs: if (name == "build"):...
3,064
28.471154
109
py
harmonic
harmonic-main/examples/gaussian_diagcov.py
import numpy as np import sys sys.path.append(".") import harmonic as hm import emcee import scipy.special as sp import time import matplotlib.pyplot as plt import utils import gc def ln_analytic_evidence(ndim, cov): """Compute analytic ln_e evidence. Args: ndim: Dimensionality of the multivariate...
10,229
34.275862
92
py
harmonic
harmonic-main/examples/normal_gamma.py
import numpy as np import sys import emcee import scipy.special as sp import time import matplotlib.pyplot as plt from functools import partial sys.path.append(".") import harmonic as hm sys.path.append("examples") import utils def ln_likelihood(x_mean, x_std, x_n, mu, tau): """Compute log_e of likelihood. Args: ...
15,817
29.655039
79
py
harmonic
harmonic-main/examples/plot_realisations.py
import numpy as np import matplotlib.pyplot as plt import argparse import os import sys sys.path.append("examples") import utils savefigs = True # Parse arguments. parser = argparse.ArgumentParser("Create violin plot of inverse evidences" + "from many realisations") parser.add_argument('filename_realisations', m...
2,344
38.083333
95
py
harmonic
harmonic-main/examples/rosenbrock.py
import numpy as np import sys import emcee import time import matplotlib.pyplot as plt from functools import partial sys.path.append(".") import harmonic as hm sys.path.append("examples") import utils def ln_prior_uniform(x, xmin=-10.0, xmax=10.0, ymin=-5.0, ymax=15.0): """Compute log_e of uniform prior. Ar...
17,503
37.135076
87
py
harmonic
harmonic-main/examples/utils.py
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.colors import LightSource from mpl_toolkits.mplot3d import Axes3D import corner from getdist import plots, MCSamples import getdist def plot_corner(samples, labels=None): """ Plot triangle plot of marginalised distribu...
9,458
29.220447
80
py
harmonic
harmonic-main/examples/rastrigin.py
import numpy as np import sys import emcee import time import matplotlib.pyplot as plt from functools import partial sys.path.append(".") import harmonic as hm sys.path.append("examples") import utils def ln_prior_uniform(x, xmin=-6.0, xmax=6.0, ymin=-6.0, ymax=6.0): """Compute log_e of uniform prior. Args:...
16,415
37.35514
87
py
harmonic
harmonic-main/examples/radiata_pine.py
import numpy as np import sys import emcee import scipy.special as sp import time import matplotlib.pyplot as plt from functools import partial sys.path.append(".") import harmonic as hm sys.path.append("examples") import utils def ln_likelihood(y, x, n, alpha, beta, tau): """Compute log_e of Radiata Pine likeli...
20,255
29.690909
96
py
harmonic
harmonic-main/examples/pima_indian.py
import numpy as np import sys import emcee import scipy.special as sp import time import matplotlib.pyplot as plt from functools import partial sys.path.append(".") import harmonic as hm sys.path.append("examples") import utils def ln_likelihood(y, theta, x): """Compute log_e of Pima Indian likelihood. Args...
13,648
33.467172
96
py
harmonic
harmonic-main/examples/gaussian_nondiagcov.py
import numpy as np import sys import emcee import time import matplotlib.pyplot as plt from functools import partial from matplotlib import cm sys.path.append(".") import harmonic as hm sys.path.append("examples") import utils def ln_analytic_evidence(ndim, cov): """Compute analytic evidence for nD Gaussian. ...
14,359
37.810811
87
py
harmonic
harmonic-main/tests/test_evidence.py
import pytest import numpy as np from scipy.stats import kurtosis import harmonic.chains as ch import harmonic.model as md import harmonic.evidence as cbe import harmonic.utils as utils def test_constructor(): nchains = 100 ndim = 1000 domain = [np.array([1e-1, 1e1])] sphere = md.HyperSphere(ndim, do...
12,445
31.83905
104
py
harmonic
harmonic-main/tests/test_logs.py
import harmonic.logs as lg import pytest import numpy as np def test_incorrect_log_yaml_path(): dir_name = "random/incorrect/filepath/" # Check cannot add samples with different ndim. with pytest.raises(ValueError): lg.setup_logging(custom_yaml_path=dir_name) def test_general_logging(): lg.se...
485
19.25
51
py
harmonic
harmonic-main/tests/__init__.py
0
0
0
py
harmonic
harmonic-main/tests/test_model.py
import pytest import harmonic.model as md import numpy as np def test_hyper_sphere_constructor(): with pytest.raises(ValueError): sphere = md.HyperSphere(2, [np.array([0.5,1.5])], hyper_parameters=[5]) with pytest.raises(ValueError): sphere = md.HyperSphere(2, [np.array([0.5,1.5]),np.array([0....
26,554
32.360553
144
py
harmonic
harmonic-main/tests/test_chains.py
import harmonic.chains as ch import pytest import numpy as np def test_constructor(): ndim = 0 with pytest.raises(ValueError): chains = ch.Chains(ndim) ndim = 3 chains = ch.Chains(ndim) assert chains.ndim == ndim assert chains.nchains == 0 assert chains.nsampl...
21,450
34.456198
80
py
harmonic
harmonic-main/tests/test_utils.py
import numpy as np import harmonic.utils as utils import harmonic.chains as ch import harmonic.model as md import pytest def test_split_data(): ndim = 5 nsamples = 100 nchains = 200 training_proportion = 0.5 chains_all = ch.Chains(ndim) np.random.seed(3) samples = np....
7,985
38.339901
108
py
harmonic
harmonic-main/docs/conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
6,728
29.586364
100
py
harmonic
harmonic-main/harmonic/__init__.py
from .chains import Chains from . import evidence from .evidence import Evidence, Shifting from . import model from . import utils from . import logs
150
20.571429
40
py
harmonic
harmonic-main/harmonic/logs.py
import os import logging.config import logging import yaml import harmonic import colorlog def setup_logging(custom_yaml_path=None, default_level=logging.DEBUG): """initialise and configure logging. Should be called at the beginning of code to initialise and configure the desired logging level. Loggi...
3,175
29.538462
83
py
DeepGAR
DeepGAR-main/test.py
from common import utils from collections import defaultdict from datetime import datetime from sklearn.metrics import roc_auc_score, confusion_matrix from sklearn.metrics import precision_recall_curve, average_precision_score import torch USE_ORCA_FEATS = False # whether to use orca motif counts along with embeddings...
8,369
46.828571
115
py
DeepGAR
DeepGAR-main/config.py
import argparse from common import utils def parse_encoder(parser, arg_str=None): enc_parser = parser.add_argument_group() #utils.parse_optimizer(parser) enc_parser.add_argument('--conv_type', type=str, help='type of convolution') enc_parser.add_argument('--method_type', type=s...
3,166
42.986111
73
py
DeepGAR
DeepGAR-main/hyp_search.py
def parse_encoder(parser): parser.opt_list('--conv_type', type=str, tunable=True, options=['GIN', 'SAGE'],#, 'GCN'],#, 'GAT'], help='type of model') parser.opt_list('--skip', type=str, tunable=True, options=['all', 'last'],#, 'GCN'],#, 'GAT'], help='type of mode...
3,927
46.325301
82
py
DeepGAR
DeepGAR-main/deepgar.py
HYPERPARAM_SEARCH = False HYPERPARAM_SEARCH_N_TRIALS = None # how many grid search trials to run # (set to None for exhaustive search) import argparse from itertools import permutations import pickle from queue import PriorityQueue import os import random import time import ne...
31,768
39.31599
205
py
DeepGAR
DeepGAR-main/common/utils.py
from collections import defaultdict, Counter from deepsnap.graph import Graph as DSGraph from deepsnap.batch import Batch from deepsnap.dataset import GraphDataset import torch import torch.optim as optim import torch_geometric.utils as pyg_utils from torch_geometric.data import DataLoader import networkx as nx import...
11,535
39.477193
120
py
DeepGAR
DeepGAR-main/common/data.py
import os import pickle import random from deepsnap.graph import Graph as DSGraph from deepsnap.batch import Batch from deepsnap.dataset import GraphDataset, Generator import networkx as nx import numpy as np from sklearn.manifold import TSNE import torch import torch.multiprocessing as mp import torch.nn.functional a...
24,005
44.20904
159
py
DeepGAR
DeepGAR-main/common/models.py
"""Defines all graph embedding models""" from functools import reduce import random import networkx as nx import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch_geometric.nn as pyg_nn import torch_geometric.utils as pyg_utils from common import utils from common import feat...
16,350
41.250646
191
py
nepali-ner
nepali-ner-master/main.py
#!/usr/bin/env python3 ''' Main file Author: Oyesh Mann Singh How to run: python main.py -k 1 -d cpu ''' import os import argparse import shutil import warnings from utils.dataloader import Dataloader import utils.utilities as utilities import utils.splitter as splitter from tqdm import tqdm ...
7,120
32.909524
120
py
nepali-ner
nepali-ner-master/app.py
""" Needs code structuring Date - 08/14/2020 """ import torch import logging import sys from flask import Flask, render_template, request from utils.dataloader2 import Dataloader from models.models import LSTMTagger from config.config import Configuration app = Flask(__name__) def get_logger(): logger =...
2,497
25.294737
98
py
nepali-ner
nepali-ner-master/wsgi.py
from app.main import app if __name__ == "__main__": app.run()
70
13.2
27
py
nepali-ner
nepali-ner-master/train.py
#!/usr/bin/env python3 ''' Trainer Author: Oyesh Mann Singh ''' import os from utils.eval import Evaluator from tqdm import tqdm, tqdm_notebook, tnrange import torch import torch.nn as nn import torch.optim as optim from sklearn.metrics import accuracy_score torch.manual_seed(163) tqdm.pandas(desc='Progress'...
8,092
34.034632
146
py
nepali-ner
nepali-ner-master/config/config.py
''' Configuration Parser Author: Oyesh Mann Singh Date 10/15/2019 ''' import os import logging from configparser import ConfigParser class Configuration(ConfigParser): def __init__(self, config_file, logger): super().__init__() config = ConfigParser(allow_no_value=True) config...
5,095
25.821053
75
py
nepali-ner
nepali-ner-master/models/models.py
''' Models Author: Oyesh Mann Singh ''' import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from tqdm import tqdm from uniseg.graphemecluster import grapheme_clusters tqdm.pandas(desc='Progress') class LSTMTagger(nn.Module): def __init__(self, config, dataloader): ...
9,650
37.146245
104
py
nepali-ner
nepali-ner-master/utils/conll_preprocessor.py
#!/usr/bin/env python3 ''' Removes CHUNK column from CoNLL file Author: Oyesh Mann Singh Date: 10/16/2019 ''' import os import argparse import pandas as pd import numpy as np import csv import shutil def preprocess(input_file, output_file): with open(input_file,'r', encoding='utf-8') as in_file, open(...
1,280
28.113636
119
py
nepali-ner
nepali-ner-master/utils/conlleval_perl.py
#!/usr/bin/python #### Original Perl Script # conlleval: evaluate result of processing CoNLL-2000 shared task # usage: conlleval [-l] [-r] [-d delimiterTag] [-o oTag] < file # README: http://cnts.uia.ac.be/conll2000/chunking/output.html # options: l: generate LaTeX output for tables like in # ...
12,636
41.123333
168
py
nepali-ner
nepali-ner-master/utils/column_extractor.py
#!/usr/bin/env python3 ''' Converts 3 columns into 2 columns Author: Oyesh Mann Singh Date: 10/16/2019 ''' import os import argparse import pandas as pd import numpy as np import csv import shutil def preprocess(input_file, output_file): with open(input_file,'r', encoding='utf-8') as in_file, open(out...
1,293
28.409091
134
py
nepali-ner
nepali-ner-master/utils/stemmer.py
#!/usr/bin/env python3 ''' Stems the postpositions in given dataset brute-force approach Author: Oyesh Mann Singh Date: 12/08/2019 ''' import os import argparse import pandas as pd import numpy as np import csv import shutil def stem(pp_file, input_file, output_file): stemmers = open(pp_file...
2,168
29.985714
135
py
nepali-ner
nepali-ner-master/utils/data_checker.py
#!/usr/bin/env python3 # Simple program to check data statistics of NER file # Input file should be in standard Stanford format # Outputs number of PER, LOC, ORG tags import csv import argparse import os from collections import Counter def main(): parser = argparse.ArgumentParser(description='Input file name') p...
1,316
25.34
64
py
nepali-ner
nepali-ner-master/utils/dataloader2.py
#!/usr/bin/env python3 ''' NER Dataloader Author: Oyesh Mann Singh Date: 10/14/2019 Data format: <WORD> <NER-tag> ''' import os import pickle from torchtext import data, vocab from torchtext.datasets import SequenceTaggingDataset class Dataloader(): def __init__(self, config, k): ...
2,467
27.367816
99
py
nepali-ner
nepali-ner-master/utils/bio_converter.py
#!/usr/bin/python import os import sys def main(): label_list = ['PER', 'ORG', 'LOC'] with open(sys.argv[1], 'r', encoding='utf-8') as in_file, open(sys.argv[2], 'w', encoding='utf-8') as out_file: prev_label = ' ' for i1, row in enumerate(in_file): row = row.strip().split() ...
821
29.444444
115
py
nepali-ner
nepali-ner-master/utils/dataloader.py
#!/usr/bin/env python3 ''' NER Dataloader Author: Oyesh Mann Singh Date: 10/14/2019 Data format: <WORD> <NER-tag> ''' import os import numpy as np import pickle import torch from torchtext import data from torchtext import vocab from torchtext.datasets import SequenceTaggingDataset from un...
6,000
34.720238
116
py
nepali-ner
nepali-ner-master/utils/splitter.py
#!/usr/bin/env python3 ''' Splits dataset into train/test/val Author: Oyesh Mann Singh Date: 10/16/2019 ''' import os import argparse import pandas as pd import numpy as np import csv import shutil try: import utilities as utilities except ImportError: import utils.utilities as utilities MAX_SEQ_...
10,065
36.007353
201
py
nepali-ner
nepali-ner-master/utils/utilities.py
# -*- coding: UTF-8 -*- import datetime import io import logging import os import sys import time def get_logger(filepath): """ Gets a logger instance to write the program info and errors to. @params: filepath (string): File path to the log output. @returns: Instanc...
1,451
29.25
97
py
nepali-ner
nepali-ner-master/utils/conll_eval.py
#!/usr/bin/python """ This script applies to IOB2 or IOBES tagging scheme. If you are using a different scheme, please convert to IOB2 or IOBES. IOB2: - B = begin, - I = inside but not the first, - O = outside e.g. John lives in New York City . B-PER O O B-LOC I-LOC I-LOC O IOBES: - B = begin, - E = ...
7,590
31.861472
163
py
nepali-ner
nepali-ner-master/utils/eval.py
''' Writes result into the file Author: Oyesh Mann Singh ''' import os import torch from tqdm import tqdm import utils.conlleval_perl as e tqdm.pandas(desc='Progress') class Evaluator: def __init__(self, config, logger, model, dataloader, model_name): self.config = config self.logger = l...
5,892
34.5
112
py
nepali-ner
nepali-ner-master/utils/converter.py
#!/usr/bin/env python3 ''' File converter into CoNLL format Author: Oyesh Mann Singh Date: 10/14/2019 ''' import os import io import argparse import re parser = argparse.ArgumentParser("POS Tagger Argument Parser") parser.add_argument("-i", "--input_folder", default="../data/", metavar="PATH", help="Data ...
1,444
32.604651
111
py
nepali-ner
nepali-ner-master/utils/NNCCorpus.py
# Natural Language Toolkit: Plaintext Corpus Reader # # Copyright (C) 2001-2018 NLTK Project # Author: Edward Loper <edloper@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """Corpus reader for the XML version of the British National Corpus.""" from nltk.corpus.reader.util import conca...
9,564
33.781818
101
py
frozen-in-time
frozen-in-time-main/test.py
import argparse import pandas as pd import torch import transformers from sacred import Experiment from tqdm import tqdm import glob import data_loader.data_loader as module_data import model.metric as module_metric import model.model as module_arch from model.model import compute_similarity from parse_config import C...
11,571
39.603509
160
py
frozen-in-time
frozen-in-time-main/parse_config.py
import inspect import logging import os import time from datetime import datetime from functools import reduce from operator import getitem from pathlib import Path from logger import setup_logging from utils import read_json, write_json class ConfigParser: def __init__(self, args, options='', timestamp=True, te...
5,382
35.869863
118
py
frozen-in-time
frozen-in-time-main/train.py
import argparse import collections import os import transformers from sacred import Experiment import data_loader.data_loader as module_data import model.loss as module_loss import model.metric as module_metric import model.model as module_arch import utils.visualizer as module_vis from parse_config import ConfigPars...
5,446
41.554688
114
py
frozen-in-time
frozen-in-time-main/trainer/__init__.py
from .trainer import *
23
11
22
py
frozen-in-time
frozen-in-time-main/trainer/trainer.py
import numpy as np import torch from torch import nn from tqdm.auto import tqdm from base import BaseTrainer from model.model import sim_matrix from utils import inf_loop class Trainer(BaseTrainer): """ Trainer class Note: Inherited from BaseTrainer. """ def __init__(self, model, loss, ...
10,116
43.179039
119
py
frozen-in-time
frozen-in-time-main/data_loader/MSRVTT_dataset.py
import json import os import random import numpy as np import pandas as pd from base.base_dataset import TextVideoDataset class MSRVTT(TextVideoDataset): def _load_metadata(self): json_fp = os.path.join(self.metadata_dir, 'annotation', 'MSR_VTT.json') with open(json_fp, 'r') as fid: ...
3,173
40.763158
103
py
frozen-in-time
frozen-in-time-main/data_loader/data_loader.py
from base import BaseDataLoaderExplicitSplit, BaseMultiDataLoader from data_loader.ConceptualCaptions_dataset import ConceptualCaptions3M from data_loader.LSMDC_dataset import LSMDC from data_loader.MSRVTT_dataset import MSRVTT from data_loader.WebVid_dataset import WebVid from data_loader.VideoDirectory_dataset import...
4,625
32.280576
115
py
frozen-in-time
frozen-in-time-main/data_loader/LSMDC_dataset.py
import os import numpy as np import pandas as pd from base.base_dataset import TextVideoDataset class LSMDC(TextVideoDataset): def _load_metadata(self): split_paths = {key: os.path.join(self.metadata_dir, 'structured-symlinks', f'{key}_list.txt') for key in ['train', 'val', 'test'...
2,542
45.236364
113
py
frozen-in-time
frozen-in-time-main/data_loader/VideoDirectory_dataset.py
import json import os import random import numpy as np import pandas as pd import glob from base.base_dataset import TextVideoDataset class VideoDirectory(TextVideoDataset): def _load_metadata(self): if self.split != 'test': raise NotImplementedError("Assumes inference, no text, hence cant b...
2,295
33.268657
123
py
frozen-in-time
frozen-in-time-main/data_loader/ImageDirectory_dataset.py
import json import os import random import numpy as np import pandas as pd import glob from base.base_dataset import TextImageDataset class ImageDirectory(TextImageDataset): def _load_metadata(self): if self.split != 'test': raise NotImplementedError("Assumes inference, no text, hence cant b...
1,355
27.851064
103
py
frozen-in-time
frozen-in-time-main/data_loader/WebVid_dataset.py
import os import pandas as pd from base.base_dataset import TextVideoDataset class WebVid(TextVideoDataset): """ WebVid Dataset. Assumes webvid data is structured as follows. Webvid/ videos/ 000001_000050/ ($page_dir) 1.mp4 (videoid.mp4) ...
1,439
31.727273
107
py
frozen-in-time
frozen-in-time-main/data_loader/ConceptualCaptions_dataset.py
import os import zlib import pandas as pd from base.base_dataset import TextImageDataset class ConceptualCaptions3M(TextImageDataset): """ Conceptual Captions dataset. Split files are specific to my download regime. """ def _load_metadata(self): # download specific split_files = { ...
1,441
33.333333
108
py
frozen-in-time
frozen-in-time-main/data_loader/__init__.py
0
0
0
py
frozen-in-time
frozen-in-time-main/data_loader/transforms.py
from torchvision import transforms def init_transform_dict(input_res=224, center_crop=256, randcrop_scale=(0.5, 1.0), color_jitter=(0, 0, 0), norm_mean=(0.485, 0.456, 0.406), norm_std=(0.229, 0.224,...
1,160
35.28125
112
py
frozen-in-time
frozen-in-time-main/logger/visualization.py
import importlib from utils import Timer class TensorboardWriter: def __init__(self, log_dir, logger, enabled): self.writer = None self.selected_module = "" if enabled: log_dir = str(log_dir) # Retrieve visualization writer. for module in ["torch.util...
2,909
35.375
120
py
frozen-in-time
frozen-in-time-main/logger/logger.py
import logging import logging.config from pathlib import Path from utils import read_json def setup_logging(save_dir, log_config='logger/logger_config.json', default_level=logging.INFO): """ Setup logging configuration """ log_config = Path(log_config) if log_config.is_file(): config = re...
751
30.333333
96
py
frozen-in-time
frozen-in-time-main/logger/__init__.py
from .logger import * from .visualization import *
50
24.5
28
py
frozen-in-time
frozen-in-time-main/scripts/create_faiss_index.py
import argparse import faiss from pathlib import Path import numpy as np import os def create_index( index: str, embed_dim: int, nlist: int, ): index = faiss.index_factory(embed_dim, f"{index}{nlist},Flat", faiss.METRIC_INNER_PRODUCT) return index def load_feats( feat_fp: Path...
2,903
31.629213
120
py
frozen-in-time
frozen-in-time-main/scripts/agg_ids_embeds.py
import numpy as np import pandas as pd import glob import os from ast import literal_eval import argparse # dir = '/scratch/shared/beegfs/maxbain/datasets/CondensedMoviesShots/features/CC-WebVid2M-4f-pt1f/0522_143949' # dir = '/scratch/shared/beegfs/maxbain/datasets/CondensedMovies/features/CLIP4CLIP/cmd_batch_size_t...
2,438
40.338983
138
py
frozen-in-time
frozen-in-time-main/base/base_model.py
import torch.nn as nn import numpy as np from abc import abstractmethod class BaseModel(nn.Module): """ Base class for all models """ @abstractmethod def forward(self, *inputs): """ Forward pass logic :return: Model output """ raise NotImplementedError ...
646
23.884615
79
py
frozen-in-time
frozen-in-time-main/base/base_trainer.py
from abc import abstractmethod import torch from numpy import inf class BaseTrainer: """ Base class for all trainers """ def __init__(self, model, loss, metrics, optimizer, config, writer=None, init_val=False): self.config = config self.logger = config.get_logger('trainer', config['tr...
9,470
38.962025
117
py
frozen-in-time
frozen-in-time-main/base/base_dataset.py
import os import random from abc import abstractmethod import av import cv2 import decord import numpy as np import torch from PIL import Image from torch.utils.data import Dataset, get_worker_info from torchvision import transforms class TextVideoDataset(Dataset): def __init__(self, dataset_nam...
8,634
35.434599
116
py
frozen-in-time
frozen-in-time-main/base/base_data_loader.py
import numpy as np from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate from torch.utils.data.sampler import SubsetRandomSampler class BaseDataLoader(DataLoader): """ Base class for all data loaders """ def __init__(self, dataset, batch_size, shuffle, validat...
3,447
30.633028
130
py
frozen-in-time
frozen-in-time-main/base/__init__.py
from .base_data_loader import * from .base_dataset import * from .base_model import * from .base_trainer import *
114
22
31
py
frozen-in-time
frozen-in-time-main/utils/custom_transforms.py
import numbers from typing import List, Tuple import torch from torch import Tensor from torchvision.transforms import functional_pil as F_pil, functional_tensor as F_t from torchvision.transforms.functional import center_crop, crop def _get_image_size(img: Tensor) -> List[int]: """Returns image size as [w, h] ...
4,569
33.360902
109
py
frozen-in-time
frozen-in-time-main/utils/video.py
import random import cv2 import numpy as np import torch def load_frames_from_video_path(path, num_frames, sample='rand'): cap = cv2.VideoCapture(path) assert (cap.isOpened()) vlen = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) acc_samples = min(num_frames, vlen) intervals = np.linspace(start=0, stop=v...
1,264
29.853659
80
py
frozen-in-time
frozen-in-time-main/utils/html.py
import os import dominate from dominate.tags import a, attr, br, h3, img, meta, p, source, span, table, td, tr, video class HTML: """This HTML class allows us to save images and write texts into a single HTML file. It consists of functions such as <add_header> (add a text header to the HTML file), <ad...
6,098
41.354167
97
py
frozen-in-time
frozen-in-time-main/utils/visualisation.py
import matplotlib import numpy as np import torch matplotlib.use('Agg') def visualise_path(pred, target, window): """ :param pred: (P, 2) Tensor where P is the number of predictions, and 2 is the (i,j) coordinate :param target: (T, 2) Tensor where T is the number of targets, and 2 is the (i,j) coordinate...
1,768
28.983051
104
py
frozen-in-time
frozen-in-time-main/utils/visualizer.py
"""A simple HTML visualizer. It is based on the Cycle-GAN codebase: https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix """ import os from pathlib import Path import numpy as np from . import html class RetrievalVis: """This class includes several functions that can display/save images. It uses a Pyth...
6,109
36.030303
89
py
frozen-in-time
frozen-in-time-main/utils/util.py
import functools import json import os import socket import time from collections import OrderedDict from datetime import datetime from itertools import repeat from pathlib import Path import humanize import numpy as np import psutil def replace_nested_dict_item(obj, key, replace_value): for k, v in obj.items():...
4,602
29.084967
90
py
frozen-in-time
frozen-in-time-main/utils/__init__.py
from .util import *
20
9.5
19
py
frozen-in-time
frozen-in-time-main/model/loss.py
import torch import torch.nn.functional as F from torch import nn class NormSoftmaxLoss(nn.Module): def __init__(self, temperature=0.05): super().__init__() self.temperature = temperature def forward(self, x): "Assumes input x is similarity matrix of N x M \in [-1, 1], computed using...
2,813
27.424242
132
py
frozen-in-time
frozen-in-time-main/model/model.py
import timm import torch import torch.nn as nn import torch.nn.functional as F from transformers import AutoModel from base import BaseModel from model.video_transformer import SpaceTimeTransformer from utils.util import state_dict_data_parallel_fix class FrozenInTime(BaseModel): def __init__(self, ...
7,958
43.463687
116
py
frozen-in-time
frozen-in-time-main/model/__init__.py
0
0
0
py
frozen-in-time
frozen-in-time-main/model/video_transformer.py
""" Implementations of Video Transformers in PyTorch A PyTorch implementation of space-time transformer as described in 'Frozen in Time: A Joint Image and Video Encoder for End-to-End Retrieval' - https://arxiv.org/abs/2104.00650 A PyTorch implementation of timesformer as described in 'Is Space-Time Attention All You...
14,164
40.784661
145
py
frozen-in-time
frozen-in-time-main/model/metric.py
"""Module for computing performance metrics """ from pathlib import Path import numpy as np import scipy.stats import torch def t2v_metrics(sims, query_masks=None): """Compute retrieval metrics from a similarity matrix. Args: sims (th.Tensor): N x M matrix of similarities between embeddings, where ...
14,381
38.839335
93
py
local-astar
local-astar-master/src/main.py
""" Code modified from: https://github.com/ignavierng/golem/blob/main/src/main.py Each run creates a directory based on current datetime to save: - log file of training process - experiment configurations - observational data and ground truth - final estimated solution - visualization of final estimated solution """ ...
3,597
37.688172
100
py
local-astar
local-astar-master/src/data_loader/__init__.py
from data_loader.synthetic_dataset import SyntheticDataset
59
29
58
py
local-astar
local-astar-master/src/data_loader/synthetic_dataset.py
""" Code modified from: - https://github.com/ignavier/golem/blob/main/src/data_loader/synthetic_dataset.py - https://github.com/xunzheng/notears/blob/master/notears/utils.py """ import logging import networkx as nx import numpy as np from utils.dag import get_cpdag, get_skeleton from utils.dag import is_dag class S...
5,873
31.274725
99
py
local-astar
local-astar-master/src/search/exact_search.py
""" Some code of DP and astar is modified from: https://github.com/jmschrei/pomegranate/blob/master/pomegranate/BayesianNetwork.pyx Several tricks to save memory of parent_graphs and prune edges in order_graph are based on: https://arxiv.org/abs/1608.02682 Several other tricks of A* (e.g., dynamic k-cycle conflict he...
18,517
35.097466
102
py