code
stringlengths
101
5.91M
def init(module, weight_init, bias_init, gain=1): weight_init(module.weight.data, gain=gain) bias_init(module.bias.data) return module
class DictionaryLearningBenchmark(Transformer, Estimator, Benchmark): param_names = ['fit_algorithm', 'n_jobs'] params = (['lars', 'cd'], Benchmark.n_jobs_vals) def setup_cache(self): super().setup_cache() def make_data(self, params): return _olivetti_faces_dataset() def make_estimat...
class LabelField(Field[torch.Tensor]): _already_warned_namespaces: Set[str] = set() def __init__(self, label: Union[(str, int)], label_namespace: str='labels', skip_indexing: bool=False) -> None: self.label = label self._label_namespace = label_namespace self._label_id = None sel...
def plot_sensitivity(ax, alg, exp, alphas, sp, tp, performance, stderr, exp_attrs): global plot_alpha lbl = f'{alg}_{tp}' ax.set_xscale('log', basex=2) if (alg == 'ETD'): color = 'red' elif (alg == 'ETDLB'): color = 'grey' plot_alpha -= 0.1 else: color = 'black' ...
def check_attr_ints_type(attr, node): if (attr.type != AttributeProto.INTS): raise ValueError(f'Only INTS is supported for {attr.name} in {node.op_type} op_type')
def pt_acfg(**kwargs): bn_cfg = (kwargs.pop('bn_cfg', None) or get_bn_args_pt()) return {'pad_type': 'LIKE', 'bn_cfg': bn_cfg, **kwargs}
class TFBertForNextSentencePrediction(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def convert_examples_to_features(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training, cls_token_at_end=False, cls_token='[CLS]', sep_token='[SEP]', pad_token=0, sequence_a_segment_id=0, sequence_b_segment_id=1, cls_token_segment_id=0, pad_token_segment_id=0, mask_padding_with_zero=True): ...
def resnet101(pretrained=False, progress=True, device='cpu', **kwargs): return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, device, **kwargs)
class InterfaceMagic(): def all_iter(cls): try: import sage.interfaces.all except ImportError: return for (name, obj) in sage.interfaces.all.__dict__.items(): if isinstance(obj, (sage.interfaces.interface.Interface, sage.misc.lazy_import.LazyImport)): ...
class VGG16(): def conv2d(self, x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(self, x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def conv_layer(self, x, kernel_dim, input_dim, output_dim, trainable, activated...
class FeedForward(nn.Module): def __init__(self, dim, mult=4, dropout=0.0): super().__init__() self.net = nn.Sequential(nn.Linear(dim, ((dim * mult) * 2)), GEGLU(), nn.Linear((dim * mult), dim), nn.Dropout(dropout)) def forward(self, x): return self.net(x)
class TransFuse_S_adapt(nn.Module): def __init__(self, num_classes=1, drop_rate=0.2, normal_init=True, pretrained=False, pretrained_folder='/bigdata/siyiplace/data/skin_lesion', num_domains=4): super(TransFuse_S_adapt, self).__init__() self.resnet = resnet34() if pretrained: self...
def get_optimizer(opt_dict, model_params): opt_dict = opt_dict.copy() optimizer = _get_optimizer_instance(opt_dict) opt_dict.pop('name') optimizer = optimizer(model_params, **opt_dict) return (optimizer, None)
def get_config_section(filenames, section): parser = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation()) parser.optionxform = str files = parser.read(filenames) if (len(files) == 0): raise ValueError('Config files not found: {}'.format(filenames)) dict_session = dic...
def R_inc_mtrx_transform(x, y, u, v, p, q): cosIby2 = T.sqrt(((1 - (p * p)) - (q * q))) x1 = (((1 - ((2 * p) * p)) * x) + (((2 * p) * q) * y)) y1 = ((((2 * p) * q) * x) + ((1 - ((2 * q) * q)) * y)) z1 = (((((- 2) * p) * cosIby2) * x) + (((2 * q) * cosIby2) * y)) u1 = (((1 - ((2 * p) * p)) * u) + (((...
def get_children(node: Union[(FASTNode, List[FASTNode])], child_type: str) -> List[FASTNode]: ...
class TestFloat_power(object): def test_type_conversion(self): arg_type = '?bhilBHILefdgFDG' res_type = 'ddddddddddddgDDG' for (dtin, dtout) in zip(arg_type, res_type): msg = ('dtin: %s, dtout: %s' % (dtin, dtout)) arg = np.ones(1, dtype=dtin) res = np.flo...
class CDivTable(Module): def __init__(self): super(CDivTable, self).__init__() self.gradInput = [] def updateOutput(self, input): self.output.resize_as_(input[0]).copy_(input[0]) self.output.div_(input[1]) return self.output def updateGradInput(self, input, gradOutput...
class FPN(nn.Module): def __init__(self, in_channels_list, out_channels): super(FPN, self).__init__() leaky = 0 if (out_channels <= 64): leaky = 0.1 self.output1 = conv_bn1X1(in_channels_list[0], out_channels, stride=1, leaky=leaky) self.output2 = conv_bn1X1(in_ch...
def results2markdown(result_dict): table_data = [] is_multiple_results = False for (cfg_name, value) in result_dict.items(): name = cfg_name.replace('configs/', '') fps = value['fps'] ms_times_pre_image = value['ms_times_pre_image'] if isinstance(fps, list): is_mu...
def confidence(bootstraps, output_path, confidence_level=0.95): cb = ConfidenceGenerator(confidence_level=confidence_level) df = cb.generate_cis(bootstraps) df.to_csv(output_path, index=False)
class DetrModel(metaclass=DummyObject): _backends = ['timm', 'vision'] def __init__(self, *args, **kwargs): requires_backends(self, ['timm', 'vision'])
def test_unary_requires_root(unary_model): test_parse_transitions.test_unary_requires_root(unary_model)
class L1_Charbonnier_loss(torch.nn.Module): def __init__(self): super(L1_Charbonnier_loss, self).__init__() self.eps = 1e-06 def forward(self, X, Y): diff = torch.add(X, (- Y)) error = torch.sqrt(((diff * diff) + self.eps)) loss = torch.mean(error) return loss
class GoogleHomeListDeviceActions(VirtualFunctionTool): name = 'GoogleHomeListDeviceActions' summary = 'Retrieves a list of possible actions that can be performed on a specified smart home device.' parameters: List[ArgParameter] = [{'name': 'device_id', 'type': 'string', 'description': 'The unique identifie...
def equal(x, y, dtype=None): if (dtype is None): dtype = 'float32' if isinstance(x, torch.Tensor): x = x.numpy() if isinstance(y, torch.Tensor): y = y.numpy() out = np.equal(x, y).astype(dtype) return torch.tensor(out)
class MultiClicker(): def __init__(self, fig): self.cid = None self.points = [] def onclick(event): try: print(('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (event.button, event.x, event.y, event.xdata, event.ydata))) if (event.button == 3): ...
def bimap(first, second): return ({f: s for (f, s) in zip(first, second)}, {s: f for (f, s) in zip(first, second)})
def export_to_embedding_projector(lf): lf.load_checkpoint(get_checkpoint_path(args)) lf.export_to_embedding_projector()
def test_model(predictor: Predictor, hypotheses: Mapping[(str, str)], test_data: datasets.Dataset, result_file: Path, n_test_examples: Optional[int]): labels = test_data.features['label'] if (n_test_examples is not None): test_data = sample(test_data, seed=42, n_examples_per_label=n_test_examples) e...
def print_range(x): return (round(float(x.min()), 2), round(float(x.mean()), 2), round(float(x.max()), 2))
_start_docstrings('CamemBERT Model with a token classification head on top (a linear layer on top of\n the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. ', CAMEMBERT_START_DOCSTRING) class TFCamembertForTokenClassification(TFRobertaForTokenClassification): config_class = CamembertConfig
def yaml_to_cpp(reg_def_cpp, reg_def_yaml): reg_yaml = ordered_yaml_load(reg_def_yaml) gen_reg_def_cpp(reg_def_cpp, reg_yaml, reg_def_yaml)
def test_part_of_speech(): nlp = stanfordnlp.Pipeline(**{'processors': 'tokenize,pos', 'models_dir': TEST_MODELS_DIR, 'lang': 'en'}) doc = nlp(EN_DOC) assert (EN_DOC_GOLD == '\n\n'.join([sent.tokens_string() for sent in doc.sentences]))
def simple_KD_train(xloader, teacher, network, criterion, scheduler, optimizer, optim_config, extra_info, print_freq, logger): (loss, acc1, acc5) = procedure(xloader, teacher, network, criterion, scheduler, optimizer, 'train', optim_config, extra_info, print_freq, logger) return (loss, acc1, acc5)
_model def efficientnet_lite2(pretrained=False, **kwargs): model = _gen_efficientnet_lite('efficientnet_lite2', channel_multiplier=1.1, depth_multiplier=1.2, pretrained=pretrained, **kwargs) return model
def run_experiment(method_call=None, batch_tasks=None, exp_prefix='experiment', exp_name=None, log_dir=None, script='garage.experiment.experiment_wrapper', python_command='python', dry=False, env=None, variant=None, force_cpu=False, pre_commands=None, **kwargs): if ((method_call is None) and (batch_tasks is None)):...
_scheme(prefixes='pavi://') def load_from_pavi(filename, map_location=None): assert filename.startswith('pavi://'), f'Expected filename startswith `pavi://`, but get {filename}' model_path = filename[7:] try: from pavi import modelcloud except ImportError: raise ImportError('Please insta...
def load_reference(path_to_reference): with open(path_to_reference, 'r') as f: qids_to_relevant_passageids = load_reference_from_stream(f) return qids_to_relevant_passageids
class EndEffectorPoseViaIK(ArmActionMode): def __init__(self, absolute_mode: bool=True, frame: str='world', collision_checking: bool=False): self._absolute_mode = absolute_mode self._frame = frame self._collision_checking = collision_checking if (frame not in ['world', 'end effector'...
class TFCTRLPreTrainedModel(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
class SetPartition(AbstractSetPartition, metaclass=InheritComparisonClasscallMetaclass): def __classcall_private__(cls, parts, check=True): P = SetPartitions() return P.element_class(P, parts, check=check) def __init__(self, parent, s, check=True): self._latex_options = {} Clonab...
class BayesianRegressionModel(PyroSviTrainMixin, PyroSampleMixin, BaseModelClass): def __init__(self, adata: AnnData, per_cell_weight=False): clear_param_store() super().__init__(adata) self.module = BayesianRegressionModule(in_features=adata.shape[1], out_features=1, per_cell_weight=per_cel...
.mlir def test_mlir_tasklet_float(): A = dace.ndarray((1,), dace.float32) B = dace.ndarray((1,), dace.float32) C = dace.ndarray((1,), dace.float32) A[:] = 5.5 B[:] = 2.2 C[:] = 15.15 mlir_tasklet_float(A, B, C) assert np.allclose(C[0], 7.7)
def _write_single_frame(im, fp, palette): im_out = _normalize_mode(im, True) for (k, v) in im_out.info.items(): im.encoderinfo.setdefault(k, v) im_out = _normalize_palette(im_out, palette, im.encoderinfo) for s in _get_global_header(im_out, im.encoderinfo): fp.write(s) flags = 0 ...
def train(train_loader, model, criterion, optimizer, epoch, args): batch_time = AverageMeter('Time', ':6.3f') data_time = AverageMeter('Data', ':6.3f') losses = AverageMeter('Loss', ':.4e') top1 = AverageMeter('', ':6.2f') top5 = AverageMeter('', ':6.2f') progress = ProgressMeter(len(train_loade...
def _format(val: Any, output_format: str='standard', errors: str='coarse') -> Any: val = str(val) result: Any = [] if (val in NULL_VALUES): return [np.nan] if (not validate_pl_regon(val)): if (errors == 'raise'): raise ValueError(f'Unable to parse value {val}') error_...
_display_as_base class _UFuncInputCastingError(_UFuncCastingError): def __init__(self, ufunc, casting, from_, to, i): super().__init__(ufunc, casting, from_, to) self.in_i = i def __str__(self): i_str = ('{} '.format(self.in_i) if (self.ufunc.nin != 1) else '') return 'Cannot cas...
class TFXLMRobertaForQuestionAnswering(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
def apply_succ(prob_letters): return [prob_letters[:(- 1)], (prob_letters[:(- 2)] + [prob_letters[(- 1)]])]
class PairMarginMiner(BaseTupleMiner): def __init__(self, pos_margin=0.2, neg_margin=0.8, **kwargs): super().__init__(**kwargs) self.pos_margin = pos_margin self.neg_margin = neg_margin self.add_to_recordable_attributes(list_of_names=['pos_margin', 'neg_margin'], is_stat=False) ...
def get_transforms(config: ((str | A.Compose) | None)=None, image_size: ((int | tuple) | None)=None, to_tensor: bool=True) -> A.Compose: warnings.warn(DeprecationWarning('The function anomalib.pre_processing.pre_process.get_transforms is deprecated and will be removed in a future release. Please use anomalib.data.u...
def main(args): utils.import_user_module(args) os.makedirs(args.destdir, exist_ok=True) logger.addHandler(logging.FileHandler(filename=os.path.join(args.destdir, 'preprocess.log'))) logger.info(args) task = tasks.get_task(args.task) def train_path(lang): return '{}{}'.format(args.trainpr...
class Shell(): def __init__(self, name: str, exe: str): self.name = name self.exe = exe
def truncated_normal_mean(r0, v0, zmin, zmax): assert (zmin < zmax) s0 = np.sqrt(v0) ymin = ((zmin - r0) / s0) ymax = ((zmax - r0) / s0) if (zmax == (+ np.inf)): g1 = G1_inf(ymin, (+ 1)) elif (zmin == (- np.inf)): g1 = G1_inf(ymax, (- 1)) else: g1 = G1(ymin, ymax) ...
class attach_to_forward_backward_class(Function): def forward(ctx, tensor, f, b, tag): ctx.f = f ctx.b = b ctx.tag = tag return f(tensor, tag) def backward(ctx, grad_output): return (ctx.b(grad_output, ctx.tag), None, None, None)
class EnumCase(AstNode): def __init__(self, name, value_str): super(EnumCase, self).__init__() self.name = name self.value_str = value_str self.type_ref = TypeRef(name) def __repr__(self): return '{} = {},'.format(self.name, self.value_str) def __eq__(self, other): ...
class DET_evaluator(Evaluator): def __init__(self): self.type = 'DET' def eval(self): arguments = [] for (seq, res, gt) in zip(self.sequences, self.tsfiles, self.gtfiles): arguments.append({'metricObject': DETMetrics(seq), 'args': {'gtDataDir': os.path.join(self.datadir, seq)...
def get_score(submission_folder='../env'): submission_path = os.path.join(submission_folder, 'submission.csv') submission = pd.read_csv(submission_path, index_col=0) test_dataset = datasets.CIFAR10(root='./data', train=False, download=True) acc = 0 for (idx, (x, y)) in enumerate(test_dataset): ...
(_reducers.All) class All(JAXReducer): name: Final = 'all' preferred_dtype: Final = np.bool_ needs_position: Final = False def from_kernel_reducer(cls, reducer: Reducer) -> Self: assert isinstance(reducer, _reducers.All) return cls() def _return_dtype(cls, given_dtype): retur...
def _maybe_apply(apply_fn, inputs, rng, apply_prob): should_apply = (jax.random.uniform(rng, shape=()) <= apply_prob) return jax.lax.cond(should_apply, inputs, apply_fn, inputs, (lambda x: x))
class TFCommonDecoderLayer(BaseModule): def __init__(self, d_model=512, d_inner=1024, n_head=8, d_k=64, d_v=64, ifmask=True, dropout=0.1, qkv_bias=False, act_cfg=dict(type='mmcv.GELU')): super().__init__() self.attn = Mask_MultiHeadAttention(n_head, d_model, d_k, d_v, qkv_bias=qkv_bias, dropout=drop...
def arnonA_long_mono_to_string(mono, latex=False, p=2): if latex: sq = '\\text{Sq}' else: sq = 'Sq' if (len(mono) == 0): return '1' else: string = '' for (m, k) in mono: for i in range(m, (k - 1), (- 1)): string = ((((string + sq) + '^{...
class MockAlgo(): sampler_cls = LocalSampler def __init__(self, env, policy, max_path_length, n_exploration_traj, meta_eval): self.env = env self.policy = policy self.max_path_length = max_path_length self.n_exploration_traj = n_exploration_traj self.meta_eval = meta_eval...
class AnswerAwareTokenizer(): def __init__(self, total_maxlen, bert_model='google/electra-base-discriminator'): self.total_maxlen = total_maxlen self.tok = ElectraTokenizerFast.from_pretrained(bert_model) def process(self, questions, passages, all_answers=None, mask=None): return Tokeniz...
def test_prediction_codes(tmp_path: pathlib.Path): time_horizon = TimeHorizon(datetime.timedelta(days=0), datetime.timedelta(days=10)) labeler = CodeLabeler(['2'], time_horizon, prediction_codes=['4', '5']) events_with_labels: EventsWithLabels = [(event((2015, 1, 3), 2, None), 'skip'), (event((2015, 1, 3), ...
class RCHWNonSimplyLacedElement(RCNonSimplyLacedElement): def check(self): for partition in self: for (i, vac_num) in enumerate(partition.vacancy_numbers): if (vac_num < partition.rigging[i]): raise ValueError('rigging can be at most the vacancy number') d...
class JHU(NWPU): def __init__(self, root, list_path, num_samples=None, num_classes=1, multi_scale=True, flip=True, ignore_label=(- 1), base_size=2048, crop_size=(512, 1024), min_unit=(32, 32), center_crop_test=False, downsample_rate=1, scale_factor=(0.5, (1 / 0.5)), mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0....
def reduction_B(input): channel_axis = (- 1) r1 = conv_block(input, 192, 1, 1) r1 = conv_block(r1, 192, 3, 3, subsample=(2, 2), border_mode='valid') r2 = conv_block(input, 256, 1, 1) r2 = conv_block(r2, 256, 1, 7) r2 = conv_block(r2, 320, 7, 1) r2 = conv_block(r2, 320, 3, 3, subsample=(2, 2)...
def _spvec2pow(specvec): fftl2 = (len(specvec) - 1) fftl = (fftl2 * 2) power = (specvec[0] + specvec[fftl2]) for k in range(1, fftl2): power += (2.0 * specvec[k]) power /= fftl return power
def walsh_matrix(m0): m = int(m0) if (m == 1): return matrix(GF(2), 1, 2, [0, 1]) if (m > 1): row2 = [x.list() for x in walsh_matrix((m - 1)).augment(walsh_matrix((m - 1))).rows()] return matrix(GF(2), m, (2 ** m), ([(([0] * (2 ** (m - 1))) + ([1] * (2 ** (m - 1))))] + row2)) rai...
def evaluate_from_args(args: argparse.Namespace) -> Dict[(str, Any)]: logging.getLogger('allennlp.common.params').disabled = True logging.getLogger('allennlp.nn.initializers').disabled = True logging.getLogger('allennlp.modules.token_embedders.embedding').setLevel(logging.INFO) archive = load_archive(ar...
class TestEnforceClusterIdUniqueness(unittest.TestCase): def test_list_of_list(self): cluster_ids = [['a', 'b', 'c'], ['b', 'c', 'd', 'e']] new_cluster_ids = utils.enforce_cluster_id_uniqueness(cluster_ids) self.assertEqual(2, len(new_cluster_ids)) self.assertEqual(3, len(new_cluster...
def get_debug_args(budget=30, detector_type=AAD_IFOREST): return ['--resultsdir=./temp', '--randseed=42', '--reruns=1', ('--detector_type=%d' % detector_type), ('--forest_score_type=%d' % (IFOR_SCORE_TYPE_NEG_PATH_LEN if (detector_type == AAD_IFOREST) else (HST_LOG_SCORE_TYPE if (detector_type == AAD_HSTREES) else ...
def get_node_corrs_objects_ids(node_corrs, objects_ids, batch_offset): node_corrs_objects_ids = [] for node_corr in node_corrs: node_corrs_objects_ids.append((objects_ids[(node_corr[0] + batch_offset)], objects_ids[(node_corr[1] + batch_offset)])) return node_corrs_objects_ids
def fully_connected(inputs, num_outputs, scope, use_xavier=True, stddev=0.001, weight_decay=None, activation_fn=tf.nn.relu, bn=False, bn_decay=None, is_training=None): with tf.variable_scope(scope) as sc: num_input_units = inputs.get_shape()[(- 1)].value weights = _variable_with_weight_decay('weight...
def test_trace(): import tracemalloc tracemalloc.start(10) time1 = tracemalloc.take_snapshot() from pycorrector import Corrector m = Corrector() c = m.correct('') print(c) time2 = tracemalloc.take_snapshot() stats = time2.compare_to(time1, 'lineno') print(('*' * 32)) for stat...
def conv_2d_layer(name, in_tensor, in_ch, out_ch, k_h, k_w, s_h, s_w, stddev=0.01, initial_w=None, padding='SAME'): with tf.variable_scope(name): W = tf.get_variable('W', [k_h, k_w, in_ch, out_ch], initializer=tf.contrib.layers.xavier_initializer(True)) conv = tf.nn.conv2d(in_tensor, W, strides=[1, ...
.parametrize('knn_methods', knn_methods) def test_desknn_proba(knn_methods): (pool_classifiers, X_dsel, y_dsel, X_test, y_test) = setup_classifiers() desknn = DESKNN(pool_classifiers, knn_classifier=knn_methods, voting='soft') desknn.fit(X_dsel, y_dsel) probas = desknn.predict_proba(X_test) expected...
def build_and_print_matrices(v, strat): treated = BooleSet() v = list(v) rows = 0 polys_in_mat = [] if (not v): return while v: rows = (rows + 1) p = v[0] v = v[1:] for m in list(p.terms()): m = Monomial(m) if (m not in BooleSet(tre...
def multi_gpu_test_net_on_dataset(args, num_images): binary_dir = os.getcwd() binary = os.path.join(binary_dir, (args.test_net_file + '.py')) assert os.path.exists(binary), "Binary '{}' not found".format(binary) outputs = subprocess_utils.process_in_parallel('detection', num_images, binary, cfg, cfg.CKP...
def test_case11(): url = (brokerIp + '/ngsi-ld/v1/entities/') headers = {'Content-Type': 'application/json'} r = requests.post(url, data=json.dumps(ld_data.subdata14b), headers=headers) print(r.content) print(r.status_code) assert (r.status_code == 400)
def _cubic_smooth_coeff(signal, lamb): (rho, omega) = _coeff_smooth(lamb) cs = ((1 - ((2 * rho) * cos(omega))) + (rho * rho)) K = len(signal) yp = zeros((K,), signal.dtype.char) k = arange(K) yp[0] = ((_hc(0, cs, rho, omega) * signal[0]) + add.reduce((_hc((k + 1), cs, rho, omega) * signal))) ...
def Fossum_calc(TP, FP, FN, TN): try: n = (((TP + FP) + FN) + TN) part1 = ((TP - 0.5) ** 2) part2 = ((TP + FP) * (TP + FN)) return ((n * part1) / part2) except Exception: return 'None'
_datapipe('map') class MapperIterDataPipe(IterDataPipe[T_co]): datapipe: IterDataPipe fn: Callable def __init__(self, datapipe: IterDataPipe, fn: Callable, input_col=None, output_col=None, *, fn_args: Optional[Tuple]=None, fn_kwargs: Optional[Dict]=None, nesting_level: int=0) -> None: super().__init...
class MapPermutationTuner(cutout_tuner.CutoutTuner): def __init__(self, sdfg: SDFG, measurement: dtypes.InstrumentationType=dtypes.InstrumentationType.Timer) -> None: super().__init__(task='MapPermutation', sdfg=sdfg) self.instrument = measurement def cutouts(self) -> Generator[(Tuple[(dace.SDFG...
class SimpleConvAbstractModel(ProteinModel): config_class = SimpleConvConfig base_model_prefix = 'simple_conv'
class EWCParamsComputer(ASR): def on_fit_start(self): (self.params, self.fisher) = ({}, {}) self.num_samples = 0 def fit_batch(self, batch): outputs = self.compute_forward(batch, sb.Stage.TRAIN) loss = self.compute_objectives(outputs, batch, sb.Stage.TRAIN) with self.no_s...
def validate_es_nif(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]: if isinstance(df, (pd.Series, dd.Series)): return df.apply(nif.is_valid) elif isinstance(df, (pd.DataFrame, dd.DataFrame)): if (column != ''): ...
_properties class MapDimShuffle(transformation.SingleStateTransformation): map_entry = transformation.PatternNode(nodes.MapEntry) parameters = ListProperty(element_type=str, default=None, desc='Desired order of map parameters') def expressions(cls): return [sdutil.node_path_graph(cls.map_entry)] ...
class DeformConvFunction(Function): def forward(ctx, input, offset, weight, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, im2col_step=64): if ((input is not None) and (input.dim() != 4)): raise ValueError('Expected 4D tensor as input, got {}D tensor instead.'.format(input.dim()...
class SawyerSoccerV1Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'ball_pos': obs[3:6], 'goal_pos': obs[9:], 'unused_info': obs[6:9]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos': np.arange(3), 'grab_effort': 3})...
def get_train_test_splits(df: pd.DataFrame, metadata: pd.DataFrame, n: int) -> (pd.DataFrame, pd.DataFrame, np.ndarray): train_df = df[metadata.trainval] test_df = df[(~ metadata.trainval)] test_labels = metadata[(~ metadata.trainval)].anomaly.values return (train_df.tail(n), test_df.head(n), test_label...
class foursquare_nyc(DatasetBuilder): def prepare(self, f_names): fs = [f for f in f_names if ('TSMC2014_NYC.txt' in f)] raw_data = pandas.read_csv(fs[0], sep=self.dataset_info['sep'], encoding=self.dataset_info['encoding'], header=None) tdf_dataset = skmob.TrajDataFrame(raw_data, latitude=4...
def get_reward_processor(config): if (config.type == 'time_independent'): return get_raw_reward elif (config.type == 'time_discounted'): return get_original_reward elif (config.type == 'click_checkboxes_hard'): return get_click_checkboxes_hard else: raise ValueError('{} n...
class Document(): def __init__(self, publication_date, sentences): self.publication_date = publication_date self.sentences = tuple(sentences) def from_xml(publication_date, text, nlp): logger = logging.getLogger(__name__) publication_date = datetime.datetime.strptime(publication_...
def run_benchmark(): global parameters timing_entries = [] with tf.Graph().as_default(): image_size = 224 if (FLAGS.data_format == 'NCHW'): image_shape = [FLAGS.batch_size, 3, (image_size + 3), (image_size + 3)] else: image_shape = [FLAGS.batch_size, (image_si...
.parametrize('seed', [311]) def test_graph_clear_buffer(seed): np.random.seed(313) rng = np.random.RandomState(seed) x = nn.Variable([2, 3, 4, 4]) t = nn.Variable([2, 1]) x.d = rng.randn(*x.shape) t.d = rng.randint(0, 5, size=t.shape) nn.set_default_context(nn.Context()) nn.clear_paramet...
class PythonScriptTaskExecution(TaskExecution): def __init__(self, model_script_path: str, tmp_dir: Union[(str, None)]=None): TaskExecution.__init__(self, tmp_dir) if (not os.path.isfile(model_script_path)): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), model_script_pa...