code stringlengths 101 5.91M |
|---|
class WaveformSignal(TimeSeries, WaveformMixin):
def __init__(self, *args, **kwargs):
raise NotImplementedError() |
class BiLinear(Layer):
def __init__(self, name='bi_linear'):
super(BiLinear, self).__init__(name)
self.projecting_layer = None
def __call__(self, t0, t1):
hidden_units = t0.shape.as_list()[(- 1)]
if (self.projecting_layer is None):
self.projecting_layer = tf.keras.lay... |
def GetTriadEdges_PUNGraph(Graph, SampleEdges=(- 1)):
return _snap.GetTriadEdges_PUNGraph(Graph, SampleEdges) |
def sample_other_than(black_list: Set[int], x: np.ndarray) -> int:
res = np.random.randint(0, len(x))
while (res in black_list):
res = np.random.randint(0, len(x))
return res |
def initialize_weights(*models):
for model in models:
for m in model.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight.data, nonlinearity='relu')
elif isinstance(m, BatchNorm2d):
m.weight.data.fill_(1.0)
m.bias.da... |
('entity_match')
class CustomEntityMatchFactory(CRFFeatureFactory):
def __init__(self, factory_config, **shared):
super(CustomEntityMatchFactory, self).__init__(factory_config, **shared)
self.use_stemming = self.args['use_stemming']
self.tagging_scheme = TaggingScheme(self.args['tagging_sche... |
_experiment
def trpo_pendulum(ctxt=None, seed=1):
set_seed(seed)
env = GarageEnv(env_name='InvertedDoublePendulum-v2')
runner = LocalRunner(ctxt)
policy = GaussianMLPPolicy(env.spec, hidden_sizes=[32, 32], hidden_nonlinearity=torch.tanh, output_nonlinearity=None)
value_function = GaussianMLPValueFun... |
def rename_keys(original_param_names):
block_names = [v.split('_')[0].split('block')[1] for v in original_param_names if v.startswith('block')]
block_names = list(set(block_names))
block_names = sorted(block_names)
num_blocks = len(block_names)
block_name_mapping = {b: str(i) for (b, i) in zip(block... |
_with_task('Doing query with k-Means')
def kmeans_query(clf, features, deep_feats, color_feats, labels, retrieval_top_n=5):
label = clf.predict(features[0].reshape(1, features[0].shape[0]))
ind = np.where((clf.labels_ == label))
d_feats = deep_feats[ind]
c_feats = color_feats[ind]
n_labels = list(np... |
def get_config():
modulenames = (set(sys.modules) & set(globals()))
allmodules = [sys.modules[name] for name in modulenames]
return {'name': 'python', 'version': platform.python_version(), 'modules': str(allmodules)} |
def run_eval_bleu(cmd):
output = check_output(cmd, shell=True, stderr=subprocess.STDOUT).decode('utf-8').strip()
print(output)
bleu = (- 1.0)
for line in output.strip().split('\n'):
m = BLEU_REGEX.search(line)
if (m is not None):
bleu = m.groups()[0]
bleu = float(... |
class Resnet_Imb_CB_beta0999_ep100_cifar100_2():
def __init__(self):
self.set_config()
def set_config(self):
self.filename_head = (self.__class__.__name__ + '_')
self.checkpoint_path = None
def get_model(self):
model = resnet.ResNet18(num_classes=100)
return model
... |
.parametrize('data', ['bin_dense_train_data', 'bin_sparse_train_data'])
.parametrize('loss', ['l1', 'l2'])
def test_fit_linear_binary(data, loss, request):
(X, y) = request.getfixturevalue(data)
clf = LinearSVC(loss=loss, random_state=0, max_iter=10)
clf.fit(X, y)
assert (list(clf.classes_) == [0, 1])
... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, cardinality=1, base_width=64, reduce_first=1, dilation=1, first_dilation=None, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, attn_layer=None, aa_layer=None, drop_block=None, drop_path=None):
super(... |
class MILSTMWithAttentionCell(AttentionCell):
def __init__(self, encoder_output_dim, encoder_outputs, decoder_input_dim, decoder_state_dim, name, attention_type, weighted_encoder_outputs, forget_bias, lstm_memory_optimization, attention_memory_optimization, forward_only=False):
decoder_cell = MILSTMCell(inp... |
def train(sess, model, train_url, test_url, batch_size, vocab_size, alternate_epochs=1, lexicon=[], result_file='test.txt', warm_up_period=100):
(train_set, train_count) = utils.data_set(train_url)
(test_set, test_count) = utils.data_set(test_url)
train_size = len(train_set)
validation_size = int((train... |
.parametrize('nntxt_idx', CASE_INDEX)
.parametrize('parameter_format', ['.protobuf', '.h5'])
.parametrize('dataset_sample_num', [32])
def test_load_and_infer_equivalence(nntxt_idx, parameter_format, dataset_sample_num):
with generate_case_from_nntxt_str(NNTXT_EQUIVALENCE_CASES[nntxt_idx], parameter_format, dataset_... |
class JTrivialSemigroups(CategoryWithAxiom):
def extra_super_categories(self):
return [Semigroups().LTrivial(), Semigroups().RTrivial()] |
def update_alpha_parameters(model, layers, p, pi, print_info=True):
standarlization = (lambda x: ((x - torch.mean(x)) / torch.std(x)))
alpha_grad_attn = torch.stack([torch.cat([getattr(model.module.visual_encoder.blocks, str(i)).attn.alpha.grad for i in range(layers)]), torch.stack([getattr(model.module.text_de... |
def hflip(in_dict, cfg):
if (np.random.random() < 0.5):
in_dict['img'] = F.hflip(in_dict['img'])
in_dict['mask'] = F.hflip(in_dict['mask']) |
def train(model, optimizer, loader):
model.train()
loss_sum = 0
acc_sum = 0
for (idx, (data, target)) in enumerate(loader):
(data, target) = (data.cuda(), target.cuda())
(data, target) = (Variable(data), Variable(target))
optimizer.zero_grad()
output = model(data)
... |
def save_checkpoint(checkpoint_manager):
if checkpoint_manager.is_checkpointing:
checkpoint_manager.saving = True
new_tmp_dest = get_temp_file('dump', 'checkpoints')
_LOG.info(('Checkpoint is being updated: %s' % new_tmp_dest))
old_tmp_file = open(checkpoint_manager.checkpoint_path).... |
def test_kmeans_inductive_gncd(merge_test_loader, args, K=None):
if (K is None):
K = (args.num_labeled_classes + args.num_unlabeled_classes)
all_feats = []
targets = np.array([])
mask_cls = np.array([])
print('Collating features...')
for (batch_idx, (feats, label, _)) in enumerate(tqdm(m... |
def _expand_braces(text, seen=None):
if (seen is None):
seen = set()
spans = [m.span() for m in re.finditer('\\{[^\\{\\}]*\\}', text)][::(- 1)]
alts = [text[(start + 1):(stop - 1)].split(',') for (start, stop) in spans]
if (len(spans) == 0):
if (text not in seen):
(yield text... |
class GlueDataTrainingArguments():
task_name: str = field(metadata={'help': ('The name of the task to train on: ' + ', '.join(glue_processors.keys()))})
data_dir: str = field(metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'})
max_seq_length: int = fie... |
def _is_in_ipython():
try:
__IPYTHON__
return True
except NameError:
pass
return False |
def _export(*args, **kwargs):
from torch.onnx import utils
return utils._export(*args, **kwargs) |
def validate_references(model: models.Model) -> None:
def process_field(parent: models.Model, child: Union[(str, optplan.ProblemGraphNodeSchema)], field_type: optplan.ReferenceType) -> None:
if (not child):
return
if ((not isinstance(child, (str, field_type.reference_type))) and (not isi... |
def get_constant(x):
if (x == inf):
return 'math.inf'
if (x == (- inf)):
return '-math.inf'
return x |
def save_summaries(file_writer, global_step=None):
global _merge_op
tfutil.assert_tf_initialized()
if (_merge_op is None):
layout = finalize_autosummaries()
if (layout is not None):
file_writer.add_summary(layout)
with tf.device(None), tf.control_dependencies(None):
... |
class Bottle2neck(_Bottleneck):
expansion = 4
def __init__(self, inplanes, planes, scales=4, base_width=26, base_channels=64, stage_type='normal', **kwargs):
super(Bottle2neck, self).__init__(inplanes, planes, **kwargs)
assert (scales > 1), 'Res2Net degenerates to ResNet when scales = 1.'
... |
class OpenEMS(Element):
def __init__(self, FDTD, CSX):
Element.__init__(self, 'openEMS')
self.append(FDTD)
self.append(CSX)
def __repr__(self):
st = ElementTree.tostring(self)
return st
def save(self, filename='openEMS.xml'):
self.filename = filename
o... |
class LayoutLMv2PreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class atlas_3_10_threads_info(atlas_3_10_info):
dir_env_var = ['PTATLAS', 'ATLAS']
_lib_names = ['tatlas']
_lib_atlas = _lib_names
_lib_lapack = _lib_names |
def unit_derivations_expr(v):
v = str(v)
Z = unit_derivations[v]
if isinstance(Z, str):
d = {x: str_to_unit(x) for x in vars_in_str(Z)}
from sage.misc.sage_eval import sage_eval
Z = sage_eval(Z, d)
unit_derivations[v] = Z
return Z |
class kappa3_gen(rv_continuous):
def _shape_info(self):
return [_ShapeInfo('a', False, (0, np.inf), (False, False))]
def _pdf(self, x, a):
return (a * ((a + (x ** a)) ** (((- 1.0) / a) - 1)))
def _cdf(self, x, a):
return (x * ((a + (x ** a)) ** ((- 1.0) / a)))
def _sf(self, x, a)... |
_builder('msvd_qa_instruct')
class MSVDQAInstructBuilder(VideoQABuilder):
train_dataset_cls = VideoQAInstructDataset
eval_dataset_cls = VideoQAInstructDataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/msvd/defaults_qa_instruct.yaml'} |
def test_deepcopy():
modela = ModelA({'int_field': 1, 'list_int_field': [2, 3], 'model_field': {'value': 4}, 'list_model_field': [{'value': 5}, {'value': 6}]})
modela_copy = copy.deepcopy(modela)
assert (modela_copy.int_field == 1)
assert (modela_copy.list_int_field == [2, 3])
assert (modela_copy.mo... |
def ref_bit_shift(x, shift, direction):
if (direction == 'LEFT'):
return (x << shift)
elif (direction == 'RIGHT'):
return (x >> shift)
else:
raise ValueError('Invalid direction: {}'.format(direction)) |
def add_weight_args_preprocessing(args, kwargs):
if (len(args) > 1):
if isinstance(args[1], (tuple, list)):
kwargs['shape'] = args[1]
args = ((args[0],) + args[2:])
if (len(args) > 1):
if isinstance(args[1], six.string_types):
kwargs['n... |
def timit_posteriorgram_url(ckpt, refresh=False, *args, **kwargs):
return timit_posteriorgram_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs) |
('/ngsi10/updateContext', methods=['POST'])
def getUpdateNotification():
data = request.get_json()
if (data.has_key('contextElements') == True):
dataContext = data['contextElements']
dataAttribute = dataContext[0]
if (dataAttribute.has_key('attributes') == True):
attribute = ... |
class KernelizedDoublyRobust(BaseContinuousOffPolicyEstimator):
kernel: str
bandwidth: float
estimator_name: str = 'kernelized_dr'
def __post_init__(self) -> None:
if (self.kernel not in ['gaussian', 'epanechnikov', 'triangular', 'cosine']):
raise ValueError(f"kernel must be one of '... |
class DaskLFApplier(BaseLFApplier):
def apply(self, df: dd.DataFrame, scheduler: Scheduler='processes', fault_tolerant: bool=False) -> np.ndarray:
f_caller = _FunctionCaller(fault_tolerant)
apply_fn = partial(apply_lfs_to_data_point, lfs=self._lfs, f_caller=f_caller)
map_fn = df.map_partitio... |
def add_arguments_oss(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
parser.add_argument('--run-only', help='only run certain test(s), for example: atest test_nn.py.', nargs='*', default=None)
return parser |
class BalancedBatchSampler(BatchSampler):
def __init__(self, labels, all_speech, n_classes, n_samples):
self.labels = np.array(labels)
self.labels_set = list(set(self.labels))
self.label_to_indices = {label: np.where((self.labels == label))[0] for label in self.labels_set}
for l in s... |
def compute_high_actor_loss(agent, batch, network_params):
cur_goals = batch['high_goals']
(v1, v2) = agent.network(batch['observations'], cur_goals, method='value')
(nv1, nv2) = agent.network(batch['high_targets'], cur_goals, method='value')
v = ((v1 + v2) / 2)
nv = ((nv1 + nv2) / 2)
adv = (nv ... |
class MultiAgentWrapper(gym.Wrapper, MultiAgentEnv):
def __init__(self, game, cfg: Config):
self.env = disable_passive_env_checker(game)
gym.Wrapper.__init__(self, self.env)
MultiAgentEnv.__init__(self.env)
self.n_agents = cfg.multiagent.n_agents
self.observation_space = gym.... |
def tf_scope():
with tf_compat.v1.Graph().as_default(), tf_compat.v1.Session().as_default() as session:
(yield session) |
def register_Ns3PssFlowPerf_t_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::pssFlowPerf_t const &', 'arg0')])
cls.add_instance_attribute('flowStart', 'ns3::Time', is_const=False)
cls.add_instance_attribute('lastAveragedThroughput', 'double', is_const=False)
cls.... |
def main():
modelname = GetModelAndOptNames()
FLAGS = getFlags(modelname)
args.print_flag(FLAGS)
cross_validate(modelname, FLAGS) |
def DenseNet169(nclass):
return DenseNet(Bottleneck, [6, 12, 32, 32], growth_rate=32, num_classes=nclass) |
def setup_logger(name, save_dir, prefix, distributed_rank):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
if (distributed_rank > 0):
return logger
ch = logging.StreamHandler(stream=sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(message)s')
c... |
def test_load_optimizer_old_format():
config = Config(dict(optimizer={'class': 'adamw', 'weight_decay': 0.001}))
model = torch.nn.Linear(7, 5)
updater = Updater(config=config, network=model, device=torch.device('cpu'))
updater.create_optimizer()
with tempfile.TemporaryDirectory(prefix='returnn_test_... |
def cvector_to_numpy(vector: Union[(pyrenderer.real3, pyrenderer.real4)]):
if isinstance(vector, pyrenderer.real3):
return np.array([vector.x, vector.y, vector.z], dtype=renderer_dtype_np)
elif isinstance(vector, pyrenderer.real4):
return np.array([vector.x, vector.y, vector.z, vector.w], dtype=... |
def enveloping_profile_elements(alist, char=2):
if (char == 2):
profiles = [profile_elt(x) for x in alist if (x != 0)]
if (not profiles):
return (0,)
if (len(profiles) == 1):
return profiles[0]
return find_min_profile((max(*a) for a in zip_longest(*profiles, f... |
def convertAttributeProto(onnx_arg):
if onnx_arg.HasField('f'):
return onnx_arg.f
elif onnx_arg.HasField('i'):
return onnx_arg.i
elif onnx_arg.HasField('s'):
return onnx_arg.s
elif onnx_arg.HasField('t'):
return onnx_arg.t
elif onnx_arg.HasField('g'):
return C... |
.torch
def test_sasrec_forward_with_float_timematrix(tensor_schema, simple_masks):
model = SasRecModel(tensor_schema.subset(['item_id', 'timestamp']), hidden_size=64, max_len=5, ti_modification=True)
(item_sequences, padding_mask, _, timestamp_sequences) = simple_masks
timestamp_sequences = timestamp_sequen... |
def linear_classifier(layer, output_size, hidden_keep_prob=1.0):
layer_shape = nn.get_sizes(layer)
input_size = layer_shape.pop()
weights = tf.get_variable('Weights', shape=[input_size, output_size], initializer=tf.zeros_initializer)
biases = tf.get_variable('Biases', shape=[output_size], initializer=tf... |
(_float_ftylists, '(n)->(n)')
def diff_reverse(a_in, a_out):
a_out[0] = a_in[0]
for i in range(1, a_in.shape[0]):
a_out[i] = (a_out[(i - 1)] - a_in[i]) |
_model
def swsl_resnext101_32x8d(pretrained=True, **kwargs):
model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], cardinality=32, base_width=8, **kwargs)
return _create_resnet('swsl_resnext101_32x8d', pretrained, **model_args) |
class ZippedDataset(torch.utils.data.Dataset):
def __init__(self, *components):
assert (len(components) >= 1)
lengths = [len(c) for c in components]
assert all(((lengths[0] == other) for other in lengths[1:])), "Lengths don't match: {}".format(lengths)
self.components = components
... |
def LF_single_char_rgx(s, dict_lf):
m = re.search('\\b(r/r/w|m/r/g|n/v/d|n/v|c/c/e|f/c/s|mg/r)\\b', s.text, re.I)
label = (2 if (not m) else 1)
char_dict = {'c', 'd', 'e', 'f', 'g', 'm', 'n', 'r', 's', 'v', 'w'}
L = {}
for (i, tok) in enumerate(s.words):
if (tok.lower() in char_dict):
... |
class BNFNetTest(BasePytorchTest):
def __init__(self, unit_test):
super().__init__(unit_test)
def create_inputs_shape(self):
return [[self.val_batch_size, 3, 32, 32], [self.val_batch_size, 3, 32, 32]]
def create_feature_network(self, input_shape):
return BNFNet() |
def train(args, ckpt_dir, loader, generator, discriminator, g_optim, d_optim, g_ema, device, writer):
get_inception_metrics = prepare_inception_metrics(args.inception, False)
sample_fn = functools.partial(sample_gema, g_ema=g_ema, device=device, truncation=1.0, mean_latent=None, batch_size=args.batch)
loade... |
class MBart50TokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
model_input_names = ['input_ids', 'attention_mask']
slow_tokenizer_class = MBart50Tokenize... |
class TrajectoryEncoder(object):
def __init__(self):
self.encoding_dim = 8
self.input_size = 3
self.grad_clip = 10.0
self.learning_rate = 0.005
self.build_model()
def build_model(self):
self.inputs = tf.placeholder(tf.float32, (self.seq_length, self.max_num_obj, s... |
def test_copy_from():
shape = [2, 3, 4]
src = nn.NdArray(shape)
dst = nn.NdArray(shape)
src.data = 0
src.cast(dtype=np.uint8)
dst.copy_from(src, use_current_context=False)
assert (dst.dtype == np.uint8)
from nnabla.ext_utils import get_extension_context
with nn.context_scope(get_exte... |
class ChessLMDataModule(LightningDataModule):
def __init__(self, data_dir=None, vocab_dir=None, batch_size=8, num_workers=1, train_size=1000000.0, n_positions=800, other_eval=True, rap_prob=0.0, rap_no_grad=False, oracle=False, model_type='transformer', **kwargs):
super().__init__()
self.other_eval ... |
class FSRNet(nn.Module):
def __init__(self):
super(FSRNet, self).__init__()
self.coarse_SR = CoarseSR()
self.fine_SR = FineSR()
self.prior_estimation = PriorEstimation()
def forward(self, img):
img_coarse = self.coarse_SR(img)
(landmark, face_parsing) = self.prior... |
def encode_dataset(dataset, vocab, test=False):
questions = []
sparqls = []
choices = []
answers = []
for question in tqdm(dataset):
q = [vocab['word_token_to_idx'].get(w, vocab['word_token_to_idx']['<UNK>']) for w in word_tokenize(question['question'].lower())]
questions.append(q)
... |
class I7PoolFunction(Function):
def forward(ctx, input, guide):
(output, maxout) = _C.I7_pool_forward(input, guide)
ctx.save_for_backward(input, output, guide, maxout)
return output
def backward(ctx, grad_output):
(input, output, guide, maxout) = ctx.saved_variables
(grad... |
def rename_rirs(decompress_path):
try:
os.rename(os.path.join(decompress_path, 'simulated_rirs_16k'), os.path.join(decompress_path, 'SLR26'))
except Exception:
pass
try:
os.rename(os.path.join(decompress_path, 'RIRS_NOISES'), os.path.join(decompress_path, 'SLR28'))
except Excepti... |
def get_device(tensors):
if isinstance(tensors, (list, tuple)):
return get_device(tensors[0])
elif isinstance(tensors, dict):
for (key, value) in tensors.items():
return get_device(value)
else:
return tensors.device |
def configure_satellite_container():
base_path = 'satellite/config/'
conf_file = (base_path + 'sat.conf')
change_line(conf_file, 17, (('emu_ipv4 = ' + str(os.getenv('EMU_NETWORK_HEAD'))) + '.0.2/24')) |
class MockRegexPattern(object):
def __init__(self, target_type):
self.type = target_type
def match(self, text):
try:
self.type(text)
except ValueError:
return False
return True |
.experimental
.parametrize('pad_columns', ['user_id'])
.usefixtures('dataframe')
def test_not_array_column(pad_columns, dataframe):
with pytest.raises(ValueError):
padder = Padder(pad_columns=pad_columns)
padder.transform(dataframe) |
def process_literal(value: str):
pattern_date = '(?:(?:jan.|feb.|mar.|apr.|may|jun.|jul.|aug.|sep.|oct.|nov.|dec.) the \\d+(?:st|nd|rd|th), \\d{4}|\\d{4}-\\d{2}-\\d{2}|\\d{2}/\\d{2}/\\d{4})'
pattern_datetime = '\\d{4}-\\d{2}-\\d{2}t[\\d:z-]+'
pattern_float = '(?:[-]*\\d+[.]*\\d*e[+-]\\d+|(?<= )[-]*\\d+[.]\\... |
def _check_params(length, size):
_check_size(size)
if ((length % size) != 0):
raise error('not a whole number of frames') |
class NeuralMatrixFactorizationModel(keras.Model):
def __init__(self, num_users, num_items, embed_mf_size, embed_mlp_size, mlp_hidden_size, dropout, is_mf_train, is_mlp_train, learning_rate=0.01, random_seed=42, name='NeuralMatrixFactorizationModel', **kwargs):
super().__init__(name=name, **kwargs)
... |
def load_cluster_config(path):
if path:
path = os.path.join(dirname(__file__), os.path.expandvars(path))
dcc = io.load_configfile(path)
else:
dcc = {}
if ('__default__' not in dcc):
dcc['__default__'] = {}
return dcc |
class StepLR(_LRScheduler):
def __init__(self, optimizer, step_size, gamma=0.1, last_epoch=(- 1), verbose=False):
self.step_size = step_size
self.gamma = gamma
super(StepLR, self).__init__(optimizer, last_epoch, verbose)
def get_lr(self):
if (not self._get_lr_called_within_step):... |
def BatchIncremental(nominal_attributes=None):
warnings.warn("'BatchIncremental' has been renamed to 'BatchIncrementalClassifier' in v0.5.0.\nThe old name will be removed in v0.7.0", category=FutureWarning)
return BatchIncrementalClassifier(nominal_attributes=nominal_attributes) |
class NOISE_TRANSFORMATIONS(Enum):
GAUSSIAN = 'gaussian'
LOCALVAR = 'localvar'
POISSON = 'poisson'
SALT = 'salt'
PEPPER = 'pepper'
SALTNPEPPER = 's&p'
SPECKLE = 'speckle' |
def require_scatter(test_case):
if (not is_scatter_available()):
return unittest.skip('test requires PyTorch Scatter')(test_case)
else:
return test_case |
def compute_validation_loss(loss_fn: Callable, dataset: Iterable, max_batches: Optional[int]=None, name: Optional[str]=None):
def compute_loss(info: StepInfo):
loss = eval_loss_loop(loss_fn, info.model, dataset, max_batches=max_batches, name=name)
if (wandb.run is not None):
prefix = 'ev... |
def deconv2d_bn_act(data, num_filter, kernel=(1, 1), stride=(1, 1), pad=(0, 0), adj=(0, 0), no_bias=True, target_shape=None, act_type='relu', momentum=0.9, eps=(1e-05 + 1e-12), fix_gamma=True, name='deconv2d', use_global_stats=False, **kwargs):
global _params
deconv = deconv2d(data=data, num_filter=num_filter, ... |
class SEResNeXtBottleneck(Bottleneck):
expansion = 4
def __init__(self, inplanes, planes, groups, reduction, stride=1, downsample=None, base_width=4):
super(SEResNeXtBottleneck, self).__init__()
width = (math.floor((planes * (base_width / 64))) * groups)
self.conv1 = nn.Conv2d(inplanes, ... |
def BIBD_196_6_1():
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
from .incidence_structures import IncidenceStructure
a = 'a'
bibd = [((0, 0), (2, 0), (12, 0), (45, 0), (3, 1), (11, a)), ((0, 0), (3, 0), (8, 0), (5, 1), (17, 1), (39, a)), ((0, 0), (9, 0), (36, 0), (24, 1), (... |
class TestChipIO(object):
def test_chip2020_task1(self):
io = ChipIO(tokenize_callback='char', sep='|||', encoding='utf-8')
(train_data, train_errors, train_mismatches) = io.read('data/chip2020/task1/train_data.txt', return_errors=True)
(dev_data, dev_errors, dev_mismatches) = io.read('data/... |
def get_random_nodelist(G, A, num_tests):
nodelist = ([None] * num_tests)
for k in range(num_tests):
i = random.randint(0, (G.numNodes() - 1))
while (A[i] == NA_VALUE):
i = random.randint(0, (G.numNodes() - 1))
nodelist[k] = i
return nodelist |
class MyMaxPool1dPadSame(nn.Module):
def __init__(self, kernel_size):
super(MyMaxPool1dPadSame, self).__init__()
self.kernel_size = kernel_size
self.stride = 1
self.max_pool = torch.nn.MaxPool1d(kernel_size=self.kernel_size)
def forward(self, x):
net = x
in_dim = ... |
_tf
class TFBertModelTest(TFModelTesterMixin, unittest.TestCase):
all_model_classes = ((TFBertModel, TFBertForMaskedLM, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification) if is_tf_available() else ())
class TFBertMode... |
def get_dset_features(dset, model=None, num_workers=12, num=None, shuffle=False, seed=0, batch_size=128, device=torch.device('cuda'), mode='clean', custom_fn_resize=None, description='', verbose=True, custom_image_transform=None):
dataset = ResizeDataset(dset, mode=mode)
if (custom_image_transform is not None):... |
_module()
class DynamicMaskHead(FCNMaskHead):
def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, dynamic_conv_cfg=dict(type='DynamicConv', ... |
def export_music(score, beat_data, chord_data, filename, repeat_chord=REPEAT_CHORD, outputs_path=OUTPUTS_PATH, water_mark=WATER_MARK):
harmony_list = []
offset = 0.0
filename = os.path.basename(filename)
filename = '.'.join(filename.split('.')[:(- 1)])
for (idx, song_chord) in enumerate(chord_data):... |
def main(args):
data_conf = {'num_channels': (NUM_CLASSES + 1), 'image_size': args.image_size, 'xbound': args.xbound, 'ybound': args.ybound, 'zbound': args.zbound, 'dbound': args.dbound, 'thickness': args.thickness, 'angle_class': args.angle_class, 'cams': ['CAM_FRONT_LEFT', 'CAM_FRONT', 'CAM_FRONT_RIGHT', 'CAM_BAC... |
.unit
.convert
def test_get_marker_file_name():
test_file_name = './test/test_file.cat'
expected_marker_file_name = 'test_file.cat.js'
actual_marker_file_name = convert.get_marker_file_name(test_file_name)
assert (expected_marker_file_name == actual_marker_file_name) |
def melspectrogram(y):
D = _stft(preemphasis(y))
S = (_amp_to_db(_linear_to_mel(np.abs(D))) - hparams.ref_level_db)
return _normalize(S) |
def test_matching():
width = 128
n_circles = 5
y = np.zeros((width, width), np.uint16)
for (i, r) in enumerate(np.linspace(0, width, (n_circles + 2))[1:(- 1)]):
(rr, cc) = disk(((width // 2), r), radius=(width // (3 * n_circles)), shape=y.shape)
y[(rr, cc)] = (i + 1)
for shift in (0,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.