code stringlengths 101 5.91M |
|---|
class HLSTMCell(nn.modules.rnn.RNNCellBase):
def __init__(self, input_size, hidden_size, bias=True):
super(HLSTMCell, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.Wi = nn.Linear((input_size + hidden_size), hidden_size, bias=bias)
self.Wf =... |
def grid_subsampling(points, features=None, labels=None, sampleDl=0.1, verbose=0):
if ((features is None) and (labels is None)):
return cpp_subsampling.compute(points, sampleDl=sampleDl, verbose=verbose)
elif (labels is None):
return cpp_subsampling.compute(points, features=features, sampleDl=sa... |
_to_string_io
def load_POSevents(fhandle: TextIO) -> annotations.Events:
times = []
labels = []
confidence = []
reader = csv.reader(fhandle, delimiter=',')
headers = next(reader)
class_ids = headers[3:]
for line in reader:
times.append([float(line[1]), float(line[2])])
classe... |
class ExponentialLR(_LRScheduler):
def __init__(self, optimizer, gamma, last_epoch=(- 1), verbose=False):
self.gamma = gamma
super(ExponentialLR, self).__init__(optimizer, last_epoch, verbose)
def get_lr(self):
if (not self._get_lr_called_within_step):
warnings.warn('To get t... |
class TextImageDataset(TextVideoDataset):
def __getitem__(self, item):
item = (item % len(self.metadata))
sample = self.metadata.iloc[item]
(video_fp, rel_fp) = self._get_video_path(sample)
caption = self._get_caption(sample)
video_loading = self.video_params.get('loading', '... |
def convert_child_by_dict(model, dict_id_b4_to_after):
if (not dict_id_b4_to_after):
return
for (child_name, child) in model.named_children():
if (id(child) in dict_id_b4_to_after):
setattr(model, child_name, dict_id_b4_to_after[id(child)])
else:
convert_child_by_... |
class _DecoderBlock(nn.Module):
def __init__(self, in_channels, out_channels, num_conv_layers):
super(_DecoderBlock, self).__init__()
middle_channels = int((in_channels / 2))
layers = [nn.ConvTranspose2d(in_channels, in_channels, kernel_size=2, stride=2), nn.Conv2d(in_channels, middle_channe... |
def _config_draft(config):
if config.draft:
config.num_steps = 2
config.eval_period = 1
config.log_period = 1
config.save_period = 1
config.eval_num_batches = 1 |
def test_nonzero_offset_fromarrow_NumpyArray_3():
content = ak.contents.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1]))
assert (to_list(ak._connect.pyarrow.handle_arrow(content.to_arrow()[2:5])) == pyarrow.Array.to_pylist(content.to_arrow()[2:5])) |
class QuestionAnsweringArgumentHandler(ArgumentHandler):
def normalize(self, item):
if isinstance(item, SquadExample):
return item
elif isinstance(item, dict):
for k in ['question', 'context']:
if (k not in item):
raise KeyError('You need t... |
def test_kmeans_semi_sup(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_lab = np.array([])
mask_cls = np.array([])
print('Collating features...')
for (batch_idx, (feats, label, _... |
class RoIPointPool3dFunction(Function):
def forward(ctx, points, point_features, boxes3d, num_sampled_points=512):
assert ((len(points.shape) == 3) and (points.shape[2] == 3))
(batch_size, boxes_num, feature_len) = (points.shape[0], boxes3d.shape[1], point_features.shape[2])
pooled_boxes3d =... |
class AlgebraicNumRef(ArithRef):
def approx(self, precision=10):
return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
def as_decimal(self, prec):
return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
def poly(self):
r... |
class Trainer(DefaultTrainer):
def resume_or_load(self, resume=True):
if (not isinstance(self.checkpointer, AdetCheckpointer)):
self.checkpointer = AdetCheckpointer(self.model, self.cfg.OUTPUT_DIR, optimizer=self.optimizer, scheduler=self.scheduler)
super().resume_or_load(resume=resume)
... |
def openai_moderation_API(data):
(scores, all_scores) = ([], [])
for sample in tqdm(data):
response = openai.Moderation.create(input=sample['output'])
pred = response['results'][0]
all_scores.append(pred['category_scores'])
scores.append((1 - np.max(list(pred['category_scores'].v... |
def get_multiple_outputs_model(input_shape):
inputs = Input(shape=input_shape[1:])
x = Conv2D(filters=2, kernel_size=3)(inputs)
x = BatchNormalization()(x)
out1 = ReLU(max_value=6.0)(x)
out2 = Conv2D(2, 4)(out1)
return keras.Model(inputs=inputs, outputs=[out1, out2]) |
def count_uses(dag, uses=None):
if (uses is None):
uses = collections.Counter()
def walk(v):
for a in v.args():
if (a not in uses):
walk(a)
uses[a] += 1
walk(dag)
return uses |
class LinearFeatureBaseline(Baseline):
def __init__(self, env_spec, reg_coeff=1e-05, name='LinearFeatureBaseline'):
super().__init__(env_spec)
self._coeffs = None
self._reg_coeff = reg_coeff
self.name = name
self.lower_bound = (- 10)
self.upper_bound = 10
def get_... |
def isASCII(word):
try:
word = word.decode('ascii')
return True
except UnicodeEncodeError:
return False
except UnicodeDecodeError:
return False |
def separate_process_wrapper_fn(func: Callable[([], None)], do_multi_processing: bool) -> Callable[([], None)]:
def multi_process_func(*args, **kwargs):
def wrapper_func(queue: Queue, *args):
try:
result = func(*args)
except Exception as e:
logger.erro... |
def get_jsd_type_scores(p_1, p_2, m, weight_1, weight_2, base, alpha):
score_1 = 0
score_2 = 0
if (alpha == 1):
if (p_1 > 0):
score_1 = (weight_1 * (log(m, base) - log(p_1, base)))
else:
score_1 = (weight_1 * log(m, base))
if (p_2 > 0):
score_2 = (... |
class Queue(multiprocessing.queues.Queue):
def __init__(self, *args, **kwargs):
super(Queue, self).__init__(*args, **kwargs)
self._reader = ConnectionWrapper(self._reader)
self._writer = ConnectionWrapper(self._writer)
self._send = self._writer.send
self._recv = self._reader.... |
.experimental
def test_raises_predict(log, item_features, model):
with pytest.raises(ValueError, match='Item features are missing for predict'):
model.fit(log, None, item_features)
_ = model.predict_pairs(log.select('user_idx', 'item_idx'), user_features=None, item_features=None) |
def random_labels(n_samples, n_classes):
return rng.randint(low=0, high=n_classes, size=n_samples) |
def test_EntanglementSwapping():
counter1 = counter2 = 0
for i in range(1000):
(tl, nodes, memories) = config_three_nodes_network(phi_plus, phi_plus, i)
(a1, a2, a3) = nodes
(memo1, memo2, memo3, memo4) = memories
es1 = EntanglementSwappingB(a1, ('a1.ESb%d' % i), memo1)
a... |
def calculate_homophily(g, labels, K=1, method='edge', multilabels=False, heterograph=False):
assert (method in ['edge', 'node'])
if multilabels:
assert (len(labels.shape) == 2)
elif ((labels.max() == 1) and (len(labels.shape) > 1)):
labels = labels.argmax(dim=1)
if heterograph:
... |
def db_input(model, blobs_out, batch_size, db, db_type):
dbreader_name = ('dbreader_' + db)
dbreader = model.param_init_net.CreateDB([], dbreader_name, db=db, db_type=db_type)
return model.net.TensorProtosDBInput(dbreader, blobs_out, batch_size=batch_size) |
def symbolic_override_packed_sequence_based(symbolic_fn):
def might_trace(args):
import torch
first_arg = args[0]
if (not isinstance(first_arg, torch.nn.utils.rnn.PackedSequence)):
raise ValueError('pad_packed_sequence expects sequence to be a PackedSequence, but got an object of... |
class StatTest(Enum):
PairedTTest = [PairedTTest, 'paired_ttest']
WilcoxonTest = [WilcoxonTest, 'wilcoxon_test'] |
def check_already_generated(md_dir, aishell1_dir):
already_generated_csv = os.listdir(md_dir)
already_generated_csv = [f.split('.')[0] for f in already_generated_csv]
original_aishell1_dirs = ['dev', 'test', 'train']
actual_aishell1_dirs = (set(next(os.walk(aishell1_dir))[1]) & set(original_aishell1_dir... |
def forward_vae_sample(vae: ConditionalVAE, x: TorchObservation, with_squash: bool=True) -> torch.Tensor:
batch_size = get_batch_size(x)
latent = torch.randn((batch_size, vae.encoder.latent_size), device=get_device(x))
return vae.decoder(x, latent.clamp((- 0.5), 0.5), with_squash=with_squash) |
_cache(maxsize=32)
def _setup_so3_rotation(b, alpha, beta, gamma, device_type, device_index):
Us = __setup_so3_rotation(b, alpha, beta, gamma)
Us = [torch.tensor(U, dtype=torch.float32, device=torch.device(device_type, device_index)) for U in Us]
return Us |
class ScoreCAM(ExplainerBase):
explanation_type = 'local'
alias = ['scorecam', 'score-cam']
def __init__(self, model, target_layer, preprocess_function: Callable, mode: str='classification', **kwargs):
super().__init__()
if ((not is_tf_available()) and (not is_torch_available())):
... |
class ContourPlot(GraphicPrimitive):
def __init__(self, xy_data_array, xrange, yrange, options):
self.xrange = xrange
self.yrange = yrange
self.xy_data_array = xy_data_array
self.xy_array_row = len(xy_data_array)
self.xy_array_col = len(xy_data_array[0])
GraphicPrimit... |
def get_metric(y_true_aspect, y_predict_aspect, y_true_sentiment, y_predict_sentiment, mask, train_op):
(f_a, f_o) = (0, 0)
(true_aspect, true_sentiment) = convert_to_list(y_true_aspect, y_true_sentiment, mask)
(predict_aspect, predict_sentiment) = convert_to_list(y_predict_aspect, y_predict_sentiment, mask... |
class HybridTrainPipe(Pipeline):
def __init__(self, batch_size, num_threads, device_id, data_dir, crop, dali_cpu=False, local_rank=0, world_size=1):
super(HybridTrainPipe, self).__init__(batch_size, num_threads, device_id, seed=(12 + device_id))
self.input = ops.FileReader(file_root=data_dir, shard_... |
class Zirilli(Benchmark):
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([(- 10.0)] * self.N), ([10.0] * self.N)))
self.custom_bounds = ([(- 2.0), 2.0], [(- 2.0), 2.0])
self.global_optimum = [[(- 1.0465), 0.0]]
self.fglob = (- ... |
def save_networks(path: str, net, name=None, *, backups: int=10, write_layers: bool=False, file_format=None):
os.makedirs(path, exist_ok=True)
if (name is None):
name = get_date_string()
data_path = os.path.join(path, name)
save_models(data_path, net, write_layers=write_layers, file_format=file_... |
def tr_te_dataset(data_tr, data_te, batch_size):
data_tr = data_tr.astype(np.float32)
data_tr_coo = data_tr.tocoo()
n_items = data_tr_coo.shape[1]
indices = np.mat([data_tr_coo.row, data_tr_coo.col]).transpose()
sparse_data_tr = tf.SparseTensor(indices, data_tr_coo.data, data_tr_coo.shape)
data_... |
.fast
.parametrize('max_seq_length1,length,max_seq_length,eos_token_id,chunk_size,num_iterations,gold_input_ids,gold_token_type_ids', [(MAX_SEQ_LENGTH, MAX_SEQ_LENGTH, MAX_SEQ_LENGTH, EOS, CHUNK_SIZE_1, 1, np.array([[0, 1, 2, 3]]), np.array([[0, (- 1), (- 2), (- 3)]])), (MAX_SEQ_LENGTH, MAX_SEQ_LENGTH, MAX_SEQ_LENGTH, ... |
def test_heap(n):
from random import randint
heap = MinMaxHeap(n)
l = []
for _ in range(n):
x = randint(0, (5 * n))
heap.insert(x)
l.append(x)
assert minmaxheapproperty(heap.a, len(heap))
assert (len(heap) == len(l))
print(heap.a)
while (len(heap) > 0):
... |
def precook(s, n=4, out=False):
words = s.split()
counts = defaultdict(int)
for k in xrange(1, (n + 1)):
for i in xrange(((len(words) - k) + 1)):
ngram = tuple(words[i:(i + k)])
counts[ngram] += 1
return (len(words), counts) |
def test_sugar_2():
resi = ['RC5_1_0', 'RG_69_0']
angles = ['nu1', 'nu4', 'nu3']
(sugar_b, rr) = bb.sugar_angles(fname, residues=resi, angles=angles)
stri = ('%20s ' % '#')
for pp in angles:
stri += (' %10s ' % pp)
stri += '\n'
for e in range(sugar_b.shape[1]):
stri += ('%20s... |
def is_tensor(x):
if isinstance(x, torch.Tensor):
return True
return isinstance(x, np.ndarray) |
class CoercionHMtoPD(HyperbolicModelCoercion):
def image_coordinates(self, x):
return ((x[0] / (1 + x[2])) + (I * (x[1] / (1 + x[2]))))
def image_isometry_matrix(self, x):
return (((matrix(2, [1, (- I), (- I), 1]) * SO21_to_SL2R(x)) * matrix(2, [1, I, I, 1])) / Integer(2)) |
def map_arg(a: Argument, fn: Callable[([Node], Argument)]) -> Argument:
if isinstance(a, (tuple, list)):
return type(a)((map_arg(elem, fn) for elem in a))
elif isinstance(a, dict):
return {k: map_arg(v, fn) for (k, v) in a.items()}
elif isinstance(a, slice):
return slice(map_arg(a.st... |
def dump_tsvs(dataset, fpath):
for name in dataset:
if (not os.path.exists(f'{fpath}/{name}')):
os.makedirs(f'{fpath}/{name}')
with open(f'{fpath}/{name}/{name}.tsv', 'w') as fp:
for (i, row_id) in enumerate(dataset[name]):
row = dataset[name][row_id]
... |
def generate_pose3_extra_factors(output_dir: T.Openable) -> None:
def between_factor_pose3_rotation(a: sf.Pose3, b: sf.Pose3, a_R_b: sf.Rot3, sqrt_info: sf.Matrix33, epsilon: sf.Scalar=0) -> sf.Matrix:
tangent_error = ops.LieGroupOps.local_coordinates(a_R_b, ops.LieGroupOps.between(a, b).R, epsilon=epsilon)... |
def export_ego_poses(nusc: NuScenes, out_dir: str):
locations = np.unique([log['location'] for log in nusc.log])
if (not os.path.isdir(out_dir)):
os.makedirs(out_dir)
for location in locations:
print('Rendering map {}...'.format(location))
nusc.render_egoposes_on_map(location)
... |
def replaces_method(func: Callable[(..., Tuple[str])], classname: str, method_name: str):
Replacements._method_rep[(classname, method_name)] = func
return func |
def test_additive_aav_packaging():
problem = flexs.landscapes.additive_aav_packaging.registry()['heart']
landscape = flexs.landscapes.AdditiveAAVPackaging(**problem['params'])
test_seqs = s_utils.generate_random_sequences(90, 100, s_utils.AAS)
landscape.get_fitness(test_seqs) |
class Algorithm(str, enum.Enum):
DYNAMOSA = 'DYNAMOSA'
MIO = 'MIO'
MOSA = 'MOSA'
RANDOM = 'RANDOM'
RANDOM_TEST_SUITE_SEARCH = 'RANDOM_TEST_SUITE_SEARCH'
RANDOM_TEST_CASE_SEARCH = 'RANDOM_TEST_CASE_SEARCH'
WHOLE_SUITE = 'WHOLE_SUITE' |
def draw_stickfigure3d(mocap_track, frame, data=None, joints=None, draw_names=False, ax=None, figsize=(8, 8)):
from mpl_toolkits.mplot3d import Axes3D
if (ax is None):
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111, projection='3d')
if (joints is None):
joints_to_draw = m... |
class ResNeXt(nn.Module):
def __init__(self, num_blocks, cardinality, bottleneck_width, num_classes=200):
super(ResNeXt, self).__init__()
self.cardinality = cardinality
self.bottleneck_width = bottleneck_width
self.in_planes = 16
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, b... |
def _parse_returns_section(self: NumpyDocstring, section: str) -> list[str]:
lines_raw = self._dedent(self._consume_to_next_section())
if (lines_raw[0] == ':'):
del lines_raw[0]
lines = self._format_block(':returns: ', list(_process_return(lines_raw)))
if (lines and lines[(- 1)]):
lines.... |
def finetune_m0(args):
print('Train m0 and finetune it with new data over time')
print(args)
device = (torch.device(('cuda:' + str(args.device))) if torch.cuda.is_available() else torch.device('cpu'))
dataset = DynRecDataset(name=args.dataset)
pinsage_hyperparam_list = get_pinsage_hyperparam_list(da... |
def executeShTest(test, litConfig, useExternalSh, extra_substitutions=[]):
if test.config.unsupported:
return (Test.UNSUPPORTED, 'Test is unsupported')
res = parseIntegratedTestScript(test, useExternalSh, extra_substitutions)
if isinstance(res, lit.Test.Result):
return res
if litConfig.n... |
class LowRatingFilter(_BaseFilter):
def __init__(self, value: float, rating_column: str='rating'):
self.value = value
self.rating_column = rating_column
def _filter_spark(self, interactions: SparkDataFrame) -> SparkDataFrame:
return interactions.filter((interactions[self.rating_column] >... |
class LogsigmoidLoss(BaseLogsigmoidLoss):
def __init__(self):
super(LogsigmoidLoss, self).__init__()
def __call__(self, score: th.Tensor, label):
return (- logsigmoid((label * score))) |
def get_corpus(products, keys=('name', 'small_description'), category_type='category'):
all_products = list(products.values())
asins_by_cat = defaultdict(set)
corpus_by_cat = defaultdict(list)
for p in all_products:
category = p[category_type]
asin = p['asin']
if (asin in asins_b... |
class SpeedtestHTTPConnection(HTTPConnection):
def __init__(self, *args, **kwargs):
source_address = kwargs.pop('source_address', None)
timeout = kwargs.pop('timeout', 10)
self._tunnel_host = None
HTTPConnection.__init__(self, *args, **kwargs)
self.source_address = source_add... |
def _should_continue(line, indent):
return (line.startswith(indent) or (len(line) <= 1) or (re.search('^\\s*\\)(\\s*->.*:|:)\\s*$', line) is not None)) |
def limit_lines(lines, N=32):
if (len(lines) > (2 * N)):
lines = ([b'... showing only last few lines ...'] + lines[(- N):])
return lines |
class SetPartitionsTk_k(SetPartitionsBk_k):
def _repr_(self):
return (SetPartitionsBk_k._repr_(self) + ' and that are planar')
def __contains__(self, x):
if (not SetPartitionsBk_k.__contains__(self, x)):
return False
if (not is_planar(x)):
return False
ret... |
class RandomImgAugment(object):
def __init__(self, no_flip, no_rotation, no_augment, size=None):
self.flip = (not no_flip)
self.augment = (not no_augment)
self.rotation = (not no_rotation)
self.size = size
def __call__(self, inputs):
img1 = inputs[0]
img2 = inputs... |
def gof(G, Aobs, changestats_func_list, theta, numSamples=1000, sampler_func=basicALAAMsampler, Ainitial=None, iterationInStep=1000, burnIn=10000):
n = len(changestats_func_list)
assert (len(theta) == n)
print('Gof numSamples =', numSamples, 'iterationInStep =', iterationInStep, 'burnIn = ', burnIn)
Zob... |
class DummyModelHandler(CommonModelHandler):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
def _get_normal_model_instance(self, *args, **kwargs):
if (self.normal_model_instance is None):
args = SimpleNamespace()
p = DumT5Partitioner(args)
args... |
def clip_eps(delta_tensor):
return tf.clip_by_value(delta_tensor, clip_value_min=(- EPS[0]), clip_value_max=EPS[0]) |
class KitchenLightSwitchV0(KitchenBase):
TASK_ELEMENTS = ['light switch']
def __init__(self, delta=0, **kwargs):
super(KitchenLightSwitchV0, self).__init__(**kwargs)
self.step_to_primitive_name = {0: 'close_gripper', 1: 'lift', 2: 'move_right', 3: 'move_forward', 4: 'move_left'}
if ((not... |
def compute_entropy(prob_states):
ent = 0
for prob in prob_states:
for p in prob:
p = np.array(p).flatten()
i = np.where((p > 0))[0]
t = np.sum(((- p[i]) * np.log2(p[i])))
ent += t
return ent |
class OvercookedEnv(object):
def __init__(self, mdp, start_state_fn=None, horizon=MAX_HORIZON, debug=False):
if isinstance(mdp, OvercookedGridworld):
self.mdp_generator_fn = (lambda : mdp)
elif (callable(mdp) and isinstance(mdp(), OvercookedGridworld)):
self.mdp_generator_fn ... |
class THTerm(Term):
def eval_real(self, shape, fargs, mode='eval', term_mode=None, diff_var=None, **kwargs):
if (diff_var is None):
if (mode == 'eval'):
out = 0.0
else:
out = nm.zeros(shape, dtype=nm.float64)
iter_kernel = fargs
... |
.operations('path_variable')
.usefixtures('filter_path_parameters')
def test_path_parameters_encoding(real_app_schema):
results = execute(real_app_schema, checks=(status_code_conformance,), hypothesis_settings=hypothesis.settings(derandomize=True, deadline=None))
assert (not results.has_errors)
assert (not ... |
class RefQualifierKind(BaseEnumeration):
_kinds = []
_name_map = None
def from_param(self):
return self.value
def __repr__(self):
return ('RefQualifierKind.%s' % (self.name,)) |
def prune_state_dict(state_dict, args):
if ((not args) or (args.arch == 'ptt_transformer')):
return state_dict
encoder_layers_to_keep = (args.encoder_layers_to_keep if ('encoder_layers_to_keep' in vars(args)) else None)
decoder_layers_to_keep = (args.decoder_layers_to_keep if ('decoder_layers_to_kee... |
(config_path='conf', config_name='rolling')
def main(cfg):
bg = cv2.imread('conf/bg_digit_240_320.jpg')
digits = tacto.Sensor(**cfg.tacto, background=bg)
log.info('Initializing world')
px.init()
p.resetDebugVisualizerCamera(**cfg.pybullet_camera)
digit_top = px.Body(**cfg.digits.top)
digit_b... |
def test():
backend = TypeTracerBackend.instance()
layout = ak.contents.ListOffsetArray(ak.index.Index64(backend.index_nplike.asarray([0, 1, 3, 7], dtype=np.dtype('int64'))), ak.contents.NumpyArray(backend.nplike.asarray([1, 2, 3, 4, 5, 6, 7])))
assert (layout.to_packed().length == 3) |
_numpy_output(non_zero=True, positive=True)
def test_modr(A: dace.int64[1], B: dace.int64[(5, 5)]):
return (A % B) |
def _jaccard(a, b):
a = sitk.GetArrayFromImage(a)
b = sitk.GetArrayFromImage(b)
return (np.sum(np.logical_and(a, b)) / np.sum(np.logical_or(a, b))) |
def save_tflite(model, onnx_path, dummy_input):
from tinynn.converter import TFLiteConverter
model = copy.deepcopy(model)
model.cpu()
if hasattr(model, 'module'):
model = model.module
model.eval()
converter = TFLiteConverter(model, dummy_input.cpu(), onnx_path)
converter.convert()
... |
class LinearNorm(torch.nn.Module):
def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
super().__init__()
self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
torch.nn.init.xavier_uniform_(self.linear_layer.weight, gain=torch.nn.init.calculate_gain(w_init_gain))
... |
def _SQS38():
return [[0, 1, 2, 14], [0, 1, 3, 34], [0, 1, 4, 31], [0, 1, 5, 27], [0, 1, 6, 17], [0, 1, 7, 12], [0, 1, 8, 36], [0, 1, 9, 10], [0, 1, 11, 18], [0, 1, 13, 37], [0, 1, 15, 35], [0, 1, 16, 22], [0, 1, 19, 33], [0, 1, 20, 25], [0, 1, 21, 23], [0, 1, 24, 32], [0, 1, 26, 28], [0, 1, 29, 30], [0, 2, 3, 10],... |
def gauss_spline(x, n):
x = asarray(x)
signsq = ((n + 1) / 12.0)
return ((1 / sqrt(((2 * pi) * signsq))) * exp((((- (x ** 2)) / 2) / signsq))) |
class TDErrorEvaluator(EvaluatorProtocol):
_episodes: Optional[Sequence[EpisodeBase]]
def __init__(self, episodes: Optional[Sequence[EpisodeBase]]=None):
self._episodes = episodes
def __call__(self, algo: QLearningAlgoProtocol, dataset: ReplayBuffer) -> float:
total_errors = []
episo... |
class Graph():
def __init__(self, labeling_mode='spatial'):
self.A = self.get_adjacency_matrix(labeling_mode)
self.num_node = num_node
self.self_link = self_link
self.inward = inward
self.outward = outward
self.neighbor = neighbor
def get_adjacency_matrix(self, la... |
def build_sem_seg_train_aug(cfg):
augs = [T.ResizeShortestEdge(cfg.INPUT.MIN_SIZE_TRAIN, cfg.INPUT.MAX_SIZE_TRAIN, cfg.INPUT.MIN_SIZE_TRAIN_SAMPLING)]
if cfg.INPUT.CROP.ENABLED:
augs.append(T.RandomCrop_CategoryAreaConstraint(cfg.INPUT.CROP.TYPE, cfg.INPUT.CROP.SIZE, cfg.INPUT.CROP.SINGLE_CATEGORY_MAX_A... |
class TestABC(object):
def test_abstract(self):
assert_(issubclass(np.number, numbers.Number))
assert_(issubclass(np.inexact, numbers.Complex))
assert_(issubclass(np.complexfloating, numbers.Complex))
assert_(issubclass(np.floating, numbers.Real))
assert_(issubclass(np.intege... |
def test_compute_hmean():
with pytest.raises(AssertionError):
utils.compute_hmean(0, 0, 0.0, 0)
with pytest.raises(AssertionError):
utils.compute_hmean(0, 0, 0, 0.0)
with pytest.raises(AssertionError):
utils.compute_hmean([1], 0, 0, 0)
with pytest.raises(AssertionError):
... |
_model
def ese_vovnet39b_evos(pretrained=False, **kwargs):
def norm_act_fn(num_features, **kwargs):
return create_norm_act('EvoNormSample', num_features, jit=False, **kwargs)
return _vovnet('ese_vovnet39b_evos', pretrained=pretrained, norm_layer=norm_act_fn, **kwargs) |
class MujocoReplayBuffer(EnvReplayBuffer):
def __init__(self, max_replay_buffer_size, env, env_info_sizes=None):
super().__init__(max_replay_buffer_size=max_replay_buffer_size, env=env, env_info_sizes=env_info_sizes)
self.body_xpos_shape = env.sim.data.body_xpos.shape
self._body_xpos = np.ze... |
def clean_line(text):
text = text.replace('[', '')
text = text.replace(']', '')
text = text.replace("'", '')
text = text.replace('\n', '')
text = text.strip()
return text |
class FPN(nn.Module):
def __init__(self, **kwargs):
super(FPN, self).__init__()
dim_in = kwargs.pop('dim_in', [256, 512, 1024, 2048])
spatial_scale = kwargs.pop('spatial_scale', [(1 / 4), (1 / 8), (1 / 16), (1 / 32)])
keep_backbone = kwargs.pop('keep_backbone', False)
fpn_dim... |
def convert_to_coco_gt(data, outpath, caption_key, sample_id_key, split, load_gt_from_file=False, img_ids=[]):
gt_data = {'annotations': [], 'images': []}
if load_gt_from_file:
print(f'Generating ground truth file for evaluation from {load_gt_from_file}....')
data = load_gt_file(load_gt_from_fil... |
class TestPredict(unittest.TestCase):
def test_predict(self) -> None:
test_audio_path = (RESOURCES_PATH / 'vocadito_10.wav')
(model_output, midi_data, note_events) = inference.predict(test_audio_path, ICASSP_2022_MODEL_PATH)
assert (set(model_output.keys()) == set(['note', 'onset', 'contour'... |
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = (out_features or in_features)
hidden_features = (hidden_features or in_features)
self.fc1 = nn.Linear(in_features, hidden_fea... |
class SawyerDoorUnlockEnvV2(SawyerXYZEnv):
def __init__(self):
hand_low = ((- 0.5), 0.4, (- 0.15))
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.1), 0.8, 0.15)
obj_high = (0.1, 0.85, 0.15)
goal_low = (0.0, 0.64, 0.21)
goal_high = (0.2, 0.7, 0.2111)
super().__init_... |
def prepare_dataset():
((train_images, train_labels), (test_images, test_labels)) = load_cifar10()
dirpath = os.path.join(FLAGS.data_dir, ('seed' + str(FLAGS.dataset_seed)))
if (not os.path.exists(dirpath)):
os.makedirs(dirpath)
rng = np.random.RandomState(FLAGS.dataset_seed)
rand_ix = rng.p... |
.parametrize('ctx, fname', ctxs)
.parametrize('reverse', [False, True])
def test_equal_values(ctx, fname, reverse):
with nn.context_scope(ctx), nn.auto_forward(True):
x = nn.Variable.from_numpy_array([2, 3, 3, 4, 2])
(y, i) = F.sort(x, reverse=reverse, with_index=True)
assert all((y.d == ([4... |
def generate_model_with_data_frame(data_frame, variables, variable_type, result_value_name, objective, direction, constraints):
direction = direction.lower()
if (direction == 'maximize'):
direction = pyomo_env.maximize
elif (direction == 'minimize'):
direction = pyomo_env.minimize
else:
... |
def add_deeplab_outputs(model, blob_in, dim):
blob_out = model.net.Sum(blob_in, ['mask_fc8'])
if (not model.train):
pass
if cfg.WSL.MASK_SOFTMAX:
model.Transpose('mask_fc8', 'mask_fc8_t', axes=(0, 2, 3, 1))
model.Softmax('mask_fc8_t', 'mask_fc8_probs_t', axis=3)
model.Transpo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.