code stringlengths 101 5.91M |
|---|
class Config(dict):
def __init__(self, *args, **kwargs):
super(Config, self).__init__()
for arg in args:
if isinstance(arg, str):
if (arg.endswith('.json') or arg.endswith('.json5')):
with open(arg) as f:
raw_dict = json5.load(f... |
def clean_oss_model_path(oss_path):
bucket = oss.get_models_bucket()
oss.delete_oss_dir_recursive(bucket, oss_path) |
def cal_performance(pred, tgt, local_rank, smoothing=True):
loss = cal_loss(pred, tgt, local_rank, smoothing)
pred = pred.max(1)[1]
tgt = tgt.contiguous().view((- 1))
non_pad_mask = tgt.ne(0)
n_correct = pred.eq(tgt)
n_correct = n_correct.masked_select(non_pad_mask).sum().item()
return (loss... |
def vectorize_batch_graph(graph, word_idx):
id_features = graph['g_ids_features']
gv = {}
nv = []
n_len_v = []
word_max_len = 0
for id in id_features:
feature = id_features[id]
word_max_len = max(word_max_len, len(feature.split()))
for id in graph['g_ids_features']:
f... |
class CosineAnnealingWarmUpRestarts(_LRScheduler):
def __init__(self, optimizer, T_0, T_mult=1, eta_max=0.1, T_up=0, gamma=1.0, last_epoch=(- 1)):
if ((T_0 <= 0) or (not isinstance(T_0, int))):
raise ValueError('Expected positive integer T_0, but got {}'.format(T_0))
if ((T_mult < 1) or ... |
class Learner(BaseLearner):
def __init__(self, args):
super().__init__(args)
self._network = DERNet(args, True)
def after_task(self):
self._known_classes = self._total_classes
logging.info('Exemplar size: {}'.format(self.exemplar_size))
def incremental_train(self, data_manage... |
def locate_files(pattern, root_dir=os.curdir, **kwargs):
for (dirpath, dirnames, filenames) in os.walk(os.path.abspath(root_dir), **kwargs):
for filename in fnmatch.filter(filenames, pattern):
(yield os.path.join(dirpath, filename)) |
class QuarticCurve_generic(projective_curve.ProjectivePlaneCurve):
def _repr_type(self):
return 'Quartic'
def genus(self):
return 3 |
def mask_special_tokens(string: str):
exceptions = [match.group(0) for match in re.finditer('[A-Za-z:_.]+_[0-9]+', string)]
for e in exceptions:
string = string.replace(e, '<temp>', 1)
return (string, exceptions) |
def update_level_set():
cashocs.interpolate_levelset_function_to_cells(psi, alpha_in, alpha_out, alpha)
cashocs.interpolate_levelset_function_to_cells(psi, 1.0, 0.0, indicator_omega)
vol.vector().vec().set(assemble((indicator_omega * dx)))
vol.vector().apply('') |
def imagenet_det_classes():
return ['accordion', 'airplane', 'ant', 'antelope', 'apple', 'armadillo', 'artichoke', 'axe', 'baby_bed', 'backpack', 'bagel', 'balance_beam', 'banana', 'band_aid', 'banjo', 'baseball', 'basketball', 'bathing_cap', 'beaker', 'bear', 'bee', 'bell_pepper', 'bench', 'bicycle', 'binder', 'bi... |
def update_shard_info_for_in_graph(meta_graph_def, num_replicas):
if (num_replicas <= 1):
return
node_name_to_node = {}
for node in meta_graph_def.graph_def.node:
node_name_to_node[node.name] = node
if (shard.SHARD_ID in meta_graph_def.collection_def):
shard_id_node_names = meta_... |
def cosine_rampup(current, rampup_length):
current = np.clip(current, 0.0, rampup_length)
return float(((- 0.5) * (np.cos(((np.pi * current) / rampup_length)) - 1))) |
def subsample_classes(dataset, include_classes=range(160)):
include_classes_cub = (np.array(include_classes) + 1)
cls_idxs = [x for (x, (_, r)) in enumerate(dataset.data.iterrows()) if (int(r['target']) in include_classes_cub)]
target_xform_dict = {}
for (i, k) in enumerate(include_classes):
tar... |
def gen_grid(args, config, config_budget={}):
task_name = '{}_grid_{}'.format(get_fname(args.config), get_fname(args.grid))
fname_start = get_fname(args.config)
out_dir = '{}/{}'.format(args.out_dir, task_name)
makedirs_rm_exist(out_dir)
config['out_dir'] = os.path.join(config['out_dir'], task_name)... |
def default_argument_parser():
parser = argparse.ArgumentParser(description='fastreid Training')
parser.add_argument('--config-file', default='', metavar='FILE', help='path to config file')
parser.add_argument('--resume', action='store_true', help='whether to attempt to resume from the checkpoint directory'... |
def _create_data(algo, nb_nodes):
batch_size = 8
ds = _make_iterable_sampler(algo, batch_size, nb_nodes)
full_sample = next(ds)
chunk_length = full_sample.features.lengths[0].astype(int)
chunked_ds = dataset.chunkify(_make_iterable_sampler(algo, batch_size, nb_nodes), chunk_length)
chunk_sample ... |
()
_context
('--network_pkl', help='Network pickle filename', required=True)
('--timesteps', type=int, help='Timesteps', default=16, show_default=True)
('--num_videos', type=int, help='Number of images to generate', default=100, show_default=True)
('--seed', type=int, help='Random seed', default=42, metavar='DIR')
('--... |
class Sst2Processor(DataProcessor):
def get_train_examples(self, data_dir):
return self._create_examples(data_dir, 'train')
def get_dev_examples(self, data_dir):
return self._create_examples(data_dir, 'dev')
def get_test_examples(self, data_dir):
return self._create_examples(data_dir... |
class ModReLU(nn.Module):
def __init__(self, features):
super().__init__()
self.features = features
self.b = nn.Parameter(torch.Tensor(self.features))
self.reset_parameters()
def reset_parameters(self):
self.b.data.uniform_((- 0.01), 0.01)
def forward(self, inputs):
... |
def test_ATan2():
(x, y) = symbols('x y')
i = atan2(x, y)
assert isinstance(i, atan2)
i = atan2(0, 1)
assert (i == 0) |
_function_dispatch(_stack_arrays_dispatcher)
def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False, autoconvert=False):
if isinstance(arrays, ndarray):
return arrays
elif (len(arrays) == 1):
return arrays[0]
seqarrays = [np.asanyarray(a).ravel() for a in arrays]
nrecords... |
def update_args(base_args, input_args):
for (key, value) in dict(input_args).items():
base_args.__dict__[key] = value
return base_args |
def _adjust_gamma_u8(image, gamma, gain):
lut = ((255 * gain) * (np.linspace(0, 1, 256) ** gamma))
lut = np.minimum(np.rint(lut), 255).astype('uint8')
return lut[image] |
def keep_relevant_rows_and_unstack(ref_df, predictions):
predictions_w_true_labels = []
eg_id_counter = []
for (i, row) in ref_df.iterrows():
if (row.num_rs > 0):
p = predictions[i]
if (len(p) > row.num_rs):
p = p[:row.num_rs]
elif (len(p) < row.nu... |
class ImageFeaturesHdfReader(object):
def __init__(self, features_hdfpath: str, in_memory: bool=False):
self.features_hdfpath = features_hdfpath
self._in_memory = in_memory
with h5py.File(self.features_hdfpath, 'r') as features_hdf:
self._split = features_hdf.attrs['split']
... |
def set_random_seed(seed: int):
np.random.seed(seed)
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed) |
class FastTextEmbeddingBag(EmbeddingBag):
def __init__(self, embedding_matrix, sparse=False):
embedding_matrix_shape = embedding_matrix.shape
super().__init__(embedding_matrix_shape[0], embedding_matrix_shape[1], sparse=sparse)
self.weight.data.copy_(torch.FloatTensor(embedding_matrix))
... |
def _regnet(variant, pretrained, **kwargs):
load_strict = True
model_class = RegNet
if kwargs.pop('features_only', False):
assert False, 'Not Implemented'
load_strict = False
kwargs.pop('num_classes', 0)
model_cfg = model_cfgs[variant]
default_cfg = default_cfgs[variant]
... |
def batch_segids20(s, l):
(res1, res2) = ([], [])
h = int((l / 2))
for i in range(h):
res1.append(tf.tile([i], [s[i]]))
res2.append(tf.tile([(i + h)], [s[(i + h)]]))
return concat_versions(0, (res1 + res2)) |
def register_Ns3OlsrAssociation_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_output_stream_operator()
cls.add_constructor([])
cls.add_constructor([param('ns3::olsr::Association const &', 'arg0')])
cls.add_instance_attribute('netmask', 'ns3::Ipv4Mask', is_const=False)
... |
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False, divide_norm=False):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.linear1 = nn.Linear(d... |
def _seg_43():
return [(64162, 'M', u''), (64163, 'M', u''), (64164, 'M', u''), (64165, 'M', u''), (64166, 'M', u''), (64167, 'M', u''), (64168, 'M', u''), (64169, 'M', u''), (64170, 'M', u''), (64171, 'M', u''), (64172, 'M', u''), (64173, 'M', u''), (64174, 'M', u''), (64175, 'M', u''), (64176, 'M', u''), (64177, ... |
def pad_to_len(pair_targets, pad, max_pair_target_len):
for i in range(len(pair_targets)):
pair_targets[i] = pair_targets[i][:max_pair_target_len]
this_len = len(pair_targets[i])
for j in range((max_pair_target_len - this_len)):
pair_targets[i].append(pad)
return pair_targets |
class RayEncoder(nn.Module):
def __init__(self, pos_octaves=8, pos_start_octave=0, ray_octaves=4, ray_start_octave=0):
super().__init__()
self.pos_encoding = PositionalEncoding(num_octaves=pos_octaves, start_octave=pos_start_octave)
self.ray_encoding = PositionalEncoding(num_octaves=ray_octa... |
def test_temperature_smooth():
smooth = (lambda probs, temp: temperature_smooth(np.array(probs, dtype=np.float32), temp))
same = (lambda x1, x2: assert_almost_equal(x1, x2, decimal=4))
probs = [0.0, 0.2, 0.4, 0.4]
third = (1.0 / 3)
correct = [0.0, third, third, third]
same(smooth(probs, 100000),... |
class ReflexiveModule_abstract(Parent):
_method(optional=True)
def tensor_type(self):
_method
def base_module(self):
def dual(self):
(k, l) = self.tensor_type()
return self.base_module().tensor_module(l, k)
def tensor(self, *args, **kwds):
return self.tensor_product(*args... |
def serial_ports():
if sys.platform.startswith('win'):
ports = [('COM%s' % (i + 1)) for i in range(256)]
elif (sys.platform.startswith('linux') or sys.platform.startswith('cygwin')):
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/de... |
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=True, drop_path=0.0, init_values=None, norm_layer=nn.LayerNorm, act_layer=nn.GELU, swiglu=False, use_rel_pos=False, input_size=None, xformers=True, use_lora=False, lora_info=dict, use_tome=False, tome_info=dict, use_repadapter=False,... |
def cosine_beta_schedule(timesteps, s=0.008):
steps = (timesteps + 1)
x = torch.linspace(0, timesteps, steps, dtype=torch.float64)
alphas_cumprod = (torch.cos((((((x / timesteps) + s) / (1 + s)) * math.pi) * 0.5)) ** 2)
alphas_cumprod = (alphas_cumprod / alphas_cumprod[0])
betas = (1 - (alphas_cumpr... |
class MultiGCN(nn.Module):
def __init__(self, n_units=[17, 128, 100], dropout=0.0):
super(MultiGCN, self).__init__()
self.num_layers = (len(n_units) - 1)
self.dropout = dropout
layer_stack = []
for i in range(self.num_layers):
layer_stack.append(GCNConv(in_channel... |
def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx):
m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx)
m.weight.data.normal_(0, 0.1)
return m |
class FP16Optimizer(_FP16OptimizerMixin, optim.FairseqOptimizer):
def __init__(self, args, params, fp32_optimizer, fp32_params):
super().__init__(args)
self.fp16_params = params
self.fp32_optimizer = fp32_optimizer
self.fp32_params = fp32_params
if (getattr(args, 'fp16_scale_... |
_utils.test()
def test_1d():
x = ti.field(ti.f32, shape=16)
def func():
for i in ti.ndrange((4, 10)):
x[i] = i
func()
for i in range(16):
if (4 <= i < 10):
assert (x[i] == i)
else:
assert (x[i] == 0) |
.skipif((not _ti_core.GGUI_AVAILABLE), reason='GGUI Not Available')
_utils.test(arch=supported_archs)
def test_imgui():
window = ti.ui.Window('test', (640, 480), show_window=False)
gui = window.get_gui()
def render():
with gui.sub_window('window 0', 0.1, 0.1, 0.8, 0.2) as w:
w.text('Hell... |
def main():
camera = skimage.data.camera()
astronaut = rgb2gray(skimage.data.astronaut())
horse = skimage.data.horse()
coffee = rgb2gray(skimage.data.coffee())
data = [camera, astronaut, horse, coffee]
print('Start to data preprocessing...')
data = [preprocessing(d) for d in data]
model ... |
class WhoamiCommand(BaseUserCommand):
def run(self):
print(ANSI.red('WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use `huggingface-cli whoami` instead.'))
token = HfFolder.get_token()
if (token is None):
print('Not logged in')
exi... |
class InceptionV3(nn.Module):
DEFAULT_BLOCK_INDEX = 3
BLOCK_INDEX_BY_DIM = {64: 0, 192: 1, 768: 2, 2048: 3}
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False, use_fid_inception=True):
super(InceptionV3, self).__init__()
self.... |
_with_checks([KernelPCovR(mixing=0.5), PCovR(mixing=0.5), fCUR(), fFPS(), fPCovCUR(), fPCovFPS(), Ridge2FoldCV(), KernelNormalizer(), StandardFlexibleScaler()])
def test_sklearn_compatible_estimator(estimator, check):
check(estimator) |
def S3a():
var('x,y,z')
f = expand(((((x ** y) + (y ** z)) + (z ** x)) ** 500))
t1 = clock()
g = f.diff(x)
t2 = clock()
return (t2 - t1) |
def test_pcpvt_init():
path = 'PATH_THAT_DO_NOT_EXIST'
model = PCPVT(pretrained=None, init_cfg=None)
assert (model.init_cfg is None)
model.init_weights()
model = PCPVT(pretrained=None, init_cfg=dict(type='Pretrained', checkpoint=path))
assert (model.init_cfg == dict(type='Pretrained', checkpoint... |
class BatchSampler(Sampler[List[int]]):
def __init__(self, sampler: Sampler[int], batch_size: int, drop_last: bool) -> None:
if ((not isinstance(batch_size, _int_classes)) or isinstance(batch_size, bool) or (batch_size <= 0)):
raise ValueError('batch_size should be a positive integer value, but ... |
class LegacySpecifier(_IndividualSpecifier):
_regex_str = '\n (?P<operator>(==|!=|<=|>=|<|>))\n \\s*\n (?P<version>\n [^,;\\s)]* # Since this is a "legacy" specifier, and the version\n # string can be just about anything, we match everything\n ... |
def tokenize(cased_lines, tokenizer, basic_tokenizer, worker_id, batch_offset):
sents = []
for cased_line in cased_lines:
tokens = basic_tokenizer.tokenize(cased_line)
split_tokens = []
for token in tokens:
subtokens = tokenizer.tokenize(token)
split_tokens += sub... |
def init_assign(config, d, traverse):
for (full_key, value) in traverse_dfs(d, 'item', continue_type=dict):
if ((type(value) == dict) and (len(value) > 0)):
continue
(sub_cfg, sub_key) = consume_dots(config, full_key, create_default=True)
sub_cfg[sub_key] = value |
def sample_dataset(dataset, n=10000, n_eval=1000, seed=0):
for k in dataset:
n_k = (n if (k == 'train') else n_eval)
if (n_k and (len(dataset[k]) > n_k)):
dataset[k] = dataset[k].train_test_split(train_size=n_k, seed=seed)['train']
return dataset |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--dataset-folder', dest='pickle_path', help="path to the Cityscapes dataset 'gtFine' folder", default=None, type=str)
parser.add_argument('--output-folder', dest='outputFolder', help='path to the output folder.', default=None, type=str)
... |
def _load_bgzf_block(handle, text_mode=False):
magic = handle.read(4)
if (not magic):
raise StopIteration
if (magic != _bgzf_magic):
raise ValueError(('A BGZF (e.g. a BAM file) block should start with %r, not %r; handle.tell() now says %r' % (_bgzf_magic, magic, handle.tell())))
(gzip_mo... |
(datatype[(N, N)], datatype[(N, M)], datatype[(N, M)], datatype[1], datatype[1])
def syr2k(C, A, B, alpha, beta):
def mult_c_rows(i: _[0:N]):
def mult_c_cols(j: _[0:(i + 1)]):
(ic << C[(i, j)])
(ib << beta)
(oc >> C[(i, j)])
oc = (ic * ib)
def compute(i: _... |
class _AssertVisitor(ast.NodeVisitor):
def __init__(self) -> None:
super().__init__()
self.asserts: list[ast.Assert] = []
def visit_Assert(self, node: ast.Assert) -> ast.AST:
self.asserts.append(node)
return getattr(super(), 'visit_Assert', super().generic_visit)(node) |
def generate_requirements(extras_require):
for (extra, depends) in extras_require.items():
condition = ''
extra = (extra or '')
if (':' in extra):
(extra, condition) = extra.split(':', 1)
extra = pkg_resources.safe_extra(extra)
if extra:
(yield ('Provi... |
def test_tfidfvectorizer_export_idf():
vect = TfidfVectorizer(use_idf=True)
vect.fit(JUNK_FOOD_DOCS)
assert_array_almost_equal(vect.idf_, vect._tfidf.idf_) |
def add_deeplab_config(cfg):
cfg.INPUT.CROP.SINGLE_CATEGORY_MAX_AREA = 1.0
cfg.SOLVER.POLY_LR_POWER = 0.9
cfg.SOLVER.POLY_LR_CONSTANT_ENDING = 0.0
cfg.MODEL.SEM_SEG_HEAD.LOSS_TYPE = 'hard_pixel_mining'
cfg.MODEL.SEM_SEG_HEAD.PROJECT_FEATURES = ['res2']
cfg.MODEL.SEM_SEG_HEAD.PROJECT_CHANNELS = [... |
class ProtectionModelIndividual(nn.Module):
def __init__(self, optimizer, optim_args):
super().__init__()
self.attn_model = GenPix2Pix(4, 1, ngf, net_noise, norm, (not no_dropout), init_type, init_gain, att_mode=True)
self.fusion_model = GenPix2Pix(3, 3, ngf, net_noise, norm, (not no_dropout... |
def reduce_gradients(model, _type='sum'):
types = ['sum', 'avg']
assert (_type in types), 'gradients method must be in "{}"'.format(types)
log_once('gradients method is {}'.format(_type))
if (get_world_size() > 1):
for param in model.parameters():
if param.requires_grad:
... |
def ap(rec, pre):
i = np.argsort(rec)
mrec = np.concatenate(([0], np.array(rec)[i], [1]))
mpre = np.concatenate(([0], np.array(pre)[i], [0]))
assert (mrec.shape == mpre.shape)
for i in range((mpre.size - 3), (- 1), (- 1)):
mpre[i] = max(mpre[i], mpre[(i + 1)])
i = (np.nonzero((mrec[1:] !... |
def run_recipe_tests(recipe_folder='tests/recipes', script_field='Script_file', hparam_field='Hparam_file', test_field='test_debug_flags', check_field='test_debug_checks', run_opts='--device=cpu', output_folder='tests/tmp/', filters_fields=[], filters=[], do_checks=True, download_only=False, run_tests_with_checks_only=... |
def test_suppress_warnings_module():
my_mod = _get_fresh_mod()
assert_equal(getattr(my_mod, '__warningregistry__', {}), {})
def warn_other_module():
def warn(arr):
warnings.warn('Some warning 2', stacklevel=2)
return arr
np.apply_along_axis(warn, 0, [0])
assert_wa... |
def RegisterConfig(model_name):
def decorator(f):
CONFIG_REGISTRY[model_name] = f
return f
return decorator |
class IsotopeNumberDensity(ProcessingPlasmaProperty):
outputs = ('isotope_number_density',)
latex_name = ('N_{i}',)
def calculate(isotope_mass, isotope_abundance, density):
number_densities = (isotope_abundance * density)
isotope_number_density_array = (number_densities.to_numpy() / isotope_... |
class PortugueseStemmer(_StandardStemmer):
__vowels = 'aeiouaeiouaeo'
__step1_suffixes = ('amentos', 'imentos', 'uciones', 'amento', 'imento', 'adoras', 'adores', 'aco~es', 'logias', 'encias', 'amente', 'idades', 'ismos', 'istas', 'adora', 'aca~o', 'antes', 'ancia', 'logia', 'ucion', 'encia', 'mente', 'idade', ... |
('pass_through')
class PassThroughWordStemmer(WordStemmer):
def stem_word(self, word: Token) -> Token:
return word |
def indentedBlock(blockStatementExpr, indentStack, indent=True):
backup_stack = indentStack[:]
def reset_stack():
indentStack[:] = backup_stack
def checkPeerIndent(s, l, t):
if (l >= len(s)):
return
curCol = col(l, s)
if (curCol != indentStack[(- 1)]):
... |
def generate_node_procs(parallel, net_size, naming_func):
if parallel:
num_procs = int(parallel[2])
else:
num_procs = 1
group_size = (net_size / num_procs)
node_procs = {}
for i in range(net_size):
node_procs[naming_func(i)] = int((i // group_size))
return node_procs |
def _base_ring_to_fraction_field(S):
R = S.base_ring()
if isinstance(R, Field):
return S
else:
Q = R.fraction_field()
gens = R.gens()
sigmaS = S.twisting_morphism()
sigmaQ = Q.hom([Q(sigmaS(g)) for g in gens])
return Q[(S.variable_name(), sigmaQ)] |
def hillman_grassl(M):
lam = [len(row) for row in M]
l = len(lam)
Mt = transpose(M)
hook_mults = []
for (j, col_j) in enumerate(Mt):
col_j_hook_mults = []
for (r, entry) in enumerate(col_j):
if (entry != 0):
col_j_hook_mults += ([(r, j)] * entry)
h... |
class TestFiltering():
def setup_method(self):
latitude = constants.LATITUDE
longitude = constants.LONGITUDE
date_time = constants.DATETIME
user_id = constants.UID
lat_lons = np.array([[43.8430139, 10.507994], [43.54427, 10.32615], [43.70853, 10.4036], [43.77925, 11.24626], [... |
def calculate_fid_given_paths(paths, batch_size, device, dims, num_workers=1):
for p in paths:
if (not os.path.exists(p)):
raise RuntimeError(('Invalid path: %s' % p))
print(dims)
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]
model = InceptionV3([block_idx]).to(device)
(m1, s1... |
def bench_and_check(bench):
def _func(query, expected):
np.testing.assert_almost_equal(bench(query), expected, decimal=6)
return _func |
def load_caltech101silhouettes(args, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'binary'
args.dynamic_binarization = False
def reshape_data(data):
return data.reshape(((- 1), 28, 28)).reshape(((- 1), (28 * 28)), order='F')
caltech_raw = loadmat(os.path.join('data', 'Caltech10... |
def parse_args():
parser = argparse.ArgumentParser(description='MMDet test detector')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--out', help='output result file')
parser.add_argument('--corruptions', typ... |
def test_categorical_encoder_saving(tmpdir):
from speechbrain.dataio.encoder import CategoricalEncoder
encoder = CategoricalEncoder(starting_index=3)
encoding_file = (tmpdir / 'char_encoding.txt')
if (not encoder.load_if_possible(encoding_file)):
encoder.update_from_iterable('abcd')
enco... |
.experimental
def test_predict_pairs_warm_items_only(log, log_to_pred):
model = MultVAE()
model.fit(log)
recs = model.predict(log.unionByName(log_to_pred), k=3, users=log_to_pred.select('user_idx').distinct(), items=log_to_pred.select('item_idx').distinct(), filter_seen_items=False)
pairs_pred = model.p... |
def register_Ns3Asn1Header_methods(root_module, cls):
cls.add_constructor([param('ns3::Asn1Header const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'bIterator')], is_pure_virtual=True, is_virtual=True)
cls.add_method('GetInstanceTypeId'... |
def prepare_esc50(data_folder, audio_data_folder, save_json_train, save_json_valid, save_json_test, train_fold_nums=[1, 2, 3], valid_fold_nums=[4], test_fold_nums=[5], skip_manifest_creation=False):
download_esc50(data_folder)
if (type(train_fold_nums) is int):
train_fold_nums = [train_fold_nums]
if... |
def gen_normalized_adjs(dataset):
(row, col) = dataset.graph['edge_index']
N = dataset.graph['num_nodes']
adj = SparseTensor(row=row, col=col, sparse_sizes=(N, N))
deg = adj.sum(dim=1).to(torch.float)
D_isqrt = deg.pow((- 0.5))
D_isqrt[(D_isqrt == float('inf'))] = 0
DAD = ((D_isqrt.view((- 1... |
class ECQA():
def __init__(self, data_dir):
self.train_path = os.path.join(data_dir, 'cqa_data_train.csv')
self.dev_path = os.path.join(data_dir, 'cqa_data_val.csv')
self.test_path = os.path.join(data_dir, 'cqa_data_test.csv')
def get_samples(self, file_path):
samples = []
... |
def test_unflatten_returns_correct_shape() -> None:
x = tf.random.uniform([2, 3, 4, 5])
(flat_x, unflatten) = flatten_leading_dims(x)
y1 = tf.random.uniform([24, 7])
y2 = tf.random.uniform([24, 7, 11])
unflat_y1 = unflatten(y1)
unflat_y2 = unflatten(y2)
npt.assert_array_equal(tf.shape(unflat... |
class CurriculumTeacher():
def __init__(self, env, curriculum, writer=None):
self.env = env
self.curriculum = curriculum
self.writer = writer
def teach(self, num_timesteps=2000):
curriculum_step = 0
for t in range(num_timesteps):
p = self.curriculum[curriculum... |
def _dim_is_scalar_size(dim: Dim) -> bool:
if (dim.size is not None):
return True
if dim.dyn_size_ext:
return (dim.dyn_size_ext.dims == ())
return False |
def get_pseudo_label_NRL_for_one_segment_from_scratch(args, node2step, step2node, matched_nodes, G_wikihow, G_howto100m, G_wikihow_tr, G_howto100m_tr, max_hop):
khop_out_neighbors = get_khop_neighbors_inStepIDs(matched_nodes, node2step, max_hop, G_wikihow, G_howto100m)
khop_in_neighbors = get_khop_neighbors_inS... |
def make_vocab(filenames, max_vocab_size=(- 1), newline_token=None, return_type='list', return_count=False):
if (not isinstance(filenames, (list, tuple))):
filenames = [filenames]
words: List[str] = []
for fn in filenames:
words += read_words(fn, newline_token=newline_token)
counter = co... |
class GradUnknownPSF(GradPSF):
def __init__(self, data, psf, prox, psf_type='fixed', convolve_method='astropy', beta_reg=1, lambda_reg=1):
if (not hasattr(prox, 'op')):
raise ValueError('prox must have "op()" method')
self.grad_type = 'psf_unknown'
self.get_grad = self._get_grad_... |
class Sentence(object):
def __init__(self, syn_type, elements=None, tokens=None, postags=None, lemmas=None, sentnum=None):
if elements:
self.sent_num = elements[0].sent_num
self.tokens = [e.form for e in elements]
self.postags = [e.nltk_pos for e in elements]
... |
class Normal(DistributionBase):
def __init__(self, low, high, q=None, log=False) -> None:
self.low = low
self.high = high
self.q = q
self.log = log |
def _sfc(content, equality=False):
content = list(content)
a = ([0] * sum(content))
content[0] -= 1
k = len(content)
return _simple_fixed_content(a, content, 2, 1, k, equality=equality) |
class CrossAttnUpBlock3D(nn.Module):
def __init__(self, in_channels: int, out_channels: int, prev_output_channel: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, resnet_pre_norm: bool=... |
class Ind2OneHotFilter(Filter):
def __init__(self, n):
self.n = n
def __call__(self, x, update=True):
out = np.zeros(self.n)
out[x] = 1
return out
def output_shape(self, input_space):
return (input_space.n,) |
class ProxylessNASNets():
def __init__(self, net_config, net_weights=None):
self.graph = tf.Graph()
self.net_config = net_config
self.n_classes = 1000
with self.graph.as_default():
self._define_inputs()
logits = self.build(init=net_weights)
predict... |
class AnsiCodes(object):
def __init__(self):
for name in dir(self):
if (not name.startswith('_')):
value = getattr(self, name)
setattr(self, name, code_to_chars(value)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.