code
stringlengths
101
5.91M
def register_all_mapillary_vistas(root): root = os.path.join(root, 'mapillary_vistas') meta = _get_mapillary_vistas_meta() for (name, dirname) in [('train', 'training'), ('val', 'validation')]: image_dir = os.path.join(root, dirname, 'images') gt_dir = os.path.join(root, dirname, 'labels') ...
class MultiRPN(RPN): def __init__(self, anchor_num, in_channels, weighted=False): super(MultiRPN, self).__init__() self.weighted = weighted for i in range(len(in_channels)): self.add_module(('rpn' + str((i + 2))), DepthwiseRPN(anchor_num, in_channels[i], in_channels[i])) ...
_method class RubiksCube(SageObject): def __init__(self, state=None, history=[], colors=[lpurple, yellow, red, green, orange, blue]): self.colors = colors self._history = history self._group = CubeGroup() if (state is None): self._state = self._group.identity() el...
def ConsonniTodeschiniI_calc(TP, FP, FN, TN): try: n = (((TP + FP) + FN) + TN) return (math.log(((1 + TP) + TN)) / math.log((1 + n))) except Exception: return 'None'
def load_real_images(path, N=100): images = [] for i in range(N): f = os.path.join(path, '{:04d}_gt.png'.format(i)) if (not os.path.exists(f)): return images.append(trn(Image.open(f))) return torch.stack(images)
_properties class Pipeline(Pass): CATEGORY: str = 'Helper' passes = properties.ListProperty(element_type=Pass, default=[], category='(Debug)', desc='List of passes that this pipeline contains') def __init__(self, passes: List[Pass]): self.passes = [] self._pass_names = set((type(p).__name__ ...
class Command(Node): class PIPE(object): pass class STDOUT(object): pass def __init__(self, name): super(Command, self).__init__() self.name = name self.argv = [name] self.stdin = None self.stdout = None self.stderr = None self.env_vars...
class LegalDataset(Dataset): def __init__(self, text): self.encodings = text def __len__(self): return len(self.encodings) def __getitem__(self, index): item = {'input_ids': torch.tensor(self.encodings.iloc[index])} return item
class Classification_data(Dataset): def __init__(self, data, label=None): super(Classification_data, self).__init__() self.data = data self.label = label def __getitem__(self, index): if (self.label is None): return self.data[index] return (self.data[index], s...
def _return_counts(input, sorted=True, return_inverse=False, return_counts=False, dim=None): if (not torch.jit.is_scripting()): if ((type(input) is not Tensor) and has_torch_function((input,))): return _unique_impl(input, sorted, return_inverse, return_counts, dim) (output, _, counts) = _uni...
def _expand_dollars(m): match = m.group(1) parts = match.split('.') if (len(parts) > 2): return (match + ' dollars') dollars = (int(parts[0]) if parts[0] else 0) cents = (int(parts[1]) if ((len(parts) > 1) and parts[1]) else 0) if (dollars and cents): dollar_unit = ('dollar' if (...
def test_vectorizer(): train_data = iter(ALL_FOOD_DOCS[:(- 1)]) test_data = [ALL_FOOD_DOCS[(- 1)]] n_train = (len(ALL_FOOD_DOCS) - 1) v1 = CountVectorizer(max_df=0.5) counts_train = v1.fit_transform(train_data) if hasattr(counts_train, 'tocsr'): counts_train = counts_train.tocsr() as...
class CrossEvalQueueConf(BaseQueueConf): _target_: str = 'hydra_plugins.hydra_drill_launcher.drill_launcher.CrossEvalLauncher'
class HistologyShardDescriptor(ShardDescriptor): URL = ' FILENAME = 'Kather_texture_2016_image_tiles_5000.zip' ZIP_SHA384 = '7d86abe1d04e68b77c055820c2a4c582a1d25d2983e38ab724eac75affce8b7cb2cbf5ba68848dcfd9d84005d87d6790' DEFAULT_PATH = ((Path.home() / '.openfl') / 'data') def __init__(self, data_f...
_class class EDMLoss(): def __init__(self, P_mean=(- 1.2), P_std=1.2, sigma_data=0.5): self.P_mean = P_mean self.P_std = P_std self.sigma_data = sigma_data def __call__(self, net, images, labels=None, augment_pipe=None): rnd_normal = torch.randn([images.shape[0], 1, 1, 1], device...
class SquadReader(BaseReader): def __init__(self, fine_grained=False): self.tokenizer = SpacyTokenizer(fine_grained) def read(self, file_path): logging.info('Reading file at %s', file_path) logging.info('Processing the dataset.') instances = self._read(file_path) instance...
class BarChart(GraphicPrimitive): def __init__(self, ind, datalist, options): self.datalist = datalist self.ind = ind GraphicPrimitive.__init__(self, options) def get_minmax_data(self): return minmax_data([0, len(self.datalist)], self.datalist, dict=True) def _allowed_options...
def test_enc_dec_model_seq_at_a_time(test_dl, model, scaler, output_sequence_length): x_input = [] truth = [] predicted = [] with torch.no_grad(): model.eval() step = 0 for (x, y, mask) in test_dl: x = x.to('cuda') y = y.unsqueeze((- 1)).to('cuda') ...
class GeneratorHyperParameters(): def __init__(self): self.leaky_relu_coeff = 0.05 self.with_batchnorm = True self.batchnorm_decay = 0.98 self.input_noise_size = 300 self.input_noise_bound = 1 self.e_layer_sizes = [300, 300] self.code1_size = 15 self.c...
def url_unescape(data): return re.sub('%([0-9a-fA-F]{2})', (lambda m: unichr(int(m.group(1), 16))), data)
def test_offset_not_none(): seed = np.array([0, 3, 6, 2, 1, 1, 1, 4, 2, 0]) mask = np.array([0, 8, 6, 8, 8, 8, 8, 4, 4, 0]) expected = np.array([0, 3, 6, 6, 6, 6, 6, 4, 4, 0]) assert_array_almost_equal(reconstruction(seed, mask, method='dilation', footprint=np.ones(3), offset=np.array([0])), expected)
def save_module_to_file(module: ast.Module, target: Path, format_with_black: bool=True) -> None: target.parent.mkdir(parents=True, exist_ok=True) with target.open(mode='w', encoding='UTF-8') as file: file.write(_PYNGUIN_FILE_HEADER) output = ast.unparse(ast.fix_missing_locations(module)) ...
def evaluate_conll(conll_scorer, gold_path, predictions, subtoken_maps, prediction_path, all_metrics=False, official_stdout=False): with open(prediction_path, 'w') as prediction_file: with open(gold_path, 'r') as gold_file: output_conll(gold_file, prediction_file, predictions, subtoken_maps) ...
def _is_punctuation(char): cp = ord(char) if (((cp >= 33) and (cp <= 47)) or ((cp >= 58) and (cp <= 64)) or ((cp >= 91) and (cp <= 96)) or ((cp >= 123) and (cp <= 126))): return True cat = unicodedata.category(char) if cat.startswith('P'): return True return False
class TransformerBlocks(nn.Module): def __init__(self, d_model=768, nlayers=3): super(TransformerBlocks, self).__init__() self.nlayers = nlayers block = TransformerBlock(d_model=d_model) self.h = _get_clones(block, nlayers) def forward(self, inp): for i in range(self.nlay...
class InferenceHost(): def __init__(self, object_directory_address, scale=1): self.store = hoplite.HopliteClient(object_directory_address) self.object_directory_address = object_directory_address self.images = torch.rand(input_shape) self.models = [] for _ in range(scale): ...
def ButterflyGraph(): edge_dict = {0: [3, 4], 1: [2, 4], 2: [4], 3: [4]} pos_dict = {0: [(- 1), 1], 1: [1, 1], 2: [1, (- 1)], 3: [(- 1), (- 1)], 4: [0, 0]} return Graph(edge_dict, pos=pos_dict, name='Butterfly graph')
class LayoutLMv3Model(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class QuantizedGRU(QuantizedRNNBase): __overloads__ = {'forward': ['forward_packed', 'forward_tensor']} .script_method def forward_impl(self, input, hx, batch_sizes, max_batch_size, sorted_indices): if (hx is None): num_directions = (2 if self.bidirectional else 1) hx = torch...
class MeshRelationAccessProxy(): def __init__(self, mesh: MeshInstance, from_index: impl.Expr, to_element_type: MeshElementType): self.mesh = mesh self.from_index = from_index self.to_element_type = to_element_type def size(self): return impl.Expr(self.mesh.get_relation_size(self...
def _scope_path(sdict: ScopeDictType, scope: NodeType) -> List[NodeType]: result = [] curnode = scope while (curnode is not None): curnode = sdict[scope] result.append(curnode) return result
class InstanceNorm2d(torch.nn.InstanceNorm2d): def __init__(self, num_features, weight, bias, scale, zero_point, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False): super(InstanceNorm2d, self).__init__(num_features, eps, momentum, affine, track_running_stats) self.weight = weight ...
class SparqlParse(): def __init__(self): select_stmt = None prefix_stmts = None where_stmts = None query_stmts = None
def _gross_pitch_error_frames(true_t, true_f, est_t, est_f, eps=1e-08): voiced_frames = _true_voiced_frames(true_t, true_f, est_t, est_f) true_f_p_eps = [(x + eps) for x in true_f] pitch_error_frames = (np.abs(((est_f / true_f_p_eps) - 1)) > 0.2) return (voiced_frames & pitch_error_frames)
def compute_bits_per_dim(x, model): zero = torch.zeros(x.shape[0], 1).to(x) (z, delta_logp) = model(x, zero) logpz = standard_normal_logprob(z).view(z.shape[0], (- 1)).sum(1, keepdim=True) logpx = (logpz - delta_logp) logpx_per_dim = (torch.sum(logpx) / x.nelement()) bits_per_dim = ((- (logpx_pe...
def test_luminosity_density_nu(spectrum): expected = (spectrum.luminosity / np.diff(spectrum._frequency)) test_helper.assert_quantity_allclose(spectrum.luminosity_density_nu, expected)
class EpicFHIRManageAppointments(VirtualFunctionTool): name = 'EpicFHIRManageAppointments' summary = 'List, access, create, update, and delete patient appointments.' parameters: List[ArgParameter] = [{'name': 'patient_id', 'type': 'string', 'description': 'The unique identifier of the patient. The identifie...
class vJoy(object): def __init__(self, reference=1): self.handle = None self.dll = ctypes.CDLL(CONST_DLL_VJOY) self.reference = reference self.acquired = False def open(self): if self.dll.AcquireVJD(self.reference): self.acquired = True return True...
.parametrize('a, feat_idxs, expected', [(B, [0], []), (B, [0, 1], [[0, 1, 0, 1, 1, 0]]), (B, [0, 1, 2, 3, 4], [[0, 1, 0, 1, 1, 0]]), (B, [0, 1, 2, 3, 4, 5], [[0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 1]])]) def test_expand_collection_unset(a, feat_idxs, expected): children = expand_collection_unset(a, feat_idxs) asse...
def validate(model, data_loader): print('validating ... ', flush=True, end='') val_loss_meter = pyutils.AverageMeter('loss1', 'loss2') model.eval() with torch.no_grad(): for pack in data_loader: img = pack['img'] label = pack['label'].cuda(non_blocking=True) a...
def bw_dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None): assert (not time_major) flat_inputs = flatten(inputs, 2) flat_len = (None if (sequence_length is None) else tf.cast(flatten(sequence_length, 0), ...
def add_rulebased_arguments(parser): parser.add_argument('--templates', help='Path to templates (.pkl)') parser.add_argument('--policy', help='Path to manager model (.pkl)')
class ActivationsTestModel(torch.nn.Module): def __init__(self): super().__init__() self.qconfig = torch.quantization.get_default_qconfig('fbgemm') self.quant = torch.quantization.QuantStub() self.hardswish = torch.nn.Hardswish().to(dtype=torch.float) self.elu = torch.nn.ELU(...
class DirichletCharacter(MultiplicativeGroupElement): def __init__(self, parent, x, check=True): MultiplicativeGroupElement.__init__(self, parent) if check: orders = parent.integers_mod().unit_group().gens_orders() if (len(x) != len(orders)): raise ValueError(...
class Function_log_integral_offset(BuiltinFunction): def __init__(self): BuiltinFunction.__init__(self, 'log_integral_offset', nargs=1, latex_name='\\operatorname{log\\_integral\\_offset}', conversions=dict(sympy='Li')) def _eval_(self, z): if (z == 2): return SR(0) return (l...
def test_random_public_method(executor): config.configuration.algorithm = config.Algorithm.RANDOM algorithm = gaf.TestSuiteGenerationAlgorithmFactory(executor, MagicMock(ModuleTestCluster)).get_search_algorithm() out_0 = MagicMock(GenericCallableAccessibleObject) out_1 = MagicMock(GenericAccessibleObjec...
.parametrize('backend', ['numpy', 'tensorflow', 'pytorch', 'jax']) def test_cls_backend_option(tmp_path, script_runner, backend): temp = tmp_path.joinpath('parsed_output.json') command = f'pyhf xml2json validation/xmlimport_input/config/example.xml --basedir validation/xmlimport_input/ --output-file {temp}' ...
def test_allowable_amino_acid_locations_do_not_contain_amino_acids_we_cant_create(esm_sampler_fixture): actual_allowed = map_aa_idx_to_tok_set(esm_sampler_fixture) non_single_standard = set('XBUXZO.-') assert actual_allowed.isdisjoint(non_single_standard)
def run_local(local_rank, num_proc, func, init_method, shard_id, num_shards, backend, cfg): world_size = (num_proc * num_shards) rank = ((shard_id * num_proc) + local_rank) try: torch.distributed.init_process_group(backend=backend, init_method=init_method, world_size=world_size, rank=rank) excep...
class BasicStage(nn.Module): def __init__(self, in_channels, out_channels, ratio, kernel_size, stride, groups, i_stage, m_blocks, use_bn=True, use_do=True, verbose=False): super(BasicStage, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.ratio = ...
def is_para_break(index, text): if (text[index] == '\n'): para_break = PARAGRAPH_BREAK.match(text, index) if para_break: break_len = len(para_break.group(0)) return (True, break_len) return (False, 0)
class Completions(): def __init__(self, list_or_dict, signature=None): self.signature = signature if isinstance(list_or_dict, list): kwargs = {} for arg in list_or_dict: for (k, v) in arg.items(): kwargs.setdefault(k, []).append(v) ...
def register_types(module): root_module = module.get_root() module.add_enum('MpduType', ['NORMAL_MPDU', 'MPDU_IN_AGGREGATE', 'LAST_MPDU_IN_AGGREGATE'], import_from_module='ns.wifi') module.add_enum('ChannelAccess', ['ContinuousAccess', 'AlternatingAccess', 'ExtendedAccess', 'DefaultCchAccess', 'NoAccess']) ...
class IndexedMonoidElement(MonoidElement): def __init__(self, F, x): MonoidElement.__init__(self, F) self._monomial = x _method def _sorted_items(self): def _repr_(self): if (not self._monomial): return '1' monomial = self._sorted_items() P = self.pare...
def get_monitors(): count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetMonitors(count) monitors = [result[i] for i in range(count_value.value)] return monitors
def main(args): (jobs, arrival_times) = utils.parse_trace(args.trace_file) policy = utils.get_policy(args.policy, solver=args.solver, seed=args.seed) sched = scheduler.Scheduler(policy, throughputs_file=args.throughputs_file, simulate=True, seed=args.seed, time_per_iteration=args.time_per_iteration) num...
def sp2torch(sparse_mx): sparse_mx = sparse_mx.tocoo().astype(np.float32) indices = torch.from_numpy(np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64)) values = torch.from_numpy(sparse_mx.data) shape = torch.Size(sparse_mx.shape) return torch.sparse.FloatTensor(indices, values, shape)
def run_algo(**kwargs): config = {} config['kwargs'] = kwargs config['kwargs']['seed'] = random.randint(0, 1000000) (_, _, algo_config) = algo_select(kwargs) load_data_from_neorl(algo_config['task'], algo_config['task_data_type'], algo_config['task_train_num']) grid_tune = algo_config['grid_tune...
class ALSModelJavaMLReadable(MLReadable): def read(cls): return ALSModelJavaMLReader(cls)
def sr_create_model(large_size, small_size, num_channels, num_res_blocks, learn_sigma, class_cond, use_checkpoint, attention_resolutions, num_heads, num_head_channels, num_heads_upsample, use_scale_shift_norm, dropout, resblock_updown, use_fp16): _ = small_size if (large_size == 512): channel_mult = (1,...
def write_to_hdf(file_list, transcription_list, charlist, n_labels, out_file_name, dataset_prefix, pad_y=15, pad_x=15, compress=True): with h5py.File(out_file_name, 'w') as f: f.attrs['inputPattSize'] = 1 f.attrs['numDims'] = 1 f.attrs['numSeqs'] = len(file_list) classes = charlist ...
def _k_radius_of_gyration_individual(traj, k=2): traj['visits'] = traj.groupby([constants.LATITUDE, constants.LONGITUDE]).transform('count')[constants.DATETIME] top_k_locations = traj.drop_duplicates(subset=[constants.LATITUDE, constants.LONGITUDE]).sort_values(by=['visits', constants.DATETIME], ascending=[Fals...
def symbolic_fg(x, grad, eps=0.3, clipping=True): reduc_ind = list(xrange(1, len(x.get_shape()))) normed_grad = (grad / tf.sqrt(tf.reduce_sum(tf.square(grad), reduction_indices=reduc_ind, keep_dims=True))) scaled_grad = (eps * normed_grad) adv_x = K.stop_gradient((x + scaled_grad)) if clipping: ...
def step(mouse_data): advect(velocities_pair.cur, velocities_pair.cur, velocities_pair.nxt) advect(velocities_pair.cur, dyes_pair.cur, dyes_pair.nxt) velocities_pair.swap() dyes_pair.swap() apply_impulse(velocities_pair.cur, dyes_pair.cur, mouse_data) divergence(velocities_pair.cur) if curl_...
def wait_for_tag(wtag, num=1): ndone = num start = MPI.Wtime() while (ndone > 0): mpi_comm.recv(source=MPI.ANY_SOURCE, tag=wtag, status=mpi_status) tag = mpi_status.Get_tag() source = mpi_status.Get_source() logger.debug(('received %s from %d (%.03fs)' % (tags.name[tag], sour...
class AdditiveAttention(nn.Module): def __init__(self, d_model: int) -> None: super(AdditiveAttention, self).__init__() self.query_proj = Linear(d_model, d_model, bias=False) self.key_proj = Linear(d_model, d_model, bias=False) self.bias = nn.Parameter(torch.rand(d_model).uniform_((-...
class AutoModelForCausalLM(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def get_model(point_cloud, is_training, num_class, bn_decay=None, gripper_feat=None, env_feat=None): batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value end_points = {} l0_xyz = point_cloud l0_points = None end_points['l0_xyz'] = l0_xyz (l1_xyz, l1_poin...
class ECAPA_TDNN(torch.nn.Module): def __init__(self, input_size, device='cpu', lin_neurons=192, activation=torch.nn.ReLU, channels=[512, 512, 512, 512, 1536], kernel_sizes=[5, 3, 3, 3, 1], dilations=[1, 2, 3, 4, 1], attention_channels=128, res2net_scale=8, se_channels=128, global_context=True, groups=[1, 1, 1, 1, ...
def main(): last_time = time.time() for i in list(range(4))[::(- 1)]: print((i + 1)) time.sleep(1) paused = False while True: if (not paused): screen = grab_screen(region=(0, 40, 960, 560)) print('loop took {} seconds'.format((time.time() - last_time))) ...
def construct_simple_trajec(traject_dict, **kwargs): return construct_trajec(traject_dict, include_agent_log=False, include_simulator_log=False, **kwargs)
class CaptureStd(): def __init__(self, out=True, err=True, replay=True): self.replay = replay if out: self.out_buf = StringIO() self.out = 'error: CaptureStd context is unfinished yet, called too early' else: self.out_buf = None self.out = 'not...
.parametrize('alpha', [np.linspace(0.05, 0.07), [0.05, 0.07, 0.9], (0.05, 0.07, 0.9), np.array([0.05, 0.07, 0.9])]) def test_invalid_calculation_of_quantile(alpha: Any) -> None: n = 10 with pytest.raises(ValueError, match='.*Number of samples of the score is too low.*'): check_alpha_and_n_samples(alpha,...
class TestEnvironmentReset(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.dm = NumbaDataManager(num_agents=5, num_envs=2, episode_length=2) self.fm = NumbaFunctionManager(num_agents=int(self.dm.meta_info('n_agents')), num_envs=int(self.dm.meta...
def extract_imdb_wiki_arcface(dataset: str='imdb', docker_port: int=10002, cuda: bool=False, resize: int=640): if cuda: image_name = 'tae898/face-detection-recognition-cuda' gpus = 'all' else: image_name = 'tae898/face-detection-recognition' gpus = None container = docker.run...
def draw_interactive(G, c, x, hover_text=None, node_size=10.0, pos=None, cmap=None): (node_colors, node_edge_colors) = set_node_colors(G, c, x, cmap) if (pos is None): pos = nx.spring_layout(G) nodelist = [d for d in G.nodes()] group_ids = [(c[d] if (c[d] is not None) else 'residual') for d in n...
def test_imagecollection_input(): pics = [fetch('data/coffee.png'), fetch('data/chessboard_GRAY.png'), fetch('data/rocket.jpg')] pattern = [os.path.join(data_dir, pic) for pic in pics] images = ImageCollection(pattern) assert (len(images) == 3)
def Chicken(A=0, a=0, B=1, b=(- 1), C=(- 1), c=1, D=(- 10), d=(- 10)): if (not ((B > A > C > D) and (c > a > b > d))): raise TypeError('the input values for a game of chicken must be of the form B > A > C > D and c > a > b > d') g = AntiCoordinationGame(A=A, a=a, B=B, b=b, C=C, c=c, D=D, d=d) g.rena...
class CiscoUmbrellaUpdatePolicy(VirtualFunctionTool): name = 'CiscoUmbrellaUpdatePolicy' summary = 'Update an existing security policy.' parameters: List[ArgParameter] = [{'name': 'policy_id', 'type': 'string', 'description': 'The unique identifier of the policy to be updated.', 'required': True}, {'name': ...
class SimpleLSTMModel(Model): def __init__(self, output_dim, hidden_dim, name='SimpleLSTMModel', *args, **kwargs): super().__init__(name) self.output_dim = output_dim self.hidden_dim = hidden_dim def network_input_spec(self): return ['full_input', 'step_input', 'step_hidden_input...
def max_pool(input_tensor, last_dim, sequence_length=None): with tf.name_scope('max_pool'): mid_dim = tf.shape(input_tensor)[1] input_tensor = handle_pad_max_pooling(input_tensor, last_dim) input_tensor = tf.reshape(input_tensor, [(- 1), mid_dim, last_dim]) input_tensor_max = tf.redu...
def register_Ns3LteRrcSapMeasIdToAddMod_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::LteRrcSap::MeasIdToAddMod const &', 'arg0')]) cls.add_instance_attribute('measId', 'uint8_t', is_const=False) cls.add_instance_attribute('measObjectId', 'uint8_t', is_const=False) ...
def _load_pretrained_model(model_name_or_path, *args, **kwargs): if PathManager.exists(model_name_or_path): download_path = model_name_or_path model_name = model_name_or_path else: download_path = download_pretrained_model(model_name_or_path, *args, **kwargs) model_name = model_n...
class TrainOptions(BaseOptions): def initialize(self, parser): parser = BaseOptions.initialize(self, parser) parser.add_argument('--display_freq', type=int, default=400, help='frequency of showing training results on screen') parser.add_argument('--display_ncols', type=int, default=4, help='...
def convert(src, dst, depth): if (depth not in arch_settings): raise ValueError('Only support ResNet-50 and ResNet-101 currently') block_nums = arch_settings[depth] caffe_model = mmcv.load(src, encoding='latin1') blobs = (caffe_model['blobs'] if ('blobs' in caffe_model) else caffe_model) sta...
class VariableSet(object): def __init__(self, d): self._raw_data = dict([(k, v) for (k, v) in d.items()]) self._re = {} self._re_sub = {} self._init_parse() def _init_parse(self): for (k, v) in self._raw_data.items(): self._init_parse_var(k, v) def _init_p...
class TStdNotify(TNotify): 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): _snap.TStdNotify_swiginit(self, _snap.new_TStdNotify()) def New(): return _snap.TStdNotify_New() New = stat...
def cross_entropy(pred, label, weight=None, class_weight=None, reduction='mean', avg_factor=None, ignore_index=(- 100), avg_non_ignore=False): loss = F.cross_entropy(pred, label, weight=class_weight, reduction='none', ignore_index=ignore_index) if ((avg_factor is None) and avg_non_ignore and (reduction == 'mean...
def test_unflatten_dict_raises_error_column_index(): flat = {'foo__1__0': 'some value'} err_msg = 'There was an error unflattening the extension.' with pytest.raises(ValueError, match=err_msg): unflatten_dict(flat)
_HEADS.register('parsingiou_head') class ParsingIoUHead(nn.Module): def __init__(self, cfg, dim_in, spatial_in): super(ParsingIoUHead, self).__init__() self.dim_in = dim_in[(- 1)] self.spatial_in = spatial_in[(- 1)] num_convs = cfg.PARSING.PARSINGIOU.NUM_CONVS conv_dim = cfg....
def test_log_operation_with_checksum(agent: Agent): file_ops.log_operation('log_test', 'path/to/test', agent=agent, checksum='ABCDEF') with open(agent.config.file_logger_path, 'r', encoding='utf-8') as f: content = f.read() assert (f'''log_test: path/to/test #ABCDEF ''' in content)
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [314]) def test_assign_recomputation(seed, ctx, func_name): rng = np.random.RandomState(seed) dst = nn.Variable((2, 3, 4)) src = nn.Variable((2, 3, 4)) recomputation_test(rng=rng, func=F.assign, vinputs=[dst, src], func_args=[], func_kwargs={}, c...
def test_sum_single(): with goos.OptimizationPlan() as plan: x = goos.Variable(2.0) res = goos.Sum([x]) assert (res.get() == 2) assert (res.get_grad([x]) == [1])
def label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=None, reduce=True): if (target.dim() == (lprobs.dim() - 1)): target = target.unsqueeze((- 1)) nll_loss = (- lprobs.gather(dim=(- 1), index=target)) smooth_loss = (- lprobs.sum(dim=(- 1), keepdim=True)) if (ignore_index is not None...
def transform(column_names, data): data[column_names] = (data[column_names] ** 2) return data
def get_normals_field(vertices): if (vertices not in normals_field_cache): N = vertices.shape[0] normals = Vector.field(3, f32, shape=(N,)) normal_weights = field(f32, shape=(N,)) normals_field_cache[vertices] = (normals, normal_weights) return (normals, normal_weights) r...
class UPChannelBAN(BAN): def __init__(self, feature_in=256, cls_out_channels=2): super(UPChannelBAN, self).__init__() cls_output = cls_out_channels loc_output = 4 self.template_cls_conv = nn.Conv2d(feature_in, (feature_in * cls_output), kernel_size=3) self.template_loc_conv =...
class TestDiscreteCNNQFunction(TfGraphTestCase): def setup_method(self): super().setup_method() self.env = GarageEnv(DummyDiscretePixelEnv()) self.obs = self.env.reset() .parametrize('filters, strides', [(((5, (3, 3)),), (1,)), (((5, (3, 3)),), (2,)), (((5, (3, 3)), (5, (3, 3))), (1, 1))...
class PredictionList(): def __init__(self, predictions: List[Prediction]): self.id_to_prediction = {p.id: p for p in predictions} assert (len(predictions) == len(self.id_to_prediction)) def __contains__(self, item: str): return (item in self.id_to_prediction) def __getitem__(self, it...
.parametrize('module', MODULES) def test_networkpass_set_variable(module): (_, inputs) = module verbose = 1 callback = nnp_graph.NnpNetworkPass(verbose) ref_callback = legacy_nnp_graph.NnpNetworkPass(verbose) for (inp_name, inp_shape) in inputs: inp_shape = (1, *inp_shape[1:]) callba...