code stringlengths 101 5.91M |
|---|
def normalize(x, alpha=900, beta=1, num_iters=100, sample=1, method='gmm', use_cuda=False, verbose=False):
if (method == 'affine'):
mu = x.mean()
std = x.std()
mu = float(mu)
std = float(std)
metadata = {'mu': mu, 'std': std, 'pi': 1}
x = ((x - mu) / std)
x = ... |
def read_args():
parse_bool = (lambda b: bool(distutils.util.strtobool(b)))
parser = argparse.ArgumentParser(description='Training framework for Rainbow DQN\n - supports environments from the ALE (via gym), gym-retro and procgen\n - individial components of Rainbow can be adjusted with cli args (below)\n - u... |
def func():
generator = abc_xyz_generator()
result = ''
for letter in generator:
if ((letter == 'x') or (letter == 'a')):
result += letter
return result |
def conv4(in_planes, out_planes, stride=2):
return nn.Sequential(nn.Conv2d(in_planes, out_planes, 3, stride, 1), nn.PReLU(out_planes), nn.Conv2d(out_planes, out_planes, 3, 1, 1), nn.PReLU(out_planes), nn.Conv2d(out_planes, out_planes, 3, 1, 1), nn.PReLU(out_planes), nn.Conv2d(out_planes, out_planes, 3, 1, 1), nn.PR... |
.expansion
class ExpandPgemmMKLOpenMPI(ExpandTransformation):
environments = [environments.intel_mkl_openmpi.IntelMKLScaLAPACKOpenMPI]
def expansion(node, parent_state, parent_sdfg, **kwargs):
return ExpandPgemmMKLMPICH.expansion(node, parent_state, parent_sdfg, **kwargs) |
class TestOldDoctestSageScript():
def test_invoke_on_inputtest_file(self):
result = subprocess.run(['sage', '-t', input_file], capture_output=True, text=True)
assert (result.returncode == 1)
assert ('Failed example:\n something()\nExpected:\n 44\nGot:\n 42\n' in result.stdout) |
def get_args():
parser = argparse.ArgumentParser(description='Training')
parser.add_argument('--load-model', action=LoadFromCheckpoint, help='Restart training using a model checkpoint')
parser.add_argument('--conf', '-c', type=open, action=LoadFromFile, help='Configuration yaml file')
parser.add_argumen... |
.parametrize('seed', [412])
.parametrize('batch_size', [2, 16])
.parametrize('grid_size', [2, 8])
.parametrize('feature_size', [4])
.parametrize('m, M', [((- 1), 1)])
.parametrize('sym_backward', [False, True])
def test_tv_loss_on_triline_forward_backward(seed, batch_size, grid_size, feature_size, m, M, sym_backward):
... |
class A000012(SloaneSequence):
def __init__(self):
SloaneSequence.__init__(self, offset=0)
def _repr_(self):
return "The all 1's sequence."
def _eval(self, n):
return ZZ.one() |
def filter_invalid_unicode(text):
return (('', True) if isinstance(text, bytes) else (text, False)) |
def uninstall() -> None:
from ....specs import openapi
openapi.unregister_string_format('uuid') |
class HardTanhInterface(HardTanh):
def __average(self, fun, a, v, rho):
m = check_m(v, rho)
v_eff = (self.var_noise + v)
H_f1 = H2(_f, args=(a, m, v_eff, self.thres, fun, 0), epsrel=1e-07)
H_f2 = H2(_f, args=(a, m, v_eff, self.thres, fun, 1), epsrel=1e-07)
H_f3 = H2(_f, args=... |
class SkewPolynomialRing(OrePolynomialRing):
def __init__(self, base_ring, morphism, derivation, name, sparse, category=None):
if (derivation is not None):
raise NotImplementedError
if (self.Element is None):
import sage.rings.polynomial.skew_polynomial_element
se... |
def scoreAlignment(aScore, bScore):
def convertScoreToListOfPitches(aScore):
def getPitches(el):
if isinstance(el, music21.note.Note):
return [el.pitch.midi]
elif isinstance(el, music21.chord.Chord):
currentList = []
for pitch in el.pit... |
def english():
output_dir = 'data'
GLUE = '
glue_dir = os.path.join(output_dir, 'GLUE')
get_data(GLUE.format('CoLA'), glue_dir, 'COLA', dataset_dir=os.path.join(glue_dir, 'CoLA'))
get_data(GLUE.format('SST-2'), glue_dir, 'SST-2', dataset_dir=os.path.join(glue_dir, 'SST-2'))
get_data(GLUE.format(... |
def load_tiff(path, standardize=False):
image = Image.open(path)
fp = image.fp
image.load()
fp.close()
if standardize:
image = np.array(image, copy=False)
image = ((image - image.mean()) / image.std())
image = Image.fromarray(image)
return image |
def _test_mpi(info, sdfg, dtype):
from mpi4py import MPI as MPI4PY
comm = MPI4PY.COMM_WORLD
rank = comm.Get_rank()
commsize = comm.Get_size()
drank = ((rank + 1) % commsize)
srank = (((rank - 1) + commsize) % commsize)
mpi_sdfg = None
if (commsize < 2):
raise ValueError('This tes... |
def get_track_box(annotation: Dict[(str, Any)], center_coordinates: Tuple[(float, float)], center_pixels: Tuple[(float, float)], resolution: float=0.1) -> np.ndarray:
assert (resolution > 0)
location = annotation['translation'][:2]
yaw_in_radians = quaternion_yaw(Quaternion(annotation['rotation']))
(row... |
def fail_if_equal(actual, desired, err_msg=''):
if isinstance(desired, dict):
if (not isinstance(actual, dict)):
raise AssertionError(repr(type(actual)))
fail_if_equal(len(actual), len(desired), err_msg)
for (k, i) in desired.items():
if (k not in actual):
... |
class CaseInsensitiveChoices(list):
def __init__(self, iterable):
super().__init__(iterable)
def __contains__(self, other):
return any([element for element in self if (element.lower() == other.lower())]) |
def align_comments(tlist):
[align_comments(sgroup) for sgroup in tlist.get_sublists()]
idx = 0
token = tlist.token_next_by_instance(idx, sql.Comment)
while token:
before = tlist.token_prev(tlist.token_index(token))
if isinstance(before, sql.TokenList):
grp = tlist.tokens_betw... |
def dist_vector(point, exemplar_dict, data):
result = {}
for cluster in exemplar_dict:
result[cluster] = min_dist_to_exemplar(point, exemplar_dict[cluster], data)
return np.array(list(result.values())) |
def inference(model, test_loader, num_query, return_f=False):
print('Test')
model.eval()
metric = R1_mAP(num_query, 500)
features = OrderedDict()
with torch.no_grad():
for (ii, batch) in enumerate(test_loader):
(data, pid, cmp, fnames) = batch
data = (data.to('cuda') ... |
def test3d_float32():
query_pts = np.array([[787014.438, (- 340616.906), 6313018.0], [751763.125, (- 59925.969), 6326205.5], [769957.188, (- 202418.125), 6321069.5]], dtype=np.float32)
kdtree = KDTree(data_pts_real.astype(np.float32))
(dist, idx) = kdtree.query(query_pts, sqr_dists=True)
epsilon = 1e-05... |
def sum(input, labels=None, index=None):
(count, sum) = _stats(input, labels, index)
return sum |
_level_function()
def sum(array, axis=None, *, keepdims=False, mask_identity=False, highlevel=True, behavior=None, attrs=None):
(yield (array,))
return _impl(array, axis, keepdims, mask_identity, highlevel, behavior, attrs) |
def issequence(t) -> bool:
return ((isinstance(t, (list, tuple)) and ((len(t) == 0) or np.isscalar(t[0]))) or (isinstance(t, np.ndarray) and (t.ndim == 1))) |
def xpos_vocab_factory(data, shorthand):
if (shorthand in ['af_afribooms', 'grc_perseus', 'ar_padt', 'bg_btb', 'cs_cac', 'cs_fictree', 'cs_pdt', 'gl_ctg', 'gl_treegal', 'it_isdt', 'it_postwita', 'la_perseus', 'lv_lvtb', 'ro_rrt', 'sk_snk', 'sl_ssj', 'sl_sst', 'uk_iu']):
return XPOSVocab(data, shorthand, idx... |
class TestDataLayout(unittest.TestCase):
def setUp(self):
self.frng1 = FmapRange((0, 0, 0, 0), (4, 4, 16, 16))
self.region1 = NodeRegion(dim=PhyDim2(2, 2), origin=PhyDim2(1, 1), type=NodeRegion.DRAM)
self.part1 = PartitionScheme(order=range(pe.NUM), pdims=(PhyDim2(1, 1), PhyDim2(2, 1), PhyDi... |
def compute_returns_yaml(f: NativeFunction) -> Tuple[(List[Dict[(str, str)]], Dict[(str, str)])]:
name_to_field_name: Dict[(str, str)] = {}
returns = []
for (i, r) in enumerate(f.func.returns):
if f.func.name.name.inplace:
assert (i == 0), 'illegal inplace function with multiple returns'... |
class ImageSoftmaxEngine(torchreid.engine.ImageSoftmaxEngine):
def run(self, save_dir='log', max_epoch=0, start_epoch=1, print_freq=10, fixbase_epoch=0, open_layers=None, start_eval=1, eval_freq=(- 1), test_only=False, dist_metric='euclidean', normalize_feature=False, visrank=False, visrank_topk=10, use_metric_cuhk... |
class TestMinrelpath(object):
def test_1(self):
n = (lambda path: path.replace('/', sep))
assert_equal(minrelpath(n('aa/bb')), n('aa/bb'))
assert_equal(minrelpath('..'), '..')
assert_equal(minrelpath(n('aa/..')), '')
assert_equal(minrelpath(n('aa/../bb')), 'bb')
asser... |
class UniformHistogramMiner(BaseTupleMiner):
def __init__(self, num_bins=100, pos_per_bin=10, neg_per_bin=10, **kwargs):
super().__init__(**kwargs)
self.num_bins = num_bins
self.pos_per_bin = pos_per_bin
self.neg_per_bin = neg_per_bin
self.add_to_recordable_attributes(list_of... |
def SResNet34(Q_l, input_channels=3, imsize=32, output_dim=10):
return SResNet(BasicBlock, [3, 4, 6, 3], Q_l, input_channels, imsize, output_dim) |
def FinitelyGeneratedAbelianPresentation(int_list):
from sage.groups.free_group import _lexi_gen
check_ls = [Integer(x) for x in int_list if (Integer(x) >= 0)]
if (len(check_ls) != len(int_list)):
raise ValueError('input list must contain nonnegative entries')
col_sp = diagonal_matrix(int_list).... |
class Adafactor(torch.optim.Optimizer):
def __init__(self, params, lr=None, eps=(1e-30, 0.001), clip_threshold=1.0, decay_rate=(- 0.8), beta1=None, weight_decay=0.0, scale_parameter=True, relative_step=True, warmup_init=False):
if ((lr is not None) and relative_step):
raise ValueError('Cannot co... |
_dispatch
def hfft2(x, s=None, axes=((- 2), (- 1)), norm=None, overwrite_x=False, workers=None, *, plan=None):
return (Dispatchable(x, np.ndarray),) |
def render_cat_num(itmdt: Intermediate, cfg: Config) -> Dict[(str, Any)]:
plot_width = (cfg.plot.width if (cfg.plot.width is not None) else 450)
plot_height = (cfg.plot.height if (cfg.plot.height is not None) else 400)
tabs: List[Panel] = []
htgs: Dict[(str, List[Tuple[(str, str)]])] = {}
(data, x, ... |
def get_embedding_layer(num_embeddings, embedding_dim, padding_idx=None):
emb = nn.Embedding(num_embeddings, embedding_dim, padding_idx)
nn.init.normal_(emb.weight, mean=0, std=(embedding_dim ** (- 0.5)))
nn.init.constant_(emb.weight[padding_idx], 0)
return emb |
class GPTNeoPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def get_intervention(action, time):
action_to_intervention_map = {0: Intervention(time=time, nonmedical_incidence=0.0, illicit_incidence=0.0), 1: Intervention(time=time, nonmedical_incidence=0.0, illicit_incidence=0.05), 2: Intervention(time=time, nonmedical_incidence=0.05, illicit_incidence=0.0), 3: Intervention(t... |
.operations('create_user', 'get_user', 'update_user')
def test_add_link_by_reference(schema_url):
schema = schemathesis.from_uri(schema_url)
links = add_link(schema, '#/paths/~1users~1{user_id}/get', parameters={'userId': '$response.body#/id'})
assert (links['#/paths/~1users~1{user_id}/get'] == {'operationR... |
class ParseResults(object):
def __new__(cls, toklist=None, name=None, asList=True, modal=True):
if isinstance(toklist, cls):
return toklist
retobj = object.__new__(cls)
retobj.__doinit = True
return retobj
def __init__(self, toklist=None, name=None, asList=True, modal... |
class Partition9(nn.Module):
LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[encoder]/T5Block[12]/T5LayerSelfAttention[0]/T5Attention[SelfAttention]/Dropout[dropout]', 'T5ForConditionalGeneration/T5Stack[encoder]/T5Block[12]/T5LayerSelfAttention[0]/T5Attention[SelfAttention]/Linear[o]', 'T5ForConditionalGenerat... |
class ClassSpecificDistributedSampler(_DistributedSampler):
def __init__(self, dataset, num_replicas=None, rank=None, dynamic_length=True, shuffle=True, seed=0):
super().__init__(dataset, num_replicas=num_replicas, rank=rank)
self.shuffle = shuffle
if (type(dataset).__name__ == 'RepeatDatase... |
.parametrize('num_of_slices', [2, 3, 5])
.parametrize('size', [197, 124])
.parametrize('batch_size', [1, 20])
.parametrize('shuffle', [False, True])
def test_sliced_data_iterator_race_condition(num_of_slices, size, batch_size, shuffle):
from nnabla.utils.data_source_implements import CacheDataSource
from nnabla... |
class set_no_jit():
def __init__(self, mode: bool) -> None:
global _NO_JIT
self.prev = _NO_JIT
_NO_JIT = mode
def __enter__(self) -> None:
pass
def __exit__(self, *args: Any) -> bool:
global _NO_JIT
_NO_JIT = self.prev
return False |
def gemm(A: dace.float32[(M, K)], B: dace.float32[(K, N)], C: dace.float32[(M, N)], alpha: dace.float32, beta: dace.float32):
C[:] = (((alpha * A) B) + (beta * C)) |
class GenerationMixin(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def main():
DEBUG = False
parser = argparse.ArgumentParser(description='CTRL-UDA Training')
parser.add_argument('--machine', type=int, default=(- 1), help='which machine to use')
parser.add_argument('--expid', type=int, default=1, help='experiment id')
parser.add_argument('--reso', type=str, default... |
def test_ClusterNodeSequence_init():
G = create_stellargraph()
nsg = ClusterNodeSequence(graph=G, clusters=[list(G.nodes())])
assert (len(nsg) == 1)
nsg = ClusterNodeSequence(graph=G, clusters=[['a'], ['b', 'd'], ['c']])
assert (len(nsg) == 3)
with pytest.raises(ValueError):
ClusterNodeS... |
def setup(app):
app.connect('builder-inited', setup_link_role)
return {'version': '0.1', 'parallel_read_safe': True} |
class TMIn(TSIn):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
_snap.TMIn_swiginit(self, _snap.new_TMIn(*args))
def New(*args):
return _snap.TMIn_New(*args)
New = staticmet... |
def test_animation():
params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 500, 'seed': 1, 'diffusion': 'max', 'method': 'add_edge_random', 'k': 15, 'plot_transition': False, 'gif_animation': True}
run_test(params) |
class Discriminator(nn.Module):
def __init__(self, opt=None):
super(Discriminator, self).__init__()
self.nc = 32
if (opt is not None):
stride_v1 = (1, 2, 2)
stride_v2 = (2, 2, 2)
stride = (stride_v1, stride_v2)[(opt.sample_duration == 16)]
else:
... |
def ksp_options():
return {'ksp_type': 'cg', 'pc_type': 'hypre', 'pc_hypre_type': 'boomeramg', 'ksp_rtol': 0.0, 'ksp_atol': 0.0, 'ksp_max_it': 1, 'ksp_monitor_true_residual': None} |
class GreedyMaskCalculator():
def __init__(self, prunable_nodes: List[BaseNode], fw_info: FrameworkInfo, simd_groups_scores: Dict[(BaseNode, np.ndarray)], target_kpi: KPI, graph: Graph, fw_impl: PruningFrameworkImplementation, tpc: TargetPlatformCapabilities, simd_groups_indices: Dict[(BaseNode, List[List[int]])]):... |
class ModuleFloatShadow(nn.Module):
def __init__(self, module):
super(ModuleFloatShadow, self).__init__()
self.original_module = module
self.float_module = deepcopy(module)
self.float_module.to(dtype=torch.float)
def parameters(self, *kargs, **kwargs):
return self.float_m... |
def function_namespace(declaration):
if (has_tensor_options(declaration) or op_name(declaration).endswith('_like')):
return 'torch'
else:
return 'at' |
class LandscapeAsModel(Model):
def __init__(self, landscape: flexs.Landscape):
super().__init__(f'LandscapeAsModel={landscape.name}')
self.landscape = landscape
def _fitness_function(self, sequences: SEQUENCES_TYPE) -> np.ndarray:
return self.landscape._fitness_function(sequences)
de... |
def _try_make_config_directory(path: PathLike) -> None:
try:
Path(path).parent.mkdir(mode=493, parents=True, exist_ok=True)
except OSError:
pass |
def in_bounds(val: Any, domain: Any) -> bool:
if (isinstance(val, Sequence) or isinstance(val, np.ndarray)):
if (isinstance(domain[0], Sequence) or isinstance(domain[0], np.ndarray)):
if (len(val) == len(domain)):
return all((((v >= d[0]) and (v <= d[1])) for (v, d) in zip(val, d... |
def get_args_and_hdf5_file(activation, network):
output_name = ('run_%s_%s_%s' % (activation.replace(':', '-'), network[0], network[1]))
parameters = [sys.executable, 'volnet/train_volnet.py', CONFIG_FILE, '--train:mode', 'world', '--train:samples', '256**3', '--train:batchsize', '64*64*128', '--train:sampler_i... |
class ProgressBarLogger(ProgressLogger):
bar_indent = 2
def __init__(self, init_state=None, bars=None, ignored_bars=None, logged_bars='all', min_time_interval=0, ignore_bars_under=0):
ProgressLogger.__init__(self, init_state)
if (bars is None):
bars = OrderedDict()
elif isins... |
def test(model):
model.eval()
from scipy import misc
img = misc.imread('lena_299.png')
inputs = torch.zeros(1, 299, 299, 3)
inputs[0] = torch.from_numpy(img)
inputs.transpose_(1, 3)
inputs.transpose_(2, 3)
outputs = model.forward(torch.autograd.Variable(inputs))
h5f = h5py.File('dump... |
class ConformerEncoderLayer(rf.Module):
def __init__(self, out_dim: Dim=Dim(512, name='conformer-enc-default-out-dim'), *, ff_dim: Dim=NotSpecified, ff_activation: Callable[([Tensor], Tensor)]=rf.swish, dropout: float=0.1, conv_kernel_size: int=32, conv_norm: Union[(rf.BatchNorm, type, Any)]=NotSpecified, conv_norm... |
class Network(nn.Module):
def __init__(self, cfg, mode='train', num_classes=1000):
super(Network, self).__init__()
pretrain = (True if ((mode == 'train') and (cfg.RESUME_MODEL == '') and (cfg.BACKBONE.PRETRAINED_MODEL != '')) else False)
self.num_classes = num_classes
self.cfg = cfg
... |
class BSDSDmat(SpectralMatrix):
def assemble(self, method):
(test, trial) = (self.testfunction, self.trialfunction)
assert isinstance(test[0], SD)
assert isinstance(trial[0], SD)
d0 = get_norm_sq(test[0], trial[0], method)
d = {0: (d0[:(- 2)] + d0[2:]), (- 2): (- d0[2:(- 2)])... |
def test_pisa_retinanet_head_loss():
s = 256
img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3)}]
cfg = mmcv.Config(dict(assigner=dict(type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=(- 1)), sampler=dict(type='Rand... |
def IsDerivedFunction(clean_lines, linenum):
opening_paren = clean_lines.elided[linenum].find('(')
if (opening_paren < 0):
return False
(line, _, closing_paren) = CloseExpression(clean_lines, linenum, opening_paren)
return ((closing_paren >= 0) and Search('\\boverride\\b', line[closing_paren:])) |
class ZoneoutWrapper(RNNCell):
def __init__(self, cell, zoneout_drop_prob, is_training=True):
self._cell = cell
self._zoneout_prob = zoneout_drop_prob
self._is_training = is_training
def state_size(self):
return self._cell.state_size
def output_size(self):
return self... |
def rand_contrast(x):
x_mean = x.mean(dim=[1, 2, 3], keepdim=True)
x = (((x - x_mean) * (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) + 0.5)) + x_mean)
return x |
def set_discrete_variable(var_names: List[str], discrete_variable_name: str):
discrete = {name: False for name in var_names}
discrete[discrete_variable_name] = True
return discrete |
def aps15_fpp(x, n):
if (not (0 <= x <= ((2 * 0.001) / (1 + n)))):
return (np.e - 1.859)
return ((((((np.exp(((((n + 1) * x) / 2) * 1000)) * (n + 1)) / 2) * 1000) * (n + 1)) / 2) * 1000) |
def get_norm_layer(norm_type='instance'):
if (norm_type == 'batch'):
norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)
elif (norm_type == 'instance'):
norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)
elif (norm_typ... |
class IBMCloudProvider(CloudProvider):
def __init__(self, key_prefix: str='skyplane', auth: Optional[IBMCloudAuthentication]=None):
super().__init__()
self.key_prefix = key_prefix
self.auth = (auth if auth else IBMCloudAuthentication())
self.regions_vpc = {}
self.provisioning... |
def update_packet_pbar(i, current_iteration, no_of_packets, total_iterations):
if (packet_pbar.postfix == ''):
packet_pbar.postfix = '0'
bar_iteration = (int(packet_pbar.postfix) - 1)
if (iterations_pbar.total == None):
fix_bar_layout(iterations_pbar, total_iterations=total_iterations)
i... |
def test_langid(basic_multilingual):
english_text = 'This is an English sentence.'
french_text = "C'est une phrase francaise."
docs = [english_text, french_text]
docs = [Document([], text=text) for text in docs]
basic_multilingual(docs)
predictions = [doc.lang for doc in docs]
assert (predic... |
def quaternion_matrix(quaternion):
q = numpy.array(quaternion, dtype=numpy.float64, copy=True)
n = numpy.dot(q, q)
if (n < _EPS):
return numpy.identity(4)
q *= math.sqrt((2.0 / n))
q = numpy.outer(q, q)
return numpy.array([[((1.0 - q[(2, 2)]) - q[(3, 3)]), (q[(1, 2)] - q[(3, 0)]), (q[(1,... |
def pdb_hook(type, value, tb):
if (hasattr(sys, 'ps1') or (not sys.stderr.isatty())):
sys.__excepthook__(type, value, tb)
else:
import traceback
try:
import ipdb as pdb
except:
import pdb
traceback.print_exception(type, value, tb)
pdb.post_... |
def resnet_v2_152(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, spatial_squeeze=True, reuse=None, scope='resnet_v2_152'):
blocks = [resnet_v2_block('block1', base_depth=64, num_units=3, stride=2), resnet_v2_block('block2', base_depth=128, num_units=8, stride=2), resnet_v2_block('... |
def train(model, loader):
model.train()
total_loss = 0
for data in train_loader:
data = data.to(device)
optimizer.zero_grad()
out = model(data.x, data.edge_index, data.batch)
loss = F.cross_entropy(out, data.y)
loss.backward()
optimizer.step()
total_lo... |
def main():
image_set_dir = 'training_range_BB8/'
test_targets = []
for (cls_idx, cls_name) in IDX2CLASS.items():
print(cls_idx, cls_name)
if (cls_name == 'camera'):
BB8_train_idx_file = osp.join(image_set_dir, 'cam.txt')
else:
BB8_train_idx_file = osp.join(im... |
def install_given_reqs(to_install, install_options, global_options=(), *args, **kwargs):
if to_install:
logger.info('Installing collected packages: %s', ', '.join([req.name for req in to_install]))
with indent_log():
for requirement in to_install:
if requirement.conflicts_with:
... |
def sketch_move(mocap_track, data=None, ax=None, figsize=(16, 8)):
if (ax is None):
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
if (data is None):
data = mocap_track.values
for frame in range(0, data.shape[0], 4):
for joint in mocap_track.skeleton.keys():
... |
def data_iterator_cityscapes(batch_size, data_dir, rng=None, train=True):
cityscapes = CityScapesDatasetPath(data_dir)
image_paths = cityscapes.get_image_paths(train=train)
label_paths = cityscapes.get_label_paths(train=train)
return data_iterator_segmentation(batch_size, image_paths, label_paths, rng, ... |
def multiprocess(func, data, num_workers=1, granularity='shards', log_every=1000, verbose=False):
start = time.time()
if (num_workers > 1):
if verbose:
print('parallel processing')
out = {}
with Pool(num_workers) as p:
count = 0
chunksize = max(1, (len... |
class BottleneckWithFixedBatchNorm(Bottleneck):
def __init__(self, in_channels, bottleneck_channels, out_channels, num_groups=1, stride_in_1x1=True, stride=1, dilation=1, dcn_config={}):
super(BottleneckWithFixedBatchNorm, self).__init__(in_channels=in_channels, bottleneck_channels=bottleneck_channels, out_... |
class FSMTTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, langs=None, src_voca... |
def mask_loss_evaluator():
matcher = Matcher(cfg.FAST_RCNN.FG_IOU_THRESHOLD, cfg.FAST_RCNN.BG_IOU_THRESHOLD, allow_low_quality_matches=False)
loss_evaluator = MaskRCNNLossComputation(matcher, cfg.MRCNN.RESOLUTION, cfg.MRCNN.MASKIOU_ON)
return loss_evaluator |
class GroupNorm(Module):
__constants__ = ['num_groups', 'num_channels', 'eps', 'affine']
num_groups: int
num_channels: int
eps: float
affine: bool
def __init__(self, num_groups: int, num_channels: int, eps: float=1e-05, affine: bool=True, device=None, dtype=None) -> None:
factory_kwargs ... |
def test_badscope():
with pytest.raises(ValueError):
(sdfg, state, t, me, mx) = create_sdfg()
nest_state_subgraph(sdfg, state, SubgraphView(state, [t, me]))
with pytest.raises(ValueError):
(sdfg, state, t, me, mx) = create_sdfg()
nest_state_subgraph(sdfg, state, SubgraphView(stat... |
class InfDataLoader():
def __init__(self, dataset, **kwargs):
self.dataloader = torch.utils.data.DataLoader(dataset, **kwargs)
def inf_dataloader():
while True:
for data in self.dataloader:
(image, label) = data
(yield (image, label... |
def process(filename, out_dir, n_frames, fps, skip_existing, ignore_exceptions, quiet):
youtube_id = filename.stem
instrument = filename.parent.name
if (skip_existing and ((out_dir / instrument) / youtube_id).is_dir()):
return
(out_dir / instrument).mkdir(exist_ok=True)
((out_dir / instrumen... |
def force_iterable(value: Any) -> (list | tuple):
if isinstance(value, (tuple, list)):
return value
return [value] |
def define_treatments(name, t, c):
treatment = dict(var_name=name, treatment_value=t, control_value=c)
return treatment |
def freesurface(model, eq):
fs_eq = []
for eq_i in eq:
for p in eq_i._flatten:
(lhs, rhs) = p.evaluate.args
zfs = model.grid.subdomains['fsdomain'].dimensions[(- 1)]
z = zfs.parent
funcs = retrieve_functions(rhs.evaluate)
mapper = {}
... |
class EventStorage():
def __init__(self, start_iter=0):
self._history = defaultdict(HistoryBuffer)
self._smoothing_hints = {}
self._latest_scalars = {}
self._iter = start_iter
self._current_prefix = ''
self._vis_data = []
self._histograms = []
def put_imag... |
def _propagate_device_option(net):
if (not net.HasField('device_option')):
return
for op in net.op:
if (not op.HasField('device_option')):
op.device_option.CopyFrom(net.device_option) |
def register_Ns3TracedValue__Unsigned_int_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::TracedValue< unsigned int > const &', 'o')])
cls.add_constructor([param('unsigned int const &', 'v')])
cls.add_method('Connect', 'void', [param('ns3::CallbackBase const &', 'cb')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.