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 |
|---|---|---|---|---|---|---|
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/prior/__init__.py | from typing import Tuple
import numpy as np
class Prior:
def __init__(
self,
# todo is may be better to pass tensor as arguments and unify whether we use tensor/np array
X_train: np.array,
y_train: np.array,
):
super(Prior, self).__init__()
asse... | 647 | 26 | 104 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/experiments/optimizer_styles.py | from matplotlib import cm
from experiments.optimizer_names import names
def _method_dict():
cmap = cm.Set1
def style(prior: bool = False, copula: bool = False):
ms = 's' if prior else ""
ls = '--' if copula else '-'
return ls, ms
rs_copula_color = cmap(0)
rs_color = cmap(0)
... | 2,359 | 32.239437 | 82 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/experiments/evaluate_optimizer_task.py | import argparse
import logging
import os
from functools import partial
from pathlib import Path
import pandas as pd
import numpy as np
from blackbox import BlackboxOffline
from blackbox.load_utils import evaluation_split_from_task, blackbox_from_task
from optimizer.benchmark import benchmark
from optimizer.gaussian_p... | 3,590 | 29.956897 | 111 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/experiments/figure_illustration.py | import seaborn as sns
import matplotlib.pyplot as plt
from pathlib import Path
import pandas as pd
import numpy as np
from optimizer.normalization_transforms import GaussianTransform
from blackbox.offline import evaluations_df, deepar
df = evaluations_df(deepar)
df = df[df.task.isin(["traffic", "electricity", "so... | 2,194 | 22.858696 | 81 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/experiments/load_results.py | from typing import Optional
import pandas as pd
from pathlib import Path
from blackbox.offline import evaluations_df
from blackbox.load_utils import error_metric
path = Path(__file__).parent
def postprocess_results(df):
# keeps only 70 iteration for NAS and 100 for other blackboxes as described in the paper
... | 2,293 | 31.309859 | 119 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/experiments/figure2.py | from pathlib import Path
from typing import List
import pandas as pd
import matplotlib.pyplot as plt
import os
import numpy as np
from experiments.load_results import load_results_paper
from experiments.optimizer_names import names
from experiments.optimizer_styles import optimizer_style
from experiments.table2 impor... | 2,967 | 31.615385 | 104 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/experiments/optimizer_names.py |
class names:
# put names into a class to add structure and avoid having lots of imports
RS = "RS"
# ablation
GP = "GP"
GCP_ho_prior = "GCP + homosk. prior"
GCP = "GCP"
GCP_prior = "GCP + prior (ours)"
GP_prior = "GP + prior"
CTS_ho_prior = "CTS + homosk. prior"
CTS_prior = "CTS... | 2,513 | 27.247191 | 94 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/experiments/table2.py | from typing import List, Optional
import pandas as pd
import numpy as np
from pathlib import Path
from blackbox.offline import deepar, fcnet, xgboost, nas102
from experiments.load_results import load_results_paper
from experiments.optimizer_names import names
path = Path(__file__).parent
def adtm_scores(df, optimi... | 3,258 | 30.038095 | 110 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/experiments/__init__.py | 0 | 0 | 0 | py | |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/experiments/table2-new-implem.py | import os
import pandas as pd
from pathlib import Path
from experiments.load_results import load_results_paper, load_results_reimplem, add_adtm
from experiments.optimizer_names import names
from experiments.table2 import adtm_scores, rank
path = Path(__file__).parent
if __name__ == '__main__':
df_paper = load_... | 912 | 26.666667 | 88 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/experiments/figure1.py | from pathlib import Path
import matplotlib.pyplot as plt
from blackbox.offline import deepar, fcnet, xgboost, nas102
from experiments.load_results import load_results_paper
from experiments.optimizer_names import names
from experiments.optimizer_styles import optimizer_style
path = Path(__file__).parent
def plot_o... | 2,457 | 27.581395 | 105 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/optimizer/benchmark.py | import gc
import logging
import sys
import traceback
from typing import Tuple, Callable
import numpy as np
from tqdm import tqdm
from blackbox import Blackbox
from misc import set_seed
from optimizer import Optimizer
def benchmark(
num_evaluations: int,
optimizer_factory: Callable[[], Optimizer],
... | 1,777 | 27.677419 | 99 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/optimizer/gaussian_process_functional_prior.py | from typing import Optional, Tuple, Callable, Union, List
import logging
import numpy as np
import torch
from gpytorch import ExactMarginalLogLikelihood
from gpytorch.constraints import GreaterThan
from gpytorch.likelihoods import GaussianLikelihood
from torch import Tensor
from torch.distributions import Normal
from ... | 9,128 | 33.711027 | 105 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/optimizer/thompson_sampling_functional_prior.py | import logging
from typing import Optional, List, Tuple
import numpy as np
from constants import num_gradient_updates
from optimizer import Optimizer
from optimizer.normalization_transforms import from_string
from optimizer.random_search import RS
from prior.mlp_pytorch import ParametricPrior
from prior.mlp_sklearn im... | 2,528 | 35.128571 | 106 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/optimizer/gaussian_process.py | import logging
from typing import Optional
import numpy as np
import torch
from botorch import fit_gpytorch_model
from botorch.acquisition import ExpectedImprovement
from botorch.models import SingleTaskGP
from botorch.optim import optimize_acqf
from botorch.utils.transforms import normalize
from gpytorch import Exact... | 4,389 | 32.51145 | 109 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/optimizer/__init__.py | from typing import Optional, Tuple, List
import numpy as np
class Optimizer:
def __init__(
self,
input_dim: int,
output_dim: int,
bounds: Optional[np.array] = None,
evaluations_other_tasks: Optional[List[Tuple[np.array, np.array]]] = None,
):
... | 2,500 | 35.246377 | 139 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/optimizer/normalization_transforms.py | import numpy as np
from scipy import stats
class GaussianTransform:
"""
Transform data into Gaussian by applying psi = Phi^{-1} o F where F is the truncated ECDF.
:param y: shape (n, dim)
"""
def __init__(self, y: np.array):
assert y.ndim == 2
self.dim = y.shape[1]
self.so... | 2,093 | 27.297297 | 94 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/optimizer/random_search.py | from typing import Optional, List, Tuple
import numpy as np
from optimizer import Optimizer
class RS(Optimizer):
def __init__(
self,
input_dim: int,
output_dim: int,
bounds: Optional[np.array] = None,
evaluations_other_tasks: Optional[List[Tuple[np.arra... | 979 | 32.793103 | 90 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/blackbox/offline.py | from pathlib import Path
import pandas as pd
import numpy as np
deepar = 'DeepAR'
fcnet = 'FCNET'
xgboost = 'XGBoost'
nas102 = 'nas_bench102'
metric_error = 'metric_error'
metric_time = 'metric_time'
def evaluations_df(blackbox: str) -> pd.DataFrame:
"""
:returns a dataframe where each row corresponds to on... | 2,136 | 27.878378 | 98 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/blackbox/load_utils.py | import logging
from typing import Tuple, List
import numpy as np
from blackbox.offline import evaluations_df, deepar, fcnet, nas102, xgboost
blackbox_tasks = {
nas102: [
'cifar10',
'cifar100',
'ImageNet16-120'
],
fcnet: [
'naval',
'parkinsons',
'protein',
... | 4,186 | 28.076389 | 107 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/src/blackbox/__init__.py | from typing import Callable
import numpy as np
class Blackbox:
def __init__(
self,
input_dim: int,
output_dim: int,
eval_fun: Callable[[np.array], np.array],
):
self.input_dim = input_dim
self.output_dim = output_dim
self.eval_fun = eval... | 1,489 | 27.113208 | 80 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/tst/test_normalization.py | import numpy as np
import pytest
from optimizer.normalization_transforms import GaussianTransform, StandardTransform
@pytest.mark.parametrize("psi_cls", [GaussianTransform, StandardTransform])
def test_gaussian_transform(psi_cls):
n = 1000
tol = 0.05
dim = 2
y = np.random.uniform(size=(n, dim))
p... | 503 | 28.647059 | 83 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/tst/test_prior.py | import numpy as np
from prior.mlp_pytorch import ParametricPrior
num_train_examples = 10000
num_test_examples = num_train_examples
dim = 2
num_gradient_updates = 200
lr = 1e-2
def make_random_X_y(num_examples: int, dim: int, noise_std: float):
X = np.random.rand(num_examples, dim)
noise = np.random.normal(sc... | 1,884 | 29.403226 | 101 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/tst/test_optimization.py | import logging
import random
from functools import partial
import numpy as np
import pytest
import torch
from blackbox import Blackbox, BlackboxOffline
from misc import set_seed
from misc.artificial_data import artificial_task1
from optimizer.gaussian_process import GP
from optimizer.gaussian_process_functional_prior... | 2,572 | 26.967391 | 83 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/tst/test_evaluate.py | import pytest
from experiments.evaluate_optimizer_task import evaluate
@pytest.mark.parametrize("optimizer", [
"RS",
"GP",
"GCP",
# slow:
# "TS",
"CTS",
# "GP+prior",
"GCP+prior",
])
def test_evaluate(optimizer: str):
evaluate(
optimizer=optimizer,
task="electricit... | 434 | 17.125 | 56 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/tst/test_gp.py | import logging
import pytest
from blackbox import Blackbox
from misc.artificial_data import artificial_task1
from optimizer.gaussian_process import GP
@pytest.mark.parametrize("constrained_search", [False, True])
@pytest.mark.parametrize("normalization", ["standard", "gaussian"])
def test_gp(constrained_search: boo... | 1,005 | 26.189189 | 86 | py |
A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning | A-Quantile-based-Approach-for-Hyperparameter-Transfer-Learning-master/tst/test_blackbox.py | import numpy as np
from blackbox import BlackboxOffline
def test_blackbox():
n = 20
dim = 2
X_test = np.random.rand(n, dim)
y_test = np.random.rand(n, 1)
blackbox = BlackboxOffline(
X=X_test,
y=y_test,
)
for x, y in zip(X_test, y_test):
assert np.allclose(blackbox(x... | 326 | 19.4375 | 42 | py |
optisplit | optisplit-main/mean.py | import pandas as pd
import os
import numpy as np
from pdb import set_trace as bp
import sys
from pathlib import Path
"""Calculate means of result files."""
def sort_dfs(dfs):
res = []
for df in dfs:
start = df.iloc[:4,:].sort_values(by=[' method'], ascending=False)
end = df.iloc[4:,:].sort_val... | 1,226 | 26.266667 | 161 | py |
optisplit | optisplit-main/evaluation_metric_experiment.py | import numpy as np
import joblib
import matplotlib.pyplot as plt
import scipy.sparse as sp
import warnings
from copy import deepcopy
from pdb import set_trace as bp
from textwrap import wrap
import cv_balance
np.set_printoptions(formatter={'float': lambda x: "{0:0.5f}".format(x)})
warnings.filterwarnings('ignore', m... | 6,729 | 29.87156 | 144 | py |
optisplit | optisplit-main/cv_comparison_experiment.py | import argparse
import sys
import time
import arff
import joblib
import numpy as np
import scipy.sparse as sp
from copy import deepcopy
from datetime import timedelta
from joblib import Parallel, delayed
from pdb import set_trace as bp
from skmultilearn.model_selection import IterativeStratification
from cv_balance ... | 9,525 | 37.723577 | 166 | py |
optisplit | optisplit-main/cv_balance.py | import time
import numpy as np
import scipy.sparse as sp
from copy import deepcopy
from datetime import timedelta
from pdb import set_trace as bp
def rld(folds, targets):
tt = deepcopy(targets)
res = []
di = np.array(tt.sum(axis=0)).ravel() / tt.shape[0]
for f in folds:
pij = np.array(tt[f[1]... | 7,298 | 31.29646 | 152 | py |
optisplit | optisplit-main/stratified_sampling_for_XML/stratify_function/stratify.py | import random
import numpy as np
from datetime import datetime
import helper_funcs
def stratified_train_test_split(X, y, target_test_size, random_state=None, epochs=50, swap_probability=0.1, threshold_proportion=0.1, decay=0.1):
if random_state != None:
random.seed(random_state)
# To keep track of ho... | 4,788 | 40.284483 | 147 | py |
optisplit | optisplit-main/stratified_sampling_for_XML/stratify_function/helper_funcs.py | import random
import numpy as np
# 1. Create instances_dict to keep track of instance information:
# labels: array of labels, []
# train_or_test: string, 'train' or 'test'
# instance_score: float, adjusted sum of label scores
def create_instances_dict(X, y, target_test_size):
instances_dict = {}
instance_id = ... | 6,577 | 47.014599 | 127 | py |
PC-JeDi | PC-JeDi-main/src/plotting.py | from copy import deepcopy
from functools import partial
from pathlib import Path
from typing import Optional, Union
import matplotlib.pyplot as plt
import numpy as np
import PIL
import wandb
from jetnet.utils import efps
def plot_multi_hists(
data_list: Union[list, np.ndarray],
data_labels: Union[list, str],... | 14,847 | 36.589873 | 87 | py |
PC-JeDi | PC-JeDi-main/src/physics.py | # import jetnet
import numpy as np
import pytorch_lightning as pl
import torch as T
# FIX RANDOM SEED FOR REPRODUCIBILITY
pl.seed_everything(0, workers=True)
def locals_to_mass_and_pt(csts: T.Tensor, mask: T.BoolTensor) -> T.Tensor:
"""Calculate the overall jet pt and mass from the constituents. The
constitu... | 2,120 | 30.191176 | 84 | py |
PC-JeDi | PC-JeDi-main/src/utils.py | 0 | 0 | 0 | py | |
PC-JeDi | PC-JeDi-main/src/numpy_utils.py | import numpy as np
def undo_log_squash(data: np.ndarray) -> np.ndarray:
"""Undo the log squash function above."""
return np.sign(data) * (np.exp(np.abs(data)) - 1)
def log_squash(data: np.ndarray) -> np.ndarray:
"""Apply a log squashing function for distributions with high tails."""
return np.sign(d... | 352 | 28.416667 | 75 | py |
PC-JeDi | PC-JeDi-main/src/torch_utils.py | from typing import Union
import numpy as np
import torch as T
import torch.nn as nn
def get_loss_fn(name: str, **kwargs) -> nn.Module:
"""Return a pytorch loss function given a name."""
if name == "none":
return None
# Regression losses
if name == "huber":
return nn.HuberLoss(reducti... | 918 | 26.848485 | 77 | py |
PC-JeDi | PC-JeDi-main/src/hydra_utils.py | """A collection of misculaneous functions usefull for the lighting/hydra
template."""
import logging
import os
from pathlib import Path
from typing import Any, List, Sequence
import hydra
import rich
import rich.syntax
import rich.tree
import wandb
from omegaconf import DictConfig, OmegaConf
from pytorch_lightning im... | 5,097 | 30.8625 | 86 | py |
PC-JeDi | PC-JeDi-main/src/__init__.py | 0 | 0 | 0 | py | |
PC-JeDi | PC-JeDi-main/src/datamodules/__init__.py | 0 | 0 | 0 | py | |
PC-JeDi | PC-JeDi-main/src/datamodules/jetnet.py | from copy import deepcopy
from typing import Mapping
import numpy as np
from jetnet.datasets import JetNet
from pytorch_lightning import LightningDataModule
from torch.utils.data import DataLoader, Dataset
from src.numpy_utils import log_squash
from src.physics import numpy_locals_to_mass_and_pt
class JetNetData(Da... | 3,490 | 34.989691 | 86 | py |
PC-JeDi | PC-JeDi-main/src/models/diffusion.py | import math
from typing import Optional, Tuple
import torch as T
from tqdm import tqdm
class VPDiffusionSchedule:
def __init__(self, max_sr: float = 1, min_sr: float = 1e-2) -> None:
self.max_sr = max_sr
self.min_sr = min_sr
def __call__(self, time: T.Tensor) -> T.Tensor:
return cosi... | 11,263 | 33.873065 | 86 | py |
PC-JeDi | PC-JeDi-main/src/models/transformers.py | """Some classes to describe transformer architectures."""
import math
from typing import Mapping, Optional, Union
import torch as T
import torch.nn as nn
from torch.nn.functional import dropout, softmax
from .modules import DenseNetwork
def merge_masks(
q_mask: Union[T.BoolTensor, None],
kv_mask: Union[T.B... | 15,049 | 33.837963 | 87 | py |
PC-JeDi | PC-JeDi-main/src/models/schedulers.py | from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
class WarmupToConstant(_LRScheduler):
"""Gradually warm-up learning rate in optimizer to a constant value."""
def __init__(self, optimizer: Optimizer, num_steps: int = 100) -> None:
"""
args:
optim... | 793 | 32.083333 | 85 | py |
PC-JeDi | PC-JeDi-main/src/models/modules.py | """Collection of pytorch modules that make up the networks."""
import math
from typing import Optional, Union
import torch as T
import torch.nn as nn
def get_act(name: str) -> nn.Module:
"""Return a pytorch activation function given a name."""
if name == "relu":
return nn.ReLU()
if name == "lrlu... | 20,518 | 35.575758 | 90 | py |
PC-JeDi | PC-JeDi-main/src/models/pc_jedi.py | import copy
from functools import partial
from typing import Mapping, Optional, Tuple
import numpy as np
import pytorch_lightning as pl
import torch as T
import wandb
from jetnet.evaluation import w1efp, w1m, w1p
from src.models.diffusion import VPDiffusionSchedule, run_sampler
from src.models.modules import CosineEn... | 12,805 | 38.403077 | 87 | py |
PC-JeDi | PC-JeDi-main/src/models/__init__.py | 0 | 0 | 0 | py | |
PC-JeDi | PC-JeDi-main/scripts/train.py | import pyrootutils
root = pyrootutils.setup_root(search_from=__file__, pythonpath=True)
import logging
import hydra
import pytorch_lightning as pl
from omegaconf import DictConfig
from src.hydra_utils import (
instantiate_collection,
log_hyperparameters,
print_config,
reload_original_config,
sav... | 1,731 | 23.742857 | 87 | py |
trees_from_transformers | trees_from_transformers-master/run.py | import argparse
import datetime
import logging
import os
import pickle
from tqdm import tqdm
import torch
from transformers import *
from data.dataset import Dataset
from utils.measure import Measure
from utils.parser import not_coo_parser, parser
from utils.tools import set_seed, select_indices, group_indices
from u... | 11,441 | 45.893443 | 85 | py |
trees_from_transformers | trees_from_transformers-master/utils/yk.py | """
The functions in this file are originated from the code for
Compound Probabilistic Context-Free Grammars for Grammar Induction,
Y. Kim et al., ACL 2019.
For more details, visit https://github.com/harvardnlp/compound-pcfg.
"""
import re
def clean_number(w):
new_w = re.sub('[0-9]{1,}([,.]?[0-9]*)*', 'N', w)
... | 4,935 | 29.097561 | 78 | py |
trees_from_transformers | trees_from_transformers-master/utils/parser.py | import numpy as np
def not_coo_parser(score, sent):
assert len(score) == len(sent) - 1
if len(score) == 0:
parse_tree = f'(T {sent[0]} )'
elif len(score) == 1:
parse_tree = f'(T (T {sent[0]} ) (T {sent[1]} ) )'
else:
idx_max = np.argmax(score)
l_len = len(sent[:idx_max... | 1,936 | 33.589286 | 80 | py |
trees_from_transformers | trees_from_transformers-master/utils/score.py | import numpy as np
import torch
from utils.yk import get_stats
class Score(object):
def __init__(self, n):
self.corpus_f1 = torch.zeros(n, 3, dtype=torch.float)
self.sent_f1 = torch.zeros(n, dtype=torch.float)
self.n = n
self.cnt = 0
self.labels = ['SBAR', 'NP', 'VP', 'PP'... | 2,521 | 35.550725 | 79 | py |
trees_from_transformers | trees_from_transformers-master/utils/tools.py | import logging
import random
import torch
specials = {'bert': '#', 'gpt2': 'Ġ', 'xlnet': '▁', 'roberta': 'Ġ'}
def set_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
random.seed(seed)
def select_indices(tokens, raw_tokens, model, mode):
mask = []
raw_i = 0
collapsed = ''
... | 1,612 | 24.603175 | 68 | py |
trees_from_transformers | trees_from_transformers-master/utils/extractor.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Extractor(nn.Module):
def __init__(self, n_hidden):
super(Extractor, self).__init__()
self.linear = nn.Linear(n_hidden * 2, 1)
nn.init.uniform_(self.linear.weight, -0.01, 0.01)
nn.init.uniform_(self.linear.bias... | 752 | 27.961538 | 77 | py |
trees_from_transformers | trees_from_transformers-master/utils/measure.py | import math
import torch
import torch.nn.functional as F
from utils.score import Score
class Measure(object):
def __init__(self, n_layers, n_att):
self.h_measures = ['cos', 'l1', 'l2']
self.a_measures = ['hellinger', 'jsd']
self.a_avg_measures = ['avg_hellinger', 'avg_jsd']
self.m... | 3,102 | 33.477778 | 82 | py |
trees_from_transformers | trees_from_transformers-master/data/dataset.py | from utils.yk import get_actions, get_nonbinary_spans, get_tags_tokens_lowercase
class Dataset(object):
def __init__(self, path, tokenizer):
self.path = path
self.tokenizer = tokenizer
self.cnt = 0
self.sents = []
self.raw_tokens = []
self.tokens = []
self.... | 1,271 | 32.473684 | 80 | py |
pi-peps | pi-peps-master/docs/source/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 ------------------------------------------------------------... | 5,615 | 28.557895 | 79 | py |
SSTAP | SSTAP-main/post_processing.py | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import json
import multiprocessing as mp
from utils import iou_with_anchors
def load_json(file):
with open(file) as json_file:
data = json.load(json_file)
return data
def getDatasetDict(opt):
df = pd.read_csv(opt["video_info"])
... | 4,633 | 34.106061 | 116 | py |
SSTAP | SSTAP-main/main.py | import sys
from dataset import VideoDataSet, VideoDataSet_unlabel
from loss_function import bmn_loss_func, get_mask
import os
import json
import torch
import torch.nn.parallel
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
import numpy as np
import opts
from ipdb import set_trace
from... | 42,436 | 48.173812 | 190 | py |
SSTAP | SSTAP-main/gen_unlabel_videos.py | import numpy as np
import pandas as pd
import json
import random
def load_json(file):
with open(file) as json_file:
json_data = json.load(json_file)
return json_data
anno_df = pd.read_csv("./data/activitynet_annotations/video_info_new.csv")
anno_database = load_json("./data/activitynet_annotatio... | 2,370 | 36.046875 | 115 | py |
SSTAP | SSTAP-main/opts.py | import argparse
def parse_opt():
parser = argparse.ArgumentParser()
# Overall settings
parser.add_argument(
'--mode',
type=str,
default='train')
parser.add_argument(
'--checkpoint_path',
type=str,
default='./checkpoint')
parser.add_argument(
... | 2,615 | 21.747826 | 71 | py |
SSTAP | SSTAP-main/utils.py | import numpy as np
def ioa_with_anchors(anchors_min, anchors_max, box_min, box_max):
# calculate the overlap proportion between the anchor and all bbox for supervise signal,
# the length of the anchor is 0.01
len_anchors = anchors_max - anchors_min
int_xmin = np.maximum(anchors_min, box_min)
int_x... | 960 | 37.44 | 92 | py |
SSTAP | SSTAP-main/dataset.py | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import json
import torch.utils.data as data
import torch
from utils import ioa_with_anchors, iou_with_anchors
from ipdb import set_trace
def load_json(file):
with open(file) as json_file:
json_data = json.load(json_file)
return json_da... | 14,230 | 51.707407 | 155 | py |
SSTAP | SSTAP-main/loss_function.py | # -*- coding: utf-8 -*-
import torch
import numpy as np
import torch.nn.functional as F
def get_mask(tscale):
bm_mask = []
for idx in range(tscale):
mask_vector = [1 for i in range(tscale - idx)
] + [0 for i in range(idx)]
bm_mask.append(mask_vector)
bm_mask = np.arr... | 3,482 | 32.171429 | 90 | py |
SSTAP | SSTAP-main/eval.py | # -*- coding: utf-8 -*-
import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append('./Evaluation')
from eval_proposal import ANETproposal
import matplotlib.pyplot as plt
import numpy as np
def run_evaluation(ground_truth_filename, proposal_filename,
max_avg_nr_proposals=100,
... | 3,247 | 44.111111 | 122 | py |
SSTAP | SSTAP-main/models.py | # -*- coding: utf-8 -*-
import math
import numpy as np
import torch
import torch.nn as nn
from ipdb import set_trace
import random
import torch.nn.functional as F
class TemporalShift(nn.Module):
def __init__(self, n_segment=3, n_div=8, inplace=False):
super(TemporalShift, self).__init__()
# self.n... | 13,366 | 43.115512 | 138 | py |
SSTAP | SSTAP-main/data/activitynet_feature_cuhk/data_process.py | # -*- coding: utf-8 -*-
import random
import numpy as np
import scipy
import pandas as pd
import pandas
import numpy
import json
def resizeFeature(inputData,newSize):
# inputX: (temporal_length,feature_dimension) #
originalSize=len(inputData)
#print originalSize
if originalSize==1:
inputData=... | 4,484 | 31.737226 | 103 | py |
SSTAP | SSTAP-main/data/activitynet_feature_cuhk/ldb_process.py | # -*- coding: utf-8 -*-
"""
Created on Mon May 15 22:31:31 2017
@author: wzmsltw
"""
import caffe
import leveldb
import numpy as np
from caffe.proto import caffe_pb2
import pandas as pd
col_names=[]
for i in range(200):
col_names.append("f"+str(i))
df=pd.read_table("./input_spatial_list.txt",names=['image','fram... | 983 | 21.883721 | 84 | py |
SSTAP | SSTAP-main/Evaluation/eval_proposal.py | import json
import numpy as np
import pandas as pd
def interpolated_prec_rec(prec, rec):
"""Interpolated AP - VOCdevkit from VOC 2011.
"""
mprec = np.hstack([[0], prec, [0]])
mrec = np.hstack([[0], rec, [1]])
for i in range(len(mprec) - 1)[::-1]:
mprec[i] = max(mprec[i], mprec[i + 1])
... | 13,318 | 38.877246 | 119 | py |
SSTAP | SSTAP-main/Evaluation/utils.py | import json
import urllib2
import numpy as np
API = 'http://ec2-52-11-11-89.us-west-2.compute.amazonaws.com/challenge16/api.py'
def get_blocked_videos(api=API):
api_url = '{}?action=get_blocked'.format(api)
req = urllib2.Request(api_url)
response = urllib2.urlopen(req)
return json.loads(response.read... | 2,648 | 33.855263 | 81 | py |
xSLHA | xSLHA-master/setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="xslha",
version="1.0.2",
author="Florian Staub",
author_email="florian.staub@gmail.com",
description="A python package to read (big/many) SLHA files",
long_description=long_description... | 710 | 28.625 | 65 | py |
xSLHA | xSLHA-master/xslha/main.py | import subprocess
import os
from six import string_types
# SLHA parser
# by Florian Staub (florian.staub@gmail.com)
# ----------------------------------------------------------
# SLHA Class
# ----------------------------------------------------------
class SLHA():
def __init__(self):
self.blocks = {}
... | 10,207 | 34.817544 | 90 | py |
xSLHA | xSLHA-master/xslha/__init__.py | from .main import *
name = "xslha"
| 35 | 11 | 19 | py |
enterprise_extensions | enterprise_extensions-master/setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup
with open("README.rst") as readme_file:
readme = readme_file.read()
with open("HISTORY.rst") as history_file:
history = history_file.read()
requirements = [
"numpy>=1.16.3",
"scipy>=1.2.0",
"ephem... | 2,094 | 27.310811 | 104 | py |
enterprise_extensions | enterprise_extensions-master/tests/test_hypermodel.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `enterprise_extensions` package."""
import json
import logging
import os
import pickle
import pytest
from enterprise_extensions import models, hypermodel
testdir = os.path.dirname(os.path.abspath(__file__))
datadir = os.path.join(testdir, 'data')
outdir = ... | 1,969 | 28.402985 | 82 | py |
enterprise_extensions | enterprise_extensions-master/tests/test_chromatic.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `enterprise_extensions.chromatic` submodule."""
import logging
import os
import pickle
import numpy as np
import pytest
from enterprise_extensions.chromatic import solar_wind as sw
testdir = os.path.dirname(os.path.abspath(__file__))
datadir = os.path.join... | 1,126 | 25.209302 | 85 | py |
enterprise_extensions | enterprise_extensions-master/tests/test_models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `enterprise_extensions` package."""
import json
import logging
import os
import pickle
import pytest
from enterprise import constants as const
from enterprise_extensions import model_utils, models
testdir = os.path.dirname(os.path.abspath(__file__))
datadi... | 19,443 | 42.792793 | 95 | py |
enterprise_extensions | enterprise_extensions-master/tests/test_sampler.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `enterprise_extensions` package."""
import json
import logging
import os
import pickle
import pytest
from enterprise_extensions import models, sampler
from enterprise_extensions.empirical_distr import (
make_empirical_distributions, make_empirical_distr... | 7,924 | 36.559242 | 90 | py |
enterprise_extensions | enterprise_extensions-master/tests/__init__.py | 0 | 0 | 0 | py | |
enterprise_extensions | enterprise_extensions-master/tests/test_frequentist.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `enterprise_extensions` package."""
import json
import logging
import os
import pickle
import numpy as np
import pytest
from enterprise_extensions import models
from enterprise_extensions.frequentist import chi_squared as chisqr
testdir = os.path.dirname(o... | 1,453 | 24.508772 | 83 | py |
enterprise_extensions | enterprise_extensions-master/tests/test_enterprise_extensions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `enterprise_extensions` package."""
import pytest
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com/audrey... | 561 | 23.434783 | 78 | py |
enterprise_extensions | enterprise_extensions-master/tests/test_os.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `enterprise_extensions` package."""
import json
import logging
import os
import pickle
import numpy as np
import pytest
from enterprise.signals import signal_base, gp_signals, parameter, utils
from enterprise_extensions import models, blocks, model_utils
fr... | 3,721 | 31.938053 | 84 | py |
enterprise_extensions | enterprise_extensions-master/tests/altpol_tests.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for altpol functions in e_e Code.
"""
import json
import logging
import os
import pickle
import enterprise.signals.parameter as parameter
import numpy as np
import pytest
from enterprise.signals import gp_signals, signal_base
from enterprise_extensions import ... | 3,893 | 33.157895 | 98 | py |
enterprise_extensions | enterprise_extensions-master/docs/conf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# enterprise_extensions documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present... | 5,714 | 30.75 | 99 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/hypermodel.py | # -*- coding: utf-8 -*-
import os
import numpy as np
import scipy.linalg as sl
from enterprise import constants as const
from PTMCMCSampler.PTMCMCSampler import PTSampler as ptmcmc
from .sampler import JumpProposal, get_parameter_groups, save_runtime_info
class HyperModel(object):
"""
Class to define hype... | 16,731 | 37.200913 | 102 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/gp_kernels.py | # -*- coding: utf-8 -*-
import numpy as np
from enterprise.signals import signal_base, utils
__all__ = ['linear_interp_basis_dm',
'linear_interp_basis_freq',
'dmx_ridge_prior',
'periodic_kernel',
'se_kernel',
'se_dm_kernel',
'get_tf_quantization_matrix... | 5,878 | 28.691919 | 86 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/deterministic.py | # -*- coding: utf-8 -*-
import numpy as np
from enterprise import constants as const
from enterprise.signals import (deterministic_signals, parameter, signal_base,
utils)
def fdm_block(Tmin, Tmax, amp_prior='log-uniform', name='fdm',
amp_lower=-18, amp_upper=-11,
... | 26,111 | 34.334235 | 116 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/sampler.py | # -*- coding: utf-8 -*-
import glob
import os
import pickle
import platform
import healpy as hp
import numpy as np
from PTMCMCSampler import __version__ as __vPTMCMC__
from PTMCMCSampler.PTMCMCSampler import PTSampler as ptmcmc
from enterprise_extensions import __version__
from enterprise_extensions.empirical_distr ... | 47,414 | 37.330639 | 165 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/model_utils.py | # -*- coding: utf-8 -*-
import time
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as scistats
try:
import acor
except ImportError:
from emcee.autocorr import integrated_time as acor
from enterprise_extensions import models
# Log-spaced frequncies
def linBinning(T, logmode, f_min, ... | 12,737 | 31.914729 | 115 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/empirical_distr.py | # -*- coding: utf-8 -*-
import logging
import pickle
import numpy as np
try:
from sklearn.neighbors import KernelDensity
sklearn_available=True
except ModuleNotFoundError:
sklearn_available=False
from scipy.interpolate import interp1d, interp2d
logger = logging.getLogger(__name__)
class EmpiricalDistr... | 12,755 | 35.033898 | 149 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/sky_scrambles.py | # -*- coding: utf-8 -*-
import pickle
import sys
import time
import numpy as np
from enterprise.signals import utils
def compute_match(orf1, orf1_mag, orf2, orf2_mag):
"""Computes the match between two different ORFs."""
match = np.abs(np.dot(orf1, orf2))/(orf1_mag*orf2_mag)
return match
def make_tr... | 6,532 | 33.75 | 111 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/timing.py | # -*- coding: utf-8 -*-
from collections import OrderedDict
import numpy as np
from enterprise.signals import deterministic_signals, parameter, signal_base
# timing model delay
@signal_base.function
def tm_delay(residuals, t2pulsar, tmparams_orig, tmparams, which='all'):
"""
Compute difference in residuals... | 2,236 | 31.897059 | 80 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/dropout.py | # -*- coding: utf-8 -*-
import enterprise
import numpy as np
from enterprise import constants as const
from enterprise.signals import (deterministic_signals,
parameter,
signal_base,
utils)
@signal_base.function
def dropo... | 8,010 | 39.872449 | 87 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/model_orfs.py | # -*- coding: utf-8 -*-
import numpy as np
import scipy.interpolate as interp
from enterprise import constants as const
from enterprise.signals import signal_base
@signal_base.function
def param_hd_orf(pos1, pos2, a=1.5, b=-0.25, c=0.5):
'''
Pre-factor parametrized Hellings & Downs spatial correlation functi... | 11,164 | 29.757576 | 113 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/models.py | # -*- coding: utf-8 -*-
import functools
from collections import OrderedDict
import numpy as np
from enterprise import constants as const
from enterprise.signals import (deterministic_signals, gp_signals, parameter,
selections, signal_base, white_signals)
from enterprise.signals.signal... | 122,774 | 41.973399 | 152 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/__init__.py | __version__ = "2.4.3"
| 22 | 10.5 | 21 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/blocks.py | # -*- coding: utf-8 -*-
import types
import numpy as np
from enterprise import constants as const
from enterprise.signals import deterministic_signals
from enterprise.signals import gp_bases as gpb
from enterprise.signals import gp_priors as gpp
from enterprise.signals import (gp_signals, parameter, selections, utils... | 34,848 | 42.506866 | 119 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/chromatic/chromatic.py | # -*- coding: utf-8 -*-
import numpy as np
from enterprise import constants as const
from enterprise.signals import deterministic_signals, parameter, signal_base
__all__ = ['chrom_exp_decay',
'chrom_exp_cusp',
'chrom_dual_exp_cusp',
'chrom_yearly_sinusoid',
'chromatic_quad_... | 12,928 | 33.569519 | 96 | py |
enterprise_extensions | enterprise_extensions-master/enterprise_extensions/chromatic/__init__.py | # -*- coding: utf-8 -*-
from .chromatic import * # noqa: F401, F403
| 70 | 16.75 | 44 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.