code
stringlengths
101
5.91M
def test_last_flag() -> None: x = [1, 2, 3, 4, 5] i = 0 for (is_last, value) in last_flag(x): if (i == (len(x) - 1)): assert is_last else: assert (not is_last) assert (value == x[i]) i += 1
class OptimRegime(Regime): def __init__(self, model, regime, defaults={}, filter=None, use_float_copy=False, log=True): super(OptimRegime, self).__init__(regime, defaults) if (filter is not None): model = FilterParameters(model, **filter) if use_float_copy: model = Mo...
class PegasusTokenizer(metaclass=DummyObject): _backends = ['sentencepiece'] def __init__(self, *args, **kwargs): requires_backends(self, ['sentencepiece'])
def q_int(n, q=None): if (n not in ZZ): raise ValueError(f'{n} must be an integer') if (q is None): q = ZZ['q'].gen() if (n == 0): return parent(q)(0) if (n > 0): return sum(((q ** i) for i in range(n))) return ((- (q ** n)) * sum(((q ** i) for i in range((- n)))))
class FunctionAiryAiGeneral(BuiltinFunction): def __init__(self): BuiltinFunction.__init__(self, 'airy_ai', nargs=2, latex_name='\\operatorname{Ai}') def _derivative_(self, alpha, x, diff_param=None): if (diff_param == 0): raise NotImplementedError('cannot differentiate airy_ai in th...
def make_np(x): if isinstance(x, np.ndarray): return x if isinstance(x, six.string_types): return _prepare_caffe2(x) if np.isscalar(x): return np.array([x]) if isinstance(x, torch.Tensor): return _prepare_pytorch(x) raise NotImplementedError('Got {}, but numpy array, ...
def predict(net, data): net.eval() outputs = net(data) probs = net.vote preds = torch.where((outputs > 0.5), torch.ones(outputs.shape).cuda(), torch.zeros(outputs.shape).cuda()) return (preds.cpu().detach().numpy(), probs.cpu().detach().numpy())
def test_error(): global _quiet qsave = _quiet (saveerr, sys.stderr) = (sys.stderr, StringIO()) try: _quiet = False error('hello, world') finally: _quiet = qsave (saveerr, sys.stderr) = (sys.stderr, saveerr) print(type(saveerr)) assert ('hello, world\n' in sav...
def _make_efficientnet_backbone(effnet): pretrained = nn.Module() pretrained.layer1 = nn.Sequential(effnet.conv_stem, effnet.bn1, effnet.act1, *effnet.blocks[0:2]) pretrained.layer2 = nn.Sequential(*effnet.blocks[2:3]) pretrained.layer3 = nn.Sequential(*effnet.blocks[3:5]) pretrained.layer4 = nn.Seq...
class CoNLL(Transform): fields = ['ID', 'FORM', 'LEMMA', 'CPOS', 'POS', 'FEATS', 'HEAD', 'DEPREL', 'PHEAD', 'PDEPREL'] def __init__(self, ID=None, FORM=None, LEMMA=None, CPOS=None, POS=None, FEATS=None, HEAD=None, DEPREL=None, PHEAD=None, PDEPREL=None): super().__init__() self.ID = ID se...
def _get_all_bases(class_or_name: Union[(str, Type)]) -> List[str]: if isinstance(class_or_name, str): return [class_or_name] return [base.__name__ for base in class_or_name.__mro__]
def compact_array(array, depth=(- 1)): data_items = [] def recurse(array, depth): if (isinstance(array, Content) and (array.__len__() > 0)): if (depth != 0): for it in range(array.__len__()): recurse(array.__getitem__(it), (depth - 1)) else: ...
.parametrize('seed', [313, 314]) .parametrize('op', ['+', '-', '*', '/', '**']) .parametrize('shape', [(2, 3, 4), (0,)]) def test_ndarray_arithmetic_scalar_ops(seed, op, shape): rng = np.random.RandomState(seed) vx = nn.NdArray.from_numpy_array(rng.randn(*shape).astype(np.float32)) a = rng.randn() if ((...
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--corpus-dir', required=True, help='Location of pre-training text files.') parser.add_argument('--vocab-file', required=True, help='Location of vocabulary file.') parser.add_argument('--output-dir', required=True, hel...
def simple_total_col_ion_coefficients(simple_index_nlte_ion): simple_col_ion_coefficients = [0., 0.] return pd.DataFrame(simple_col_ion_coefficients, index=simple_index_nlte_ion)
class ArgScopeTest(tf.test.TestCase): def testEmptyArgScope(self): with self.test_session(): self.assertEqual(scopes._current_arg_scope(), {}) def testCurrentArgScope(self): func1_kwargs = {'a': 1, 'b': None, 'c': [1]} key_op = (func1.__module__, func1.__name__) curre...
def _read_array(f, typecode, array_desc): if (typecode in [1, 3, 4, 5, 6, 9, 13, 14, 15]): if (typecode == 1): nbytes = _read_int32(f) if (nbytes != array_desc['nbytes']): warnings.warn('Not able to verify number of bytes from header') array = np.frombuffer(f....
def infer_aliasing(node: nodes.NestedSDFG, sdfg: SDFG, state: SDFGState) -> None: data_to_conn: Dict[(str, Set[str])] = defaultdict(set) def _infer_aliased_connectors(get_edges: Callable[([nodes.NestedSDFG], List[Edge[Memlet]])], get_conn: Callable[([Edge[Memlet]], str)], outgoing: bool): for e in get_e...
class OnnxifiTest(TestCase): ('Need ONNXIFI backend support') def test_relu_graph(self): batch_size = 1 X = np.random.randn(batch_size, 1, 3, 2).astype(np.float32) graph_def = make_graph([make_node('Relu', ['X'], ['Y'])], name='test', inputs=[make_tensor_value_info('X', onnx.TensorProto....
def shrink_simplicial_complex(K): L = K._contractible_subcomplex() return SimplicialSet_finite(K).quotient(L)
class ControlSuite(): def __init__(self, task_name='humanoid_run'): self.task_name = task_name self._uint8_features = set([]) self._environment = None if (task_name == 'fish_swim'): self._domain_name = 'fish' self._task_name = 'swim' self._shapes =...
_lr_scheduler('reduce_lr_on_plateau') class ReduceLROnPlateau(FairseqLRScheduler): def __init__(self, args, optimizer): super().__init__(args, optimizer) if (len(args.lr) > 1): raise ValueError('Cannot use a fixed learning rate schedule with reduce_lr_on_plateau. Consider --lr-scheduler=...
def brightness(image, factor): factor = (((factor / MAX_LEVEL) * 1.8) + 0.1) image = Image.fromarray(image) image = ImageEnhance.Brightness(image).enhance(factor) return np.asarray(image)
class M2M100ForConditionalGeneration(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class ConvReLU3d(torch.nn.Sequential): def __init__(self, conv, relu): assert ((type(conv) == Conv3d) and (type(relu) == ReLU)), 'Incorrect types for input modules{}{}'.format(type(conv), type(relu)) super(ConvReLU3d, self).__init__(conv, relu)
def test_recovery_custom_io(tmpdir): from speechbrain.utils.checkpoints import register_checkpoint_hooks from speechbrain.utils.checkpoints import mark_as_saver from speechbrain.utils.checkpoints import mark_as_loader from speechbrain.utils.checkpoints import Checkpointer _checkpoint_hooks class...
def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration from scipy._build_utils.system_info import get_info from scipy._build_utils import numpy_nodepr_api config = Configuration('dsolve', parent_package, top_path) config.add_data_dir('tests') lap...
class Gpt2Embeddings(StateDictSerializationMixin, eqx.Module): Vocab: Axis = eqx.static_field() config: Gpt2Config = eqx.static_field() token_embeddings: NamedArray position_embeddings: NamedArray dropout: hnn.Dropout def init(Vocab: Axis, config: Gpt2Config, *, key) -> 'Gpt2Embeddings': ...
class Func_assoc_legendre_Q(BuiltinFunction): def __init__(self): BuiltinFunction.__init__(self, 'gen_legendre_Q', nargs=3, latex_name='Q', conversions={'maxima': 'assoc_legendre_q', 'mathematica': 'LegendreQ', 'maple': 'LegendreQ'}) def _eval_(self, n, m, x, *args, **kwds): ret = self._eval_spe...
def _catalog_shared_params(module, memo=None, prefix=''): if (memo is None): first_call = True memo = {} else: first_call = False for (name, param) in module._parameters.items(): param_prefix = ((prefix + ('.' if prefix else '')) + name) if (param not in memo): ...
def f(f_string): frame = inspect.stack()[1][0] return Formatter(frame.f_globals, frame.f_locals).format(f_string)
def to_pd_datetime(timestamp): if isinstance(timestamp, pd.DatetimeIndex): return timestamp elif isinstance(timestamp, (int, float)): return pd.to_datetime(int((timestamp * 1000)), unit='ms') elif (isinstance(timestamp, Iterable) and all((isinstance(t, (int, float)) for t in timestamp))): ...
def create_train_val_dataloader(opt, logger): (train_loader, val_loader) = (None, None) for (phase, dataset_opt) in opt['datasets'].items(): if (phase == 'train'): dataset_enlarge_ratio = dataset_opt.get('dataset_enlarge_ratio', 1) train_set = build_dataset(dataset_opt) ...
_get_mesh_stats(mode='generate') def regular_mesh(n: int=10, length_x: float=1.0, length_y: float=1.0, length_z: Optional[float]=None, diagonal: Literal[('left', 'right', 'left/right', 'right/left', 'crossed')]='right', comm: Optional[MPI.Comm]=None) -> _typing.MeshTuple: if (length_x <= 0.0): raise _except...
def test_custom_constraints_from_object(tmpdir): data = pd.DataFrame({'primary_key': ['user-000', 'user-001', 'user-002'], 'pii_col': ['223 Williams Rd', '75 Waltham St', '77 Mass Ave'], 'numerical_col': [2, 3, 4], 'categorical_col': ['a', 'b', 'a']}) metadata = SingleTableMetadata() metadata.detect_from_da...
def set_random_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
def register_emitter(name, emitter_class): if (name in _EMITTER_TYPES): raise RegistrationError(f"Emitter '{name}' is already registered") _EMITTER_TYPES[name] = emitter_class
def get_num_inputs(o): args = 0 for a in o['arguments']: if (a['type'] == 'TensorList'): return '*' elif value_has_tensors(a): args += 1 return str(args)
class Pct(nn.Module): def __init__(self, output_channels=40, dropout=0.5): super(Pct, self).__init__() self.conv1 = nn.Conv1d(3, 64, kernel_size=1, bias=False) self.conv2 = nn.Conv1d(64, 64, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm1d(64) self.bn2 = nn.BatchNorm1d(64...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = bn(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(plane...
def build_gpr(data: Dataset, search_space: Optional[SearchSpace]=None, kernel_priors: bool=True, likelihood_variance: Optional[float]=None, trainable_likelihood: bool=False, kernel: Optional[gpflow.kernels.Kernel]=None) -> GPR: (empirical_mean, empirical_variance, _) = _get_data_stats(data) if ((kernel is None)...
class ReadValuesNested(object): def test_access_top_fields(self): h = np.array(self._buffer, dtype=self._descr) if (not self.multiple_rows): assert_((h.shape == ())) assert_equal(h['x'], np.array(self._buffer[0], dtype='i4')) assert_equal(h['y'], np.array(self._bu...
def findfactor(cp1, cp2): size = 2 if ((len(cp1) % 2) != 0): raise error('Strings should be even-sized') if (len(cp1) != len(cp2)): raise error('Samples should be same size') sample_count = _sample_count(cp1, size) sum_ri_2 = _sum2(cp2, cp2, sample_count) sum_aij_ri = _sum2(cp1, ...
def process(spans, length, use_fine_grained=False): def compare(a, b): if (a[0] > b[0]): return 1 elif (a[0] == b[0]): if (a[1] > b[1]): return (- 1) else: return 1 else: return (- 1) def compare2(a, b): ...
def get_network_fn(name, num_classes, weight_decay=0.0, is_training=False): if (name not in networks_map): raise ValueError(('Name of network unknown %s' % name)) arg_scope = arg_scopes_map[name](weight_decay=weight_decay) func = networks_map[name] (func) def network_fn(images): with...
(base=10) def plot_semilogx(funcs, *args, **kwds): return plot(funcs, *args, scale='semilogx', **kwds)
def matrix_from_pose_msg(pose): t = matrix_from_point_msg(pose.position) r = matrix_from_quaternion_msg(pose.orientation) return concatenate_matrices(t, r)
def load_tr_te_data(csv_file_tr, csv_file_te, n_items): tp_tr = pd.read_csv(csv_file_tr) tp_te = pd.read_csv(csv_file_te) start_idx = min(tp_tr['uid'].min(), tp_te['uid'].min()) end_idx = max(tp_tr['uid'].max(), tp_te['uid'].max()) (rows_tr, cols_tr) = ((tp_tr['uid'] - start_idx), tp_tr['sid']) ...
('/start', method='POST') def start_analyzer(): req = json.loads(request.body.read().decode('utf-8')) measurer.start(req)
class ClassificationMetric(EvaluateInstancesMetric): def __init__(self, delimiter: Optional[str]=None): self.delimiter = delimiter def is_multi_label(self) -> bool: return bool(self.delimiter) def evaluate_instances(self, request_states: List[RequestState]) -> List[Stat]: y_pred: Lis...
class MaskedLMTrainer(Trainer): def __init__(self, model: torch.nn.Module, **kwargs): super().__init__(model, **kwargs) def forward_batch(self, batch): batch_inputs = {'input_ids': batch.mlm_tok_ids, 'attention_mask': (~ batch.mlm_att_mask).long(), 'labels': batch.mlm_lab_ids} if hasattr...
class Texfunc(): def __init__(self, ttype=0, center=(0, 0, 0), rotate=(0, 0, 0), scale=(1, 1, 1), imagefile=''): self._ttype = ttype (x, y, z) = center self._center = (float(x), float(y), float(z)) (x, y, z) = rotate self._rotate = (float(x), float(y), float(z)) (x, y...
def test_ambiguous_schedule(): def add(a: (dace.float32[(10, 10)] dace.StorageType.GPU_Global), b: dace.float32[(10, 10)]): return (a + b) with pytest.raises(InvalidSDFGNodeError): sdfg = add.to_sdfg() set_default_schedule_and_storage_types(sdfg, None)
class TestReaderWithLimit(TestCase): def test_runtime_threads(self): ws = workspace.C.Workspace() session = LocalSession(ws) src_ds = make_source_dataset(ws) totals = ([None] * 3) def proc(rec): with ops.task_init(): counter1 = ops.CreateCounter([]...
def _pil_interp(method): if (method == 'bicubic'): return Image.BICUBIC elif (method == 'lanczos'): return Image.LANCZOS elif (method == 'hamming'): return Image.HAMMING else: return Image.BILINEAR
class BertGFPBrightness(flexs.Landscape): gfp_wt_sequence = 'MSKGEELFTGVVPILVELDGDVNGHKFSVSGEGEGDATYGKLTLKFICTTGKLPVPWPTLVTTLSYGVQCFSRYPDHMKQHDFFKSAMPEGYVQERTIFFKDDGNYKTRAEVKFEGDTLVNRIELKGIDFKEDGNILGHKLEYNYNSHNVYIMADKQKNGIKVNFKIRHNIEDGSVQLADHYQQNTPIGDGPVLLPDNHYLSTQSALSKDPNEKRDHMVLLEFVTAAGITHGMDELYK' starts = {'...
def pair_process(item, strict_one=True): if hasattr(item, '__iter__'): for i in item: if (i != item[0]): if strict_one: raise ValueError('number in item {} must be the same'.format(item)) else: print('IMPORTANT WARNING: numb...
class TopicDrivenMaskedLM(RobertaPreTrainedModel): def __init__(self, config): super().__init__(config) if config.is_decoder: logger.warning('If you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.') self.roberta = RobertaMod...
def test_set_tokens(doc): ner_contents = ['O', 'ARTIFACT', 'ARTIFACT', 'O', 'CAT'] doc.set(fields=NER, contents=ner_contents, to_token=True) result = doc.get(NER, from_token=True) assert (result == ner_contents)
class ResNet(nn.Module): def __init__(self, in_channels, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d ...
class NetParameter(_message.Message): __metaclass__ = _reflection.GeneratedProtocolMessageType DESCRIPTOR = _NETPARAMETER
class Block(nn.Module): def __init__(self, in_planes, out_planes, stride=1): super(Block, self).__init__() self.conv1 = nn.Conv2d(in_planes, in_planes, kernel_size=3, stride=stride, padding=1, groups=in_planes, bias=False) self.bn1 = nn.BatchNorm2d(in_planes) self.conv2 = nn.Conv2d(i...
class UnionFind(): def __init__(self, elements) -> None: self.ids = {e: e for e in elements} def add_element(self, e): if (e in self.ids): return False self.ids.update({e: e}) return True def find(self, e): prev = e curr = self.ids[e] while...
def create_einsum(state: dace.SDFGState, map_ranges, code, inputs, outputs=None, wcr_outputs=None): outputs = (outputs or []) wcr_outputs = (wcr_outputs or []) inpdict = {access_node.data: access_node for (access_node, _) in inputs} outdict = {access_node.data: access_node for (access_node, _) in (outpu...
class LeanPreprocessedIf(LeanPreprocessedWithAsserts): expr_a: Expression expr_b: Expression cond_eq: bool jump_instr: Optional[LeanPreprocessedJumpToLabelInstruction] def get_exprs(self) -> List[Expression]: return [self.expr_a, self.expr_b]
class TFModelUtilsTest(unittest.TestCase): .skipif(('tensorflow' not in sys.modules), reason='requires TensorFlow') def test_model_from_pretrained(self): pass
def get_halluci(sess): halluci_step_idx = [] for step in sess: if ('step_id' in step): step_id = step['step_id'] numbers = re.findall('\\d+', step_id) (sess_idx, step_idx) = numbers if ('observation' in step): if ('Invalid action!' in step[...
class LegacyMatrixGroupElement(MatrixGroupElement_gap): def __setstate__(self, state): parent = state[0] m = state[1]['_MatrixGroupElement__mat'] m = parent.matrix_space()(m) self.__init__(parent, m, check=False)
def start_virtual_display() -> None: try: from pyvirtualdisplay.display import Display display = Display() display.start() except ImportError as e: raise ImportError('pyvirtualdisplay is not installed.\n$ pip install pyvirtualdisplay') from e
def load_table(dataset: str, version: str, overwrite: bool=False) -> Table: table_path = ((DATA_ROOT / dataset) / f'{version}.table.pkl') if ((not overwrite) and table_path.is_file()): L.info('table exists, load...') with open(table_path, 'rb') as f: table = pickle.load(f) L....
class DLoss(nn.Module): def __init__(self): super(DLoss, self).__init__() def forward(self, real_vloss, fake_vloss): d_loss = (torch.mean(torch.relu((1.0 - real_vloss))) + torch.mean(torch.relu((1.0 + fake_vloss)))) return d_loss
class SequentialDropout(nn.Module): def __init__(self, p=0.5): super(SequentialDropout, self).__init__() if ((p < 0) or (p > 1)): raise ValueError('dropout probability has to be between 0 and 1, but got {}'.format(p)) self.p = p self.restart = True def _make_noise(sel...
def output_as_str(string_like): if ((string_like is not None) and (type(string_like) != str)): return string_like.decode('utf-8') else: return string_like
class SegmentCorpus(Job): def __init__(self, corpus_path, num_segments, use_fullname=False): self.set_vis_name('Segment Corpus') self.corpus_path = corpus_path self.num_segments = num_segments self.use_fullname = use_fullname self.segment_files = [self.output_path(('segments....
def motorcycle_data(): df = pd.read_csv('./data/motor.csv', index_col=0) (X, Y) = (df['times'].values.reshape((- 1), 1), df['accel'].values.reshape((- 1), 1)) Y = ((Y - Y.mean()) / Y.std()) X /= X.max() return (X, Y)
def entity_coverage_with_bert_ner(split): dataset = load_json(f'outputs/WebQSP.{split}.expr.json') linking_result = load_json(f'stagg/webqsp_{split}-entities.json') counted = 0 all_first_covered = [] topk_choices = [1, 3, 5, 10] for (i, data) in enumerate(dataset): skip = True fo...
class AlexNet(Network): def setup(self): self.feed('data').conv(11, 11, 96, 4, 4, padding='VALID', name='conv1').lrn(2, 2e-05, 0.75, name='norm1').max_pool(3, 3, 2, 2, padding='VALID', name='pool1').conv(5, 5, 256, 1, 1, group=2, name='conv2').lrn(2, 2e-05, 0.75, name='norm2').max_pool(3, 3, 2, 2, padding='...
def conv1d_layer_sentence_representation(sent_wordembeddings): representation_from_filters = [] output_channel = 0 if (FLAGS.handle_filter_output == 'sum'): output_channel = FLAGS.sentembed_size else: output_channel = (FLAGS.sentembed_size / FLAGS.max_filter_length) if ((output_c...
def add_backward_desc(backward_sdfg: dace.SDFG, forward_sdfg: dace.SDFG, forward_desc: dt.Data, forward_name: str) -> str: backward_name = utils.find_str_not_in_set(forward_sdfg.arrays, (forward_name + '_grad')) new_desc = copy.deepcopy(forward_desc) new_desc.transient = False return backward_sdfg.add_d...
_module() class SegRecognizer(BaseRecognizer): def __init__(self, preprocessor=None, backbone=None, neck=None, head=None, loss=None, label_convertor=None, train_cfg=None, test_cfg=None, pretrained=None, init_cfg=None): super().__init__(init_cfg=init_cfg) assert (label_convertor is not None) ...
class HallLittlewood_p(HallLittlewood_generic): class Element(HallLittlewood_generic.Element): pass def __init__(self, hall_littlewood): HallLittlewood_generic.__init__(self, hall_littlewood) self._self_to_s_cache = p_to_s_cache self._s_to_self_cache = s_to_p_cache def _q_to_...
def _export_to_json(json_name, xs, xlabel, ys, ylabel, ys_std): json_path = os.path.join(_log_dir, 'auto', (json_name + '.json')) with open(json_path, 'w') as json_file: json.dump(dict(x=xs, y=ys.tolist(), y_min=(ys - ys_std).tolist(), y_max=(ys + ys_std).tolist(), xlabel=xlabel, ylabel=ylabel), json_fi...
class BernoulliRBM(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): _parameter_constraints: dict = {'n_components': [Interval(Integral, 1, None, closed='left')], 'learning_rate': [Interval(Real, 0, None, closed='neither')], 'batch_size': [Interval(Integral, 1, None, closed='left')], 'n_iter': [Int...
def best_linear_code_in_guava(n, k, F): from .linear_code import LinearCode GapPackage('guava', spkg='gap_packages').require() libgap.load_package('guava') C = libgap.BestKnownLinearCode(n, k, F) return LinearCode(C.GeneratorMat()._matrix_(F))
def parse_args(): argparser = argparse.ArgumentParser() argparser.add_argument('domain', help='path to domain pddl file') argparser.add_argument('task', help='path to task pddl file') argparser.add_argument('--relaxed', dest='generate_relaxed_task', action='store_true', help='output relaxed task (no del...
class DistributedTestDataSampler(Sampler): def __init__(self, data_source, batch_size, rank, world_size): data_len = len(data_source) all_indices = np.arange(data_len, dtype=int) split_indices = np.array_split(all_indices, world_size) num_batches = (((len(split_indices[0]) + batch_si...
class Configurable(): def from_config(cls, config, **kwargs): return cls._from_config(config, **kwargs) def _from_config(cls, config, **kwargs): return cls(**config, **kwargs) def get_config(self): return {self.get_kind(): self._get_config()} def get_kind(self): return ge...
class _Merge(Layer): def __init__(self, **kwargs): super(_Merge, self).__init__(**kwargs) self.supports_masking = True def _merge_function(self, inputs): raise NotImplementedError def _compute_elemwise_op_output_shape(self, shape1, shape2): if (None in [shape1, shape2]): ...
def get_repeats(csv_file): files = [] with open(csv_file, 'r') as csv_fp: csv_reader = csv.DictReader(csv_fp) for row in csv_reader: files.append(row['file2']) files.append(row['file3']) return files
def argmax(vals: T.Iterable[Scalar]) -> Scalar: return sum(((i * val) for (i, val) in enumerate(argmax_onehot(vals))))
class RandomActorPolicy(BaseActorPolicy): def __init__(self, low_bound, upper_bound): super(RandomActorPolicy, self).__init__(identifier='random_policy') self._low_bound = low_bound self._upper_bound = upper_bound return def act(self, obs): return np.random.uniform(self._...
def get_clientid(): config = configparser.ConfigParser() if host_uuid_path.exists(): config.read(os.path.expanduser(host_uuid_path)) id = uuid.UUID(int=uuid.getnode()).hex if ('client' not in config): config.add_section('client') config.set('client', 'anon_clientid', id) elif...
_module class SoftmaxFocalClassificationLoss(Loss): def __init__(self, gamma=2.0, alpha=0.25): self._alpha = alpha self._gamma = gamma def _compute_loss(self, prediction_tensor, target_tensor, weights, class_indices=None): weights = weights.unsqueeze(2) if (class_indices is not N...
def get_region_score(features, feature_columns, region_number, l2_reg, seed, prefix='region_', seq_mask_zero=True): region_logit = concat_func([get_linear_logit(features, feature_columns, seed=(seed + i), prefix=(prefix + str((i + 1))), l2_reg=l2_reg) for i in range(region_number)]) return Activation('softmax')...
def init_logger(args): log_file = os.path.join(args.log_dir, (args.name + '.log')) logging.basicConfig(format='%(asctime)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, filename=log_file, filemode='a+') console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = l...
def to_pretty_midi(music: 'Music') -> PrettyMIDI: midi = PrettyMIDI() (tempo_times, tempi) = ([0], [float(DEFAULT_TEMPO)]) for tempo in music.tempos: tempo_times.append(tempo.time) tempi.append(tempo.qpm) if (len(tempi) > 1): last_tempo = tempi[0] last_time = tempo_times[...
def get_human_normalized_score(entry): human_entries = find_all({'env-title': entry['env-title'], 'algo-title': 'Human', 'env-variant': entry['env-variant']}) random_entries = find_all({'env-title': entry['env-title'], 'algo-title': 'Random', 'env-variant': entry['env-variant']}) if (len(human_entries) > 1)...
class Quaternionr(MsgpackMixin): w_val = np.float32(0) x_val = np.float32(0) y_val = np.float32(0) z_val = np.float32(0) def __init__(self, x_val=np.float32(0), y_val=np.float32(0), z_val=np.float32(0), w_val=np.float32(1)): self.x_val = x_val self.y_val = y_val self.z_val = ...
def validate_network(val_loader, model): batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() global best_acc model.eval() criterion = nn.CrossEntropyLoss().cuda() with torch.no_grad(): end = time.perf_counter() for (i, (inp, tar...
class UnalignedDataset(BaseDataset): def modify_commandline_options(parser, is_train): return parser def initialize(self, opt): self.opt = opt self.root = opt.dataroot self.dir_A = os.path.join(opt.dataroot, (opt.phase + 'A')) self.dir_B = os.path.join(opt.dataroot, (opt....