code
stringlengths
101
5.91M
def calculate_roc_values(thresholds, distances, labels, num_folds=10): num_pairs = min(len(labels), len(distances)) num_thresholds = len(thresholds) k_fold = KFold(n_splits=num_folds, shuffle=False) true_positive_rates = np.zeros((num_folds, num_thresholds)) false_positive_rates = np.zeros((num_fold...
class TextClassProcessor(DataProcessor): def get_train_examples(self, raw_data_dir): examples = self._create_examples(self._read_tsv(os.path.join(raw_data_dir, 'train.csv'), quotechar='"', delimiter=','), 'train') assert (len(examples) == self.get_train_size()) return examples def get_de...
class ReverseSDE(object): def __init__(self, score_model): self.sde = score_model.sde self.score_model = score_model def drift(self, x, t, **kwargs): drift = self.sde.drift(x, t) diffusion = self.sde.diffusion(t) score = self.score_model.score(x, t, **kwargs) retu...
(help='Initialize PASCAL Context dataset.') ('download_dir', type=str) def main(download_dir): dataset_dir = (Path(download_dir) / 'pcontext') download_pcontext(dataset_dir, overwrite=False) devkit_path = (dataset_dir / 'VOCdevkit') out_dir = ((devkit_path / 'VOC2010') / 'SegmentationClassContext') ...
def process_line(args, line): try: (text, transcript) = line.split(args.delimiter) inputs = {'text': text, 'transcript': transcript.strip().split()} text = ' '.join(text.strip().split()) for p in ',.:;?!-_': text = text.replace(p, '') inputs['text'] = list(text.lo...
def encode_pyunicode_string(s): s = (list(map(ord, s)) + [0]) if (sys.maxunicode >= 65536): (utf16, utf32) = ([], s) for code_point in s: if (code_point >= 65536): (high, low) = divmod((code_point - 65536), 1024) utf16.append((high + 55296)) ...
def create_loss_func(npeak, nbins=None): import zfit bounds = (0.1, 3.0) obs = zfit.Space('x', limits=bounds) np.random.seed(0) tau = (- 2.0) beta = ((- 1) / tau) bkg = np.random.exponential(beta, 300) peak = np.random.normal(1.2, 0.1, npeak) data = np.concatenate((bkg, peak)) da...
def save_path_stats(x2role, output_fpath): with codecs.open(output_fpath, 'w', 'utf-8') as out: for (path, freq) in sorted(x2role.items(), key=operator.itemgetter(1), reverse=True): if (freq > 2): out.write('{}\t{}\n'.format(path, freq)) print('Output:', output_fpath)
def imload(filename, gray=False, scale_rate=1.0, enhance=False): if (not gray): image = cv2.imread(filename) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) if (scale_rate != 1.0): image = scale(image, scale_rate) if enhance: image = Image.fromarray(np.asarray(...
def generate_all_logical_forms_for_literal(value: str): lfs = [] date = (not (value.__contains__('integer') or value.__contains__('float'))) if date: for r in date_relations: if legal_relation(r): lfs.append(f'(AND {relations_info[r][0]} (JOIN {r} {value}))') else: ...
class GraphRepair(): def __init__(self, graph, nodes): self.graph = graph self.nodes = nodes self.repaired_items = set() def do(graph, nodes): gr = GraphRepair(graph, nodes) gr.remove_redundant_edges() gr.remove_unknown_nodes() def remove_unknown_nodes(self): ...
def _get_axes_excluding(ndim, axes): axes = _force_list(axes) axes = [(a + (ndim * (a < 0))) for a in axes] return [i for i in range(ndim) if (i not in axes)]
class EnsembleModel(nn.Module): def __init__(self, encoding_model, alignment_model, node_filter, top_k=5): super(EnsembleModel, self).__init__() self._encoding_model = encoding_model self._alignment_model = alignment_model self._weight = V(FT([1.0, 1.0])) self.node_filter = n...
def dot_product_scores(q_vectors: T, ctx_vectors: T) -> T: r = torch.matmul(q_vectors, torch.transpose(ctx_vectors, 0, 1)) return r
def save_state_dict(state_dict: StateDict, path): state_dict = {k: v for (k, v) in state_dict.items() if (v is not None)} if (jax.process_index() == 0): safetensors.numpy.save_file(state_dict, path, metadata={'format': 'pt'}) global _GLOBAL_SAVE_COUNT sync_global_devices(f'local {_GLOBAL_SAVE_CO...
class DiagonalTest(tf.test.TestCase): def test(self): for units in TEST_DIMENSIONS: diag_layer = Diagonal(units=units) self.assertAllClose(diag_layer(diag_layer.inverse_matrix), tf.eye(units))
def register_Ns3HigherLayerTxVectorTag_methods(root_module, cls): cls.add_constructor([param('ns3::HigherLayerTxVectorTag const &', 'arg0')]) cls.add_constructor([]) cls.add_constructor([param('ns3::WifiTxVector', 'txVector'), param('bool', 'adaptable')]) cls.add_method('Deserialize', 'void', [param('ns...
def unison_shuffled_copies_three(amat, bmat, slmat): ipdb.set_trace() assert ((len(amat) == len(bmat)) and (len(bmat) == len(slmat))) pmat = np.random.permutation(len(amat)) return (amat[pmat], bmat[pmat], slmat[pmat])
def run(): test_opts = TestOptions().parse() out_path_w = 'celebaha_w.npy' ckpt = torch.load(test_opts.checkpoint_path, map_location='cpu') opts = ckpt['opts'] opts.update(vars(test_opts)) opts = Namespace(**opts) net = StyleTransformer(opts) net.eval() net.cuda() print('Loading ...
def mask_cross_entropy(pred, target, label, reduction='mean', avg_factor=None, class_weight=None, ignore_index=None): assert (ignore_index is None), 'BCE loss does not support ignore_index' assert ((reduction == 'mean') and (avg_factor is None)) num_rois = pred.size()[0] inds = torch.arange(0, num_rois,...
class PNA(ScalableGNN): def __init__(self, num_nodes: int, in_channels: int, hidden_channels: int, out_channels: int, num_layers: int, aggregators: List[int], scalers: List[int], deg: Tensor, dropout: float=0.0, drop_input: bool=True, batch_norm: bool=False, residual: bool=False, pool_size: Optional[int]=None, buff...
def ignore_undocumented(name): if name.isupper(): return True if (name.endswith('PreTrainedModel') or name.endswith('Decoder') or name.endswith('Encoder') or name.endswith('Layer') or name.endswith('Embeddings') or name.endswith('Attention')): return True if (os.path.isdir(os.path.join(PATH_...
class SeparableUnderapproximationMemlet(UnderapproximationMemletPattern): def can_be_applied(self, expressions, variable_context, node_range, orig_edges): data_dims = len(expressions[0]) self.patterns_per_dim = ([None] * data_dims) params = variable_context[(- 1)] other_params = vari...
def save_concrete_function(function, input_signature, add_nms_plugin, opset, output_dir, target='tensorrt', model_params=None, simplify=True, large_model=False, debug=False): if (add_nms_plugin and (model_params is None)): raise ValueError('model_params are required to add NMS plugin') tf2onnx.logging.b...
def get_checkpoint_name(checkpoints_path, iteration, release=False, mp_rank=None): if release: d = 'release' else: d = 'iter_{:07d}'.format(iteration) return os.path.join(checkpoints_path, d, 'mp_rank_{:02d}'.format((mpu.get_model_parallel_rank() if (mp_rank is None) else mp_rank)), 'model_o...
def test_redundant_array_failure(): sdfg = _make_sdfg_1(succeed=False) sdfg.save('test2.sdfg') num = sdfg.apply_transformations(RedundantArray) assert (num == 0)
class Tower(BaseTower): def initialize(self): params = self.params placeholders = self.placeholders tensors = self.tensors variables_dict = self.variables_dict (N, J, V, Q, M) = (params.batch_size, params.max_sent_size, params.vocab_size, params.max_ques_size, params.mem_size...
class GitHubGetRepositoryDetails(VirtualFunctionTool): name = 'GitHubGetRepositoryDetails' summary = 'Retrieve repository details, including issues, branches.' parameters: List[ArgParameter] = [{'name': 'repo_id', 'type': 'string', 'description': 'The unique identifier of the repository.', 'required': True}...
def r_action1(t): def fn(k, n): if (n > MAX_FUNC_CALL): return (k, n, False) action = np.array([1, 0, 0, 0, 0]) try: k.state_transition(action) except: return (k, n, False) else: return (k, n, True) return [('action', fn)]
def MobileNet_arg_scope(weight_decay=0.0005): with slim.arg_scope([slim.batch_norm], decay=0.9, zero_debias_moving_mean=True, scale=True, activation_fn=tf.nn.relu): with slim.arg_scope([slim.convolution2d, slim.fully_connected], activation_fn=None, weights_initializer=tf.contrib.layers.variance_scaling_init...
def graph(A: np.ndarray) -> np.ndarray: probe = ((A != 0) * 1.0) probe = (((A + np.eye(A.shape[0])) != 0) * 1.0) return probe
_model_architecture('universal_transformer_lm', 'universal_transformer_lm_gpt') def transformer_lm_gpt(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 3072) args.decoder_layers = getattr(args, 'decoder_layers', 12) ...
class ShenNeumann(CompositeBase): def __init__(self, N, quad='GC', bc=(0, 0), domain=((- 1), 1), dtype=float, padding_factor=1, dealias_direct=False, coordinates=None, **kw): if isinstance(bc, (tuple, list)): bc = BoundaryConditions({'left': {'N': bc[0]}, 'right': {'N': bc[1]}}, domain=domain) ...
class SimpleReduction(nn.Module): def __init__(self, cs, heights, out_ch=64): super(SimpleReduction, self).__init__() (c1, c2, c3, c4) = cs (h1, h2, h3, h4) = heights def EfficientConvCompressH(in_c, out_c, scale, down_h): return nn.Sequential(PanoUpsampleW(scale), nn.Con...
def make_transform(model_type: str, resolution: int): if (model_type in ['ddpm', 'guidance_ddpm']): transform = transforms.Compose([transforms.Resize(resolution), transforms.ToTensor(), (lambda x: ((2 * x) - 1))]) elif (model_type in ['mae', 'swav', 'swav_w2', 'deeplab']): transform = transforms...
(frozen=True) class PassageQuestionInput(Input): def __init__(self, passage: str, question: str, passage_prefix: str='', question_prefix: str='Question: ', separator: str='\n'): super().__init__(f'{passage_prefix}{passage}{separator}{question_prefix}{question}')
class Comparable(object): def __eq__(self, other): return self._cmp(operator.eq, other) def __ge__(self, other): return self._cmp(operator.ge, other) def __gt__(self, other): return self._cmp(operator.gt, other) def __le__(self, other): return self._cmp(operator.le, other...
def SetPartitionsAk(k): (is_int, k) = _int_or_half_int(k) if (not is_int): return SetPartitionsAkhalf_k(k) return SetPartitionsAk_k(k)
class GanBase(nn.Module, metaclass=Named): def __init__(self, z_dim, img_channels, num_classes=None): self.z_dim = z_dim self.img_channels = img_channels super().__init__() def device(self): try: return self._device except AttributeError: self._dev...
def test_raises_on_floating_point_input(): with pytest.raises(ValueError): graph = csr_matrix([[0, 1.5], [0, 0]], dtype=np.float64) maximum_flow(graph, 0, 1) maximum_flow(graph, 0, 1, method='edmonds_karp')
class Cli(): def run(self, **kwargs): return self.extract(**kwargs) def extract(self, **kwargs): if ('out_path' in kwargs): kwargs['data.output.path'] = kwargs.pop('out_path') if ('tar_path' in kwargs): kwargs['shards_path'] = kwargs.pop('tar_path') if ('s...
class SRCNN(nn.Sequential): def __init__(self, n_colors=3): m = [nn.Conv2d(n_colors, 64, 9, padding=4), nn.ReLU(True), nn.Conv2d(64, 32, 1, padding=0), nn.ReLU(True), nn.Conv2d(32, 3, 5, padding=2)] super().__init__(*m) def get_kwargs(cfg, conv=common.default_conv): kwargs = {'n_colors':...
class Linear(nn.Module): def __init__(self, dim, variance=1.0, lengthscale=None): super(Linear, self).__init__() self.dim = torch.tensor([dim], requires_grad=False) if (lengthscale is None): self.lengthscale = torch.nn.Parameter(transform_backward(torch.ones(1, dim))) els...
def test_fb15k_237_load() -> None: _knowledge_graph_load(FB15k_237(), nodes=14541, rels=237, train=272115, test=20466, valid=17535)
class Request(BaseRequest, AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthorizationMixin, CORSRequestMixin, CommonRequestDescriptorsMixin):
def griddata(points, values, xi, method='linear', fill_value=np.nan, rescale=False): points = _ndim_coords_from_arrays(points) if (points.ndim < 2): ndim = points.ndim else: ndim = points.shape[(- 1)] if ((ndim == 1) and (method in ('nearest', 'linear', 'cubic'))): from .interpol...
class SuperProxylessNASNets(ProxylessNASNets): def __init__(self, width_stages, n_cell_stages, conv_candidates, stride_stages, n_classes=1000, width_mult=1, bn_param=(0.1, 0.001), dropout_rate=0): self._redundant_modules = None self._unused_modules = None input_channel = make_divisible((32 *...
class DataLoader(): def __init__(self, json_path): self.json_path = json_path with open(self.json_path, 'r') as f: data = json.load(f) self.content = self.solveData(data) def solveData(self, data): content = [] for key in sorted(data.keys()): detec...
def np_to_pytorch_batch(np_batch): return {k: _elem_or_tuple_to_variable(x) for (k, x) in _filter_batch(np_batch) if (x.dtype != np.dtype('O'))}
def _parse_version_parts(s): for part in _legacy_version_component_re.split(s): part = _legacy_version_replacement_map.get(part, part) if ((not part) or (part == '.')): continue if (part[:1] in ''): (yield part.zfill(8)) else: (yield ('*' + part)) ...
def reflection(a=np.zeros(3), b=((2 * np.pi) * np.ones(3))): angles = np.zeros(3) for i in range(3): angles[i] = np.random.uniform(a[i], b[i], 1) (cos1, sin1) = (np.cos(angles[0]), np.sin(angles[0])) (cos2, sin2) = (np.cos(angles[1]), np.sin(angles[1])) u = np.array([[sin1, (cos1 * sin2), (c...
class listingType(GeneratedsSuper): subclass = None superclass = None def __init__(self, codeline=None): if (codeline is None): self.codeline = [] else: self.codeline = codeline def factory(*args_, **kwargs_): if listingType.subclass: return li...
class MultiheadAttention(SequenceModule): def __init__(self, d_model, n_heads, *args, causal=True, **kwargs): super().__init__() self.d_model = d_model self.d_output = d_model self.mha = nn.MultiheadAttention(d_model, n_heads, *args, batch_first=True, **kwargs) self.causal = ...
def conv_block(in_channels, out_channels): return nn.Sequential(nn.Conv2d(in_channels, out_channels, 3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(), nn.MaxPool2d(2))
def evalkernels(): with open(os.path.join(CURRENT_DIR, '..', 'awkward-cpp', 'tests-spec', 'kernels.py')) as kernelfile: exec(kernelfile.read(), globals())
def closest_parent_sourcepos(elem): while (elem.sourcepos is None): elem = elem.parent return elem.sourcepos
class GLUETransformer(BaseTransformer): mode = 'sequence-classification' def __init__(self, hparams): if (type(hparams) == dict): hparams = Namespace(**hparams) hparams.glue_output_mode = glue_output_modes[hparams.task] num_labels = glue_tasks_num_labels[hparams.task] ...
class PretrainNpcPipe(SequentialDataPipe): def __init__(self, output_keys: dict=None, feat_type: str='fbank', feat_dim: int=80, frame_length: int=25, frame_shift: int=10, decode_wav: bool=False, cmvn: bool=True, audio_sample_rate: int=16000, audio_channel_reduction: str='first', n_jobs: int=6): output_keys ...
class SplitBenchmark(op_bench.TorchBenchmarkBase): def init(self, M, N, parts, device): self.input_one = torch.rand(M, N, device=device) self.split_size = int(((M * N) / parts)) self.set_module_name('split') def forward(self): return torch.split(self.input_one, self.split_size)
def munge(src_dir): files = os.listdir(src_dir) for fn in files: (base, ext) = os.path.splitext(fn) first = base[:14] second = base[:22] dst_dir = os.path.join('MCG', 'mat', first, second) if (not os.path.exists(dst_dir)): os.makedirs(dst_dir) src = os...
def convert_weights_and_push(save_directory: Path, model_name: str=None, push_to_hub: bool=True): filename = 'imagenet-1k-id2label.json' num_labels = 1000 expected_shape = (1, num_labels) repo_id = 'huggingface/label-files' num_labels = num_labels id2label = json.load(open(cached_download(hf_hub...
class RetrievalModel(BaseModel): def __init__(self, output_channels, freeze=False, freezeBN=False): super(RetrievalModel, self).__init__() self.output_channels = output_channels self.backbone = resnet50(output_channels) if freeze: self.freeze() if freezeBN: ...
class precision_recall(object): def __init__(self, inception_model, device): self.inception_model = inception_model self.device = device self.disable_tqdm = (device != 0) def generate_images(self, gen, dis, truncated_factor, prior, latent_op, latent_op_step, latent_op_alpha, latent_op_be...
class MaxPool2dSamePad(nn.MaxPool2d): PAD_VALUE: float = (- float('inf')) def __init__(self, kernel_size: int, stride=1, padding=0, dilation=1, ceil_mode=False, count_include_pad=True): assert (padding == 0), 'Padding in MaxPool2d Same Padding should be zero' kernel_size = (kernel_size, kernel_s...
.parametrize('coupling', ['additive', 'affine']) def test_normal_vs_invertible_module_wrapper(coupling): for seed in range(10): set_seeds(seed) X = torch.rand(2, 4, 5, 5) c1 = torch.nn.Conv2d(2, 2, 3, padding=1) c2 = torch.nn.Conv2d(2, 2, 3, padding=1) c1_2 = copy.deepcopy(c1...
class StableDiffusionOnnxPipeline(metaclass=DummyObject): _backends = ['transformers', 'onnx'] def __init__(self, *args, **kwargs): requires_backends(self, ['transformers', 'onnx'])
def save_checkpoint(epoch): if (hvd.rank() == 0): os.remove(args.checkpoint_format.format(epoch=epoch)) filepath = args.checkpoint_format.format(epoch=(epoch + 1)) state = {'model': model.state_dict(), 'optimizer': optimizer.state_dict()} torch.save(state, filepath)
def lnlstm_creator(script=True, decompose_layernorm=False, **kwargs): assert (script is True) from .custom_lstms import script_lnlstm input_size = kwargs['inputSize'] hidden_size = kwargs['hiddenSize'] seq_len = kwargs['seqLength'] batch_size = kwargs['miniBatch'] ge = script_lnlstm(input_si...
def load_train_files(root_path, cfg, split): spk2idx = {} npys = cfg[split]['wav_files'] labs = cfg[split]['spk_ids'] Y = [] X = [] spk2idx = {} for (npy, lab) in zip(npys, labs): npy_name = os.path.join(root_path, npy) x = np.load(npy_name) if (lab not in spk2idx): ...
class TorchMBRLAlgorithm(MBRLAlgorithm): def to(self, device): for net in self.trainer.networks: net.to(device) for net in self.model_trainer.networks: net.to(device) def training_mode(self, mode): for net in self.trainer.networks: net.train(mode) ...
class E1000NIC(NICSim): def __init__(self) -> None: super().__init__() self.debug = False def run_cmd(self, env: ExpEnv) -> str: cmd = self.basic_run_cmd(env, '/e1000_gem5/e1000_gem5') if self.debug: cmd = ('env E1000_DEBUG=1 ' + cmd) return cmd
def evaluate(model, criterion, corpus, data_source, eval_batch_size): model.eval() total_loss = 0.0 total_words = 0.0 total_entropy = 0.0 ntokens = len(corpus.dictionary) hidden = model.init_hidden(eval_batch_size) with torch.no_grad(): for i in range(0, (data_source.size(0) - 1), ar...
def insert_tokenizer_in_auto_module(old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns): if ((old_model_patterns.tokenizer_class is None) or (new_model_patterns.tokenizer_class is None)): return with open((((TRANSFORMERS_PATH / 'models') / 'auto') / 'tokenization_auto.py'), 'r', encodi...
def load_model_and_optimizer(model, optimizer, model_state, optimizer_state): model.load_state_dict(model_state, strict=True) optimizer.load_state_dict(optimizer_state)
class AssertNetTest(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 AssertNet() def compar...
def _to_space_separated_string(l, base_ring=None): if base_ring: return ' '.join((repr(base_ring(x)) for x in l)) return ' '.join((repr(x) for x in l))
def dataset_for_class(i): ds = sample_dataset() i = tf.cast(i, tf.uint8) return ds.filter((lambda image, label: (label == i))).repeat()
def check_float_range(min_val, max_val): def helper(x): x = float(x) if ((x < min_val) or (x > max_val)): raise argparse.ArgumentTypeError('Value must be between {} and {}.'.format(min_val, max_val)) return x return helper
class GCSInterface(ObjectStoreInterface): def __init__(self, bucket_name: str): self.bucket_name = bucket_name self.auth = compute.GCPAuthentication() self._gcs_client = self.auth.get_storage_client() self._requests_session = requests.Session() def provider(self): return ...
def update_indiv_generation_losses(losses, nums, micro, macro, bs, length, loss): nums[micro] += (bs * length) batch_loss = (loss * bs) losses[micro][(- 1)] += batch_loss losses[micro][(- 1)] /= nums[micro] losses[macro][(- 1)] += (batch_loss / length) losses[macro][(- 1)] /= nums[macro]
(config_path='config', config_name='main', version_base=None) def main(cfg): local_rank = int(os.environ.get('LOCAL_RANK', (- 1))) (cfg_dict, tags) = prepare_logging(cfg) training_args = run_clm.TrainingArguments(**cfg_dict['training_args'], local_rank=local_rank) model_args = run_clm.ModelArguments(**c...
def test_method_get_accessible_object(default_test_case, method_mock, variable_reference_mock): meth = stmt.MethodStatement(default_test_case, method_mock, variable_reference_mock) assert (meth.accessible_object() == method_mock)
def get_schemas_from_json(fpath): with open(fpath) as f: data = json.load(f) db_names = [db['db_id'] for db in data] tables = {} schemas = {} for db in data: db_id = db['db_id'] schema = {} column_names_original = db['column_names_original'] table_names_origin...
_function_dispatch(_partition_dispatcher) def partition(a, kth, axis=(- 1), kind='introselect', order=None): if (axis is None): a = asanyarray(a).flatten() axis = (- 1) else: a = asanyarray(a).copy(order='K') a.partition(kth, axis=axis, kind=kind, order=order) return a
class ModelInfo(): def __init__(self, modelId: str, key: str, author: Optional[str]=None, downloads: Optional[int]=None, tags: List[str]=[], pipeline_tag: Optional[str]=None, siblings: Optional[List[Dict]]=None, **kwargs): self.modelId = modelId self.key = key self.author = author se...
class MatrixMorphism_abstract(sage.categories.morphism.Morphism): def __init__(self, parent, side='left'): if (not sage.categories.homset.is_Homset(parent)): raise TypeError('parent must be a Hom space') if (side not in ['left', 'right']): raise ValueError("the argument side ...
class MLP_4HL(nn.Module): def __init__(self, dim_in, dim_hidden1, dim_hidden2, sparse=False, bn=True): super(MLP_3HL, self).__init__() self.in_layer = (SpLinear(dim_in, dim_hidden1) if sparse else nn.Linear(dim_in, dim_hidden1)) self.dropout_layer = nn.Dropout(0.0) self.lrelu = nn.Le...
(scope='session') def random_data(): batch_size = 4 x = np.random.random((batch_size, 28, 28, 3)) y = tf.keras.utils.to_categorical(np.random.randint(2, size=batch_size), num_classes=2).astype('uint8') return (x, y)
class GNConv(nn.Module): def __init__(self, edge_model_block, node_model_block, global_model_block, use_edge_block=True, use_node_block=True, use_global_block=True, update_graph=False): super(GNConv, self).__init__() self.edge_model_block = edge_model_block self.node_model_block = node_model...
def main(_): g = tf.Graph() with g.as_default(): model = inference_wrapper.InferenceWrapper() restore_fn = model.build_graph_from_config(configuration.ModelConfig(), FLAGS.checkpoint_path) g.finalize() vocab = vocabulary.Vocabulary(FLAGS.vocab_file) filenames = [] for file_patter...
def assign_hgraph_singletons(hgraph, singletons, singleton_type='grey_out'): if (singleton_type == 'grey_out'): for node in hgraph['nodes']: if (node['id'].replace('|', '') in singletons): node['if_singleton'] = True else: node['if_singleton'] = False ...
def get_balanced_output_list_for_evidence_context_data(output_list: list[ProcessedData]): label_split = {'supported': [], 'partially_supported': [], 'not_supported': []} for d in output_list: label_split[d['label']].append(d) new_output_list: list[dict] = [] for label in ['supported', 'partially...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size...
def module_init(): root_module = Module('ns.mobility', cpp_namespace='::ns3') return root_module
class Date(): def __init__(self, year=None, month=None, day=None): self.year = year self.month = month self.day = day
def unsupervised_training_one_epoch(adata: AnnData, run_setup_anndata: bool=True, batch_key: Optional[str]=None, labels_key: Optional[str]=None): if run_setup_anndata: SCVI.setup_anndata(adata, batch_key=batch_key, labels_key=labels_key) m = SCVI(adata) m.train(1, train_size=0.4)
def _reshape_for_microbatch(Batch: Axis, Microbatch: Axis, AccumStep: Axis, inputs, axis_mapping): def _reshape(x): if isinstance(x, hax.NamedArray): if (not x.has_axis(Batch.name)): return x x = x.unflatten_axis(Batch, (AccumStep, Microbatch)) return hax....
def test(sim_time, qc_atten): network_config = 'star_network.json' network_topo = RouterNetTopo(network_config) set_parameters(network_topo, sim_time, qc_atten) quantum_router_nodes = network_topo.get_nodes_by_type(RouterNetTopo.QUANTUM_ROUTER) node_names = [node.name for node in quantum_router_node...
def make_rectangle(img_size=(64, 64), num_points_per_cluster=8, cluster_radius=1): is_rectangle = False while (not is_rectangle): point_1_x = random.randint((0 + cluster_radius), (img_size[0] - cluster_radius)) point_1_y = random.randint((0 + cluster_radius), (img_size[1] - cluster_radius)) ...
def build_roi_box_head(cfg, in_channels): if cfg.MODEL.ROI_BOX_HEAD.WSDDN: return WSDDNHead(cfg, in_channels) else: return ROIBoxHead(cfg, in_channels)