code
stringlengths
101
5.91M
class AveragePoolingDataGrad(UnaryDataGrad): def __init__(self, ctx, kernel, stride=None, ignore_border=True, pad=None, channel_last=False, including_pad=True): super(AveragePoolingDataGrad, self).__init__(ctx) self._func = _F.AveragePooling(ctx, kernel, stride, ignore_border, pad, channel_last, inc...
def norm(a, ord=None, axis=None, keepdims=False, check_finite=True): if check_finite: a = np.asarray_chkfinite(a) else: a = np.asarray(a) if (a.size and (a.dtype.char in 'fdFD') and (axis is None) and (not keepdims)): if ((ord in (None, 2)) and (a.ndim == 1)): nrm2 = get_...
(frozen=True) class DistributedConfig(): coordinator_address: Optional[str] = None num_processes: Optional[int] = None process_id: Optional[int] = None local_device_ids: Optional[Union[(int, List[int])]] = None def _is_distributed(self): if ((self.coordinator_address is not None) or (self.nu...
def train_std_scaler(X): xscaler = prep.StandardScaler() fX = [] for x in X: fX.extend(x) xscaler.fit(fX) return xscaler
class GaussianMLPRegressorModel(GaussianMLPModel): def __init__(self, input_shape, output_dim, name='GaussianMLPRegressorModel', **kwargs): super().__init__(output_dim=output_dim, name=name, **kwargs) self._input_shape = input_shape def network_output_spec(self): return ['means', 'log_st...
def _valid_accessor(acc): if (not isinstance(acc, tuple)): return False if (len(acc) != 2): return False return (isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1])))
def test_constructor_param_count_of_type_none(default_test_case, constructor_mock): const = stmt.ConstructorStatement(default_test_case, constructor_mock) assert (const._param_count_of_type(AnyType()) == 0)
def verbosity_to_loglevel(verbosity): if (verbosity <= 0): log_level = logging.ERROR warnings.filterwarnings('ignore') elif (verbosity == 1): log_level = logging.WARNING elif (verbosity == 2): log_level = logging.INFO else: log_level = logging.DEBUG return log...
class QuantEmbedding(nn.Module): def __init__(self, num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False, _weight=None, weight_bit=8, momentum=0.95, quant_mode=False): super().__init__() self.num_ = num_embeddings self.dim = em...
class ConfigurationError(Exception): def __init__(self, msg): super(ConfigurationError, self).__init__() self._msg = msg def message(self): return self._msg
def random_str(length: int=4) -> str: return ''.join(random.choices((string.ascii_letters + string.digits), k=4))
class _BatchNorm(nn.Module): def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True): super(_BatchNorm, self).__init__() self.num_features = num_features self.eps = eps self.momentum = momentum self.affine = affine self.track_r...
def draw_rectangle(img, bbox, bbox_color=(255, 255, 255), thickness=3, is_opaque=False, alpha=0.5): output = img.copy() if (not is_opaque): cv2.rectangle(output, (bbox[0], bbox[1]), (bbox[2], bbox[3]), bbox_color, thickness) else: overlay = img.copy() cv2.rectangle(overlay, (bbox[0],...
def exp(field): def func(edges): return {field: torch.exp(edges.data[field].sum((- 1), keepdim=True).clamp((- 5), 5))} return func
class RobertaForMultipleChoice(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def register_Ns3Ipv4MaskChecker_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return
class LEDForQuestionAnswering(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
class DebugUnderflowOverflow(): def __init__(self, model, max_frames_to_save=21, trace_batch_nums=[], abort_after_batch_num=None): self.model = model self.trace_batch_nums = trace_batch_nums self.abort_after_batch_num = abort_after_batch_num self.frames = collections.deque([], max_fr...
class NoTransformerFoundationCache(FoundationCache): def load_bert(self, transformer_name): return load_bert(transformer_name)
def LatticePoset(data=None, *args, **options): if (isinstance(data, FiniteLatticePoset) and (not args) and (not options)): return data if ('check' in options): check = options.pop('check') else: check = True P = Poset(data, *args, **options) if (P.cardinality() != 0): ...
class Bottleneck_depthwise_ip(Bottleneck): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(Bottleneck_depthwise_ip, self).__init__(inplanes, planes, stride, downsample, dilation) self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False) ...
_jieba class CPMAntTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = CpmAntTokenizer test_rust_tokenizer = False def setUp(self): super().setUp() vocab_tokens = ['<d>', '</d>', '<s>', '</s>', '</_>', '<unk>', '<pad>', '</n>', '', '', 'C', 'P', 'M', 'A', 'n', 't'] ...
def get_paws_loss(multicrop=6, tau=0.1, T=0.25, me_max=True): def sharpen(proba): sharp_p = (proba ** (1.0 / T)) sharp_p /= tf.reduce_sum(sharp_p, axis=1, keepdims=True) return sharp_p def snn(query, supports, labels): query = tf.math.l2_normalize(query, axis=1) supports ...
class HubertFeatureReaderS2T(HubertFeatureReader): def read_audio(self, path, ref_len=None): (path, *extra) = path.split(':') assert (len(extra) == 2) assert path.endswith('.zip') data = read_from_uncompressed_zip(path, int(extra[0]), int(extra[1])) f = io.BytesIO(data) ...
class IntegralProjectivePlaneCurve_finite_field(IntegralProjectiveCurve_finite_field, ProjectivePlaneCurve_finite_field): _point = IntegralProjectivePlaneCurvePoint_finite_field
def entropy(p): plogp = (p * torch.log(p)) plogp[(p == 0)] = 0 return (- plogp.sum(dim=(- 1)))
class LogFormatter(logging.Formatter): DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s' DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S' DEFAULT_COLORS = {logging.DEBUG: 4, logging.INFO: 2, logging.WARNING: 3, logging.ERROR: 1} def __init__(self, color=Tru...
def MannWhitney(data_A, data_B): if ((n < 20) or (m < 20)): print('Use only when the number of observation in each sample is > 20') return 1.0 (_, pval) = Utest(data_A, data_B, alternative='less') return pval
def buffered_db_writer(conn, table_name, table_schema, buff_size=100, slice_id=0): driver = conn.driver if (driver == 'maxcompute'): w = db_writer.MaxComputeDBWriter(conn, table_name, table_schema, buff_size) elif (driver == 'mysql'): w = db_writer.MySQLDBWriter(conn, table_name, table_schem...
class InputFeatures(object): def __init__(self, unique_id, example_index, paragraph_index=None, doc_span_index=None, doc_tokens=None, tokens=None, token_to_orig_map=None, token_is_max_context=None, input_ids=None, input_mask=None, segment_ids=None, start_position=None, end_position=None, switch=None, answer_mask=No...
def main(all_settings): oie_data_dir = 'SORE/data/OpenIE/processed/' sore_output_dir = 'SORE/data/processed_data/' brat_output_dir = 'SORE/data/brat_annotations/' prep = all_settings['Prepare_data'] parse_narrow = all_settings['Parse_narrowIE_predictions'] runOIE = all_settings['Run_OIE'] fi...
class AST_RangeExpression(AST_Node): def __init__(self, context, lhs, rhs): AST_Node.__init__(self, context) self.lhs = lhs self.rhs = rhs def __repr__(self): return (((('AST_RangeExpression(' + str(self.lhs)) + ', ') + str(self.rhs)) + ')') def get_children(self): L ...
class LIM(Model): def __init__(self, cfg, emb_dim): super().__init__(name=cfg['name']) cfg['num_inputs'] = (2 * emb_dim) if ('augment' in cfg.keys()): self.augment = cfg['augment'] else: self.augment = False self.minion = minion_maker(cfg) self...
def create_sin_dataset(n, p): x1 = (5 * np.random.uniform(0, 1, n).reshape((- 1), 1)) x2 = (5 * np.random.uniform(0, 1, n).reshape((- 1), 1)) y = (np.sin(x1) * (np.cos(x2) ** 3)) relevant = np.hstack((x1, x2)) noise_vector = norm.rvs(loc=0, scale=1, size=[n, (p - 2)]) data = np.concatenate([rele...
class TestLRN(test_util.TestCase): def setUp(self): self.test_configs = [(6, 10), (3, 13)] def testLRN(self): for (input_size, depth) in self.test_configs: op = core.CreateOperator('LRN', ['X'], ['Y', 'Y_scale'], size=11, alpha=0.001, beta=0.5, bias=2.0, order='NHWC') X =...
def test_SincConv(device): from speechbrain.nnet.CNN import SincConv input = torch.rand([4, 16000], device=device) convolve = SincConv(input_shape=input.shape, out_channels=8, kernel_size=65, padding='same').to(device) output = convolve(input) assert (output.shape[(- 1)] == 8) assert torch.jit.t...
def local_density_congruence(self, p, m, Zvec=None, NZvec=None): return ((self.local_good_density_congruence(p, m, Zvec, NZvec) + self.local_zero_density_congruence(p, m, Zvec, NZvec)) + self.local_bad_density_congruence(p, m, Zvec, NZvec))
class FiniteWordPath_dyck_callable(WordDatatype_callable, FiniteWordPath_dyck, FiniteWord_class): pass
class PairwiseDistance(Module): def __init__(self, p): super(PairwiseDistance, self).__init__() assert ((p % 1) == 0) self.gradInput = [] self.diff = torch.Tensor() self.norm = p self.outExpand = None self.grad = None self.ones = None def updateOut...
def qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False, overwrite_b=False, check_finite=True): (result, _) = _qz(A, B, output=output, lwork=lwork, sort=sort, overwrite_a=overwrite_a, overwrite_b=overwrite_b, check_finite=check_finite) return (result[0], result[1], result[(- 4)], result[(- 3)])
class IfAllStructural(Visitor): def __init__(self) -> None: super().__init__() self.res = True def __call__(self, node): super().__call__(node) def visit_A_Expr(self, ancestors, node: A_Expr): if (self.res is False): return def is_structural(expr): ...
_model def ig_resnext101_32x16d(pretrained=True, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], cardinality=32, base_width=16, **kwargs) return _create_resnet('ig_resnext101_32x16d', pretrained, **model_args)
class ZeroEvenOpTest(unittest.TestCase): def _run_zero_even_op(self, X): op = core.CreateOperator('ZeroEven', ['X'], ['Y']) workspace.FeedBlob('X', X) workspace.RunOperatorOnce(op) Y = workspace.FetchBlob('Y') return Y def _run_zero_even_op_gpu(self, X): with core...
def compute_stab_reg(args, model, meter, eps, eps_scheduler): loss = torch.zeros(()).to(args.device) if isinstance(model, BoundDataParallel): modules = list(model._modules.values())[0]._modules else: modules = model._modules nodes = {} for m in modules.values(): if isinstance...
def helper_variable_scope(): with tf_util.reuse_name_scope('IO', absolute=True) as scope: (yield scope)
class ArrayDim(AstNode): def __init__(self, sizes): super(ArrayDim, self).__init__() self.sizes_as_declared = sizes self.size_str = None self.size_int = None self._dynamic = None self._auto_member = None def dynamic(self): if (self._dynamic is None): ...
def layer_norm_linear_fn(x, norm_weight, norm_bias, linear_weight, linear_bias, residual=None, eps=1e-06, prenorm=False, residual_in_fp32=False, is_rms_norm=False): return LayerNormLinearFn.apply(x, norm_weight, norm_bias, linear_weight, linear_bias, residual, eps, prenorm, residual_in_fp32, is_rms_norm)
class Config(object): def _file2dict(filename): filename = osp.abspath(osp.expanduser(filename)) check_file_exist(filename) if filename.endswith('.py'): with tempfile.TemporaryDirectory() as temp_config_dir: shutil.copyfile(filename, osp.join(temp_config_dir, '_te...
def test__get_qualified_name_class(): fully_qualified_name = _get_qualified_name(Constraint) expected_name = 'sdv.constraints.base.Constraint' assert (fully_qualified_name == expected_name)
class DepthWiseConv1d(nn.Module): def __init__(self, chan_in, chan_out, kernel_size, padding): super().__init__() self.padding = padding self.conv = nn.Conv1d(chan_in, chan_out, kernel_size, groups=chan_in) def forward(self, x): x = F.pad(x, self.padding) return self.conv...
_on_pypy def test_cyclic_gc(): instance = m.DynamicClass() instance.circular_reference = instance cstats = ConstructorStats.get(m.DynamicClass) assert (cstats.alive() == 1) del instance assert (cstats.alive() == 0) i1 = m.DynamicClass() i2 = m.DynamicClass() i1.cycle = i2 i2.cycl...
class Caffe2Tracer(): def __init__(self, cfg: CfgNode, model: nn.Module, inputs): assert isinstance(cfg, CfgNode), cfg assert isinstance(model, torch.nn.Module), type(model) if ('EXPORT_CAFFE2' not in cfg): cfg = add_export_config(cfg) C2MetaArch = META_ARCH_CAFFE2_EXPORT...
class EarlyStopping(): def __init__(self, model, checkpoint_instance, early_stop_criteria='total_loss', patience=1000, minimize=False, should_stop=True): self.minimize = minimize self.patience = patience self.model = model self.checkpoint = checkpoint_instance self.early_stop...
def add_rotation_to_pcloud(pcloud): r_rotation = rand_rotation_matrix() if (len(pcloud.shape) == 2): return pcloud.dot(r_rotation) else: return np.asarray([e.dot(r_rotation) for e in pcloud])
def register_Ns3LteRrcSapAntennaInfoCommon_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::LteRrcSap::AntennaInfoCommon const &', 'arg0')]) cls.add_instance_attribute('antennaPortsCount', 'uint16_t', is_const=False) return
class WeightNorm(object): name: str dim: int def __init__(self, name: str, dim: int) -> None: if (dim is None): dim = (- 1) self.name = name self.dim = dim def compute_weight(self, module: Module) -> Any: g = getattr(module, (self.name + '_g')) v = get...
def _decompression_bomb_check(size): if (MAX_IMAGE_PIXELS is None): return pixels = (size[0] * size[1]) if (pixels > (2 * MAX_IMAGE_PIXELS)): raise DecompressionBombError(('Image size (%d pixels) exceeds limit of %d pixels, could be decompression bomb DOS attack.' % (pixels, (2 * MAX_IMAGE_P...
(wandb=True, sh=True) .slow def test_optuna_sweep_ddp_sim_wandb(tmp_path): command = [startfile, '-m', 'hparams_search=mnist_optuna', ('hydra.sweep.dir=' + str(tmp_path)), 'hydra.sweeper.n_trials=5', 'trainer=ddp_sim', 'trainer.max_epochs=3', '+trainer.limit_train_batches=0.01', '+trainer.limit_val_batches=0.1', '+...
_module() class YOLOV3(SingleStageDetector): def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None): super(YOLOV3, self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained)
def colorize_mask(image_array): new_mask = Image.fromarray(image_array.astype(np.uint8)).convert('P') new_mask.putpalette(color_mapping) return new_mask
class Config(object): def __init__(self, conf=None, **kwargs): super(Config, self).__init__() config = ConfigParser() config.read((conf or [])) self.update({**dict(((name, literal_eval(value)) for section in config.sections() for (name, value) in config.items(section))), **kwargs}) ...
_cmd('lint') class Lint(): def run(): run_doit_task({'lint': {}, 'unicode-check': {}, 'check-testname': {}})
def load_solve_state_from_h5(nnp, filename): class SolverState(): def __init__(self): self.t = 0 self.pstate = {} states = OrderedDict() with get_file_handle_load(nnp, filename, '.h5') as f: skeys = [] pkeys = set() def _get_skeys(name, obj): ...
def reduction_test_3(A: dace.float64[(M, N)], B: dace.float64[(M, N)], C: dace.float64[N]): tmp = dace.reduce((lambda a, b: max(a, b)), A, identity=(- 9999999), axis=0) tmp2 = dace.reduce((lambda a, b: (a + b)), B, identity=0, axis=0) for i in dace.map[0:N]: with dace.tasklet: (in1 << tm...
_driver.jit def NumbaClassicControlAcrobotEnvStep(state_arr, action_arr, done_arr, reward_arr, observation_arr, env_timestep_arr, episode_length): kEnvId = numba_driver.blockIdx.x kThisAgentId = numba_driver.threadIdx.x TORQUE = numba_driver.const.array_like(AVAIL_TORQUE) assert (kThisAgentId == 0), 'We...
def unregister(): bpy.utils.unregister_module(__name__) bpy.types.INFO_MT_file_import.remove(menu_func_import)
_start_docstrings('The bare MMBT Model outputting raw hidden-states without any specific head on top.', MMBT_START_DOCSTRING) class MMBTModel(nn.Module, ModuleUtilsMixin): def __init__(self, config, transformer, encoder): super().__init__() self.config = config self.transformer = transformer...
def percent_good_ring(x_fake, var=0.0001, n_clusters=8, radius=2.0): std = np.sqrt(var) thetas = np.linspace(0, (2 * np.pi), (n_clusters + 1))[:n_clusters] (x, y) = ((radius * np.sin(thetas)), (radius * np.cos(thetas))) threshold = np.array([(std * 3), (std * 3)]) means = [] for i in range(n_clu...
def matplotlib_imshow(img, one_channel=False): (fig, ax) = plt.subplots(figsize=(10, 6)) ax.imshow(img.permute(1, 2, 0).numpy())
def do_title(s): return ''.join([(item[0].upper() + item[1:].lower()) for item in _word_beginning_split_re.split(soft_unicode(s)) if item])
class RoIAwarePool3dFunction(Function): def forward(ctx, rois, pts, pts_feature, out_size, max_pts_per_voxel, mode): if isinstance(out_size, int): out_x = out_y = out_z = out_size else: assert (len(out_size) == 3) assert mmcv.is_tuple_of(out_size, int) ...
def log_normal_diag(x, mean, log_var, average=False, dim=None): log_normal = ((- 0.5) * ((log_var + log_2_pi) + (torch.pow((x - mean), 2) / torch.exp(log_var)))) if average: return torch.mean(log_normal, dim) else: return torch.sum(log_normal, dim)
class EmbeddingImagenet(nn.Layer): def __init__(self, emb_size): super(EmbeddingImagenet, self).__init__() self.emb_size = emb_size self.ndf = 64 self.conv1 = nn.Conv2D(3, self.ndf, kernel_size=3, stride=1, padding=1, bias_attr=False) self.bn1 = nn.BatchNorm2D(self.ndf) ...
def price_sum(x: list) -> int: res = 0 for item in x: res += int(item[C.Keys.PRICE]) return res
def apply_bias_correction_to_graph(graph_to_apply_bias_correction: Graph, core_config: CoreConfig, fw_impl: FrameworkImplementation) -> Graph: graph = copy.deepcopy(graph_to_apply_bias_correction) for n in graph.nodes: if (n.is_weights_quantization_enabled() and core_config.quantization_config.weights_b...
_model def seresnext26d_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['seresnext26d_32x4d'] model = ResNet(Bottleneck, [2, 2, 2, 2], cardinality=32, base_width=4, stem_width=32, stem_type='deep', avg_down=True, num_classes=num_classes, in_chans=in_chans, block_args=...
def state_form_z(z, q, y, v, geometry): return ((dot(grad(z), grad(q)) * geometry.dx) - (((y + v) * q) * geometry.dx))
class TestTorch(test_inference.TestInference): def setUp(self): if skip: raise unittest.SkipTest('PyTorch not installed') test_inference.TestInference.setUp(self) self.engine = FactoredInference(self.domain, backend='torch', log=True)
def r_cond2(t): cond = t[2] def fn(world, n): if (n > MAX_FUNC_CALL): return (world, n, False, False) (world, n, s, c) = cond(world, n) return (world, n, s, (not c)) return [('cond', fn)]
def rpn(base_layers, num_anchors): x = Convolution2D(512, (3, 3), padding='same', activation='relu', kernel_initializer='normal', name='rpn_conv1')(base_layers) x_class = Convolution2D(num_anchors, (1, 1), activation='sigmoid', kernel_initializer='uniform', name='rpn_out_class')(x) x_regr = Convolution2D((n...
class TestFeatureColumnBase(unittest.TestCase): def check(self, column, column_names, inputs, expected_outputs): if (not isinstance(inputs, (list, tuple))): inputs = (inputs,) if (not isinstance(expected_outputs, (list, tuple))): expected_outputs = (expected_outputs,) ...
class ComputeBucketAssignmentTest(TestCase): def test_single_limit_single_dtype(self): tensors = [torch.empty([100], dtype=torch.float), torch.empty([200], dtype=torch.float), torch.empty([100], dtype=torch.float), torch.empty([50], dtype=torch.float)] result = dist._compute_bucket_assignment_by_siz...
class UnaryBinaryExpressionGen(): def __init__(self, unary_ops: T.Sequence[OpProbability], binary_ops: T.Sequence[OpProbability], leaves: T.Sequence[sf.Scalar]): self.unary_ops = unary_ops self.binary_ops = binary_ops self.leaves = leaves self.ops = (list(self.unary_ops) + list(self....
_args('v', 'i', 'v', 'v', 'v', 'v') def empty(g, sizes, dtype, layout, device, pin_memory=False, memory_format=None): return zeros(g, sizes, dtype, layout, device, pin_memory)
class IsMaleLabeler(Labeler): def __init__(self, ontology: extension_datasets.Ontology): self.male_code: str = 'Gender/M' def label(self, patient: Patient) -> List[Label]: is_male: bool = (self.male_code in [e.code for e in patient.events]) labels: List[Label] = [] for event in p...
class MobileViTFeatureExtractor(metaclass=DummyObject): _backends = ['vision'] def __init__(self, *args, **kwargs): requires_backends(self, ['vision'])
_to_string_io def load_events(fhandle: TextIO) -> annotations.Events: times = [] labels = [] confidence = [] default_headers = ['start', 'end', 'label', 'confidence'] reader = csv.DictReader(fhandle, delimiter='\t', fieldnames=default_headers) for line in reader: times.append([float(line...
def test(): x = np.arange((- 100.0), 101.0, 5.0) y = np.arange((- 100.0), 101.0, 5.0) (x_vec, y_vec) = b_hat(x, y) fig = plt.figure(figsize=(10, 8)) ax1 = plt.subplot('111') ax1.quiver(x, y, x_vec, y_vec) for i in range((- 120), 121, 10): (x, y) = b_line(float(i), 0.0, 100) a...
class QuantAct(nn.Module): def __init__(self, activation_bit, act_range_momentum=0.95, per_channel=False, channel_len=None, quant_mode=False): super().__init__() self.activation_bit = activation_bit self.act_range_momentum = act_range_momentum self.quant_mode = quant_mode sel...
def assure_array_length(array, size, value=128): while (len(array) < size): array.append(value)
def main(args, model): misc.init_distributed_mode(args) device = torch.device(args.device) misc.fix_random_seeds(args) cudnn.benchmark = True create_dataset_and_evalmetrix(args, mode='finetune') if args.disable_eval_during_finetuning: dataset_val = None else: dataset_val = Da...
class BLEUScore(NGramScore): TINY = 1e-15 SMALL = 1e-09 def __init__(self, max_ngram=4, case_sensitive=False, smoothing=0.0): super(BLEUScore, self).__init__(max_ngram, case_sensitive) self.smoothing = smoothing self.reset() def reset(self): self.ref_len = 0 self....
def get_bag_of_words(cmd): cmd = clean_anonymize_command(cmd) tokens = cmd.strip().split() return tokens
class TestBasicConv(): def test_init(self): layers = [5] units = 5 model = BasicConv(layers, units) def test_fill(self): pass def test_unfill(self): pass def test_forward(self): pass
def save_checkpoint(its, model_state, optim_state, logdir): last_model = os.path.join(logdir, 'last.model') last_optim = os.path.join(logdir, 'last.optim') last_config = os.path.join(logdir, 'last.config') opt = {'its': its} torch.save(model_state, last_model) torch.save(optim_state, last_optim)...
def create_parsers(): return PipelineCommon([(ProcessorTokenizerNltkEn(), ['text'], {0: 'tokens'}), (ProcessorSentenceSplitter(), ['tokens'], {0: 'sentences'})]) return ppl
def dump_table(table: Table) -> None: with open(((DATA_ROOT / table.dataset) / f'{table.version}.table.pkl'), 'wb') as f: pickle.dump(table, f, protocol=PKL_PROTO)
class ValidateSpans(object): def __init__(self, system, duplicate='error', crossing='warn', nested='ignore'): self.system = system self.duplicate = duplicate self.crossing = crossing self.nested = nested def __call__(self): OLD_VALIDATION = Document.VALIDATION Doc...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--input-scene', required=True, help='scene graph json file') parser.add_argument('--vocab-json', required=True, help='vocab file') parser.add_argument('--output-scene', required=True, help='output file') args = parser.parse_args() ...
def error(alpha, n): k = len(alpha) pvals = dirichlet(alpha) counts = multinomial(n, pvals) h0 = sp_entropy(pvals) (h, std) = ndd.entropy(counts, k=k, return_std=True) return (((h - h0) / h0), (std / h0))