code
stringlengths
101
5.91M
def generate_model_info(): op_stats = OpStats() tensor_stats = TensorStats() all_ops = tf.get_default_graph().get_operations() op_stats.op_count = len(all_ops) for op in all_ops: if ('update_' in op.name): op_stats.update_op_count += 1 if (op.name.endswith('/read') or op....
def get_sources_from_local_dir(globs, base_path): return {Source.create(filename) for filename in iterate_all_python_files(base_path)}
def copy_dict(ori_dict: Union[(dict, Generator)]): generator = (ori_dict.items() if isinstance(ori_dict, dict) else ori_dict) copied_dict = dict() for (key, param) in generator: copied_dict[key] = param return copied_dict
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-dataset', help='name of dataset;', type=str, choices=DATASETS, required=True) parser.add_argument('-model', help='name of model;', type=str, required=True) parser.add_argument('--num-rounds', help='number of rounds to simulate;',...
class RandomGaussianBlur(object): def __call__(self, sample): img = sample['image'] mask = sample['label'] if (random.random() < 0.5): img = img.filter(ImageFilter.GaussianBlur(radius=random.random())) return {'image': img, 'label': mask}
class PriorBox(object): def __init__(self, cfg): super(PriorBox, self).__init__() self.image_size = cfg['min_dim'] self.num_priors = len(cfg['aspect_ratios']) self.variance = (cfg['variance'] or [0.1]) self.feature_maps = cfg['feature_maps'] self.min_sizes = cfg['min_...
class CNN_Net(nn.Module): def __init__(self, device=None): super(CNN_Net, self).__init__() self.conv1 = nn.Conv2d(1, 64, 3, 1) self.conv2 = nn.Conv2d(64, 16, 7, 1) self.fc1 = nn.Linear(((4 * 4) * 16), 200) self.fc2 = nn.Linear(200, 10) def forward(self, x): x = x....
class Identity(torch.nn.Module): def __init__(self): super().__init__() def forward(self, *args): if (len(args) == 1): return args[0] else: return args
class IGate(Gate): def __init__(self, label=None): super().__init__('i', 1, [], label=label) def _define(self): definition = [] q = QuantumRegister(1, 'q') rule = [(U3Gate(pi, 0, pi), [q[0]], [])] for inst in rule: definition.append(inst) self.definiti...
class SFT_Net_torch(nn.Module): def __init__(self): super(SFT_Net_torch, self).__init__() self.conv0 = nn.Conv2d(3, 64, 3, 1, 1) sft_branch = [] for i in range(16): sft_branch.append(ResBlock_SFT_torch()) sft_branch.append(SFTLayer_torch()) sft_branch.appe...
class Lamb(torch.optim.Optimizer): def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, adam=False): if (not (0.0 <= lr)): raise ValueError('Invalid learning rate: {}'.format(lr)) if (not (0.0 <= eps)): raise ValueError('Invalid epsilon value: {...
class GroupedIterator(object): def __init__(self, iterable, chunk_size): self._len = int(math.ceil((len(iterable) / float(chunk_size)))) self.offset = int(math.ceil((getattr(iterable, 'count', 0) / float(chunk_size)))) self.itr = iterable self.chunk_size = chunk_size def __len__(...
class LitModel(pl.LightningModule): def __init__(self, opt): super().__init__() self.opt = opt self.args = args self.model = CLIPScore(use_grammar=opt.use_grammar, joint_out=opt.joint_out) for p in self.model.clip_model.vision_model.parameters(): p.requires_grad =...
class Flatten(nn.Module): def __init__(self): super(Flatten, self).__init__() def forward(self, x): x = x.view(x.size(0), (- 1)) return x
class ShmDataset(IterableDataset): def __init__(self, shm_context): self.shm_context = shm_context def __iter__(self): worker_info = torch.utils.data.get_worker_info() worker_id = (0 if (worker_info is None) else worker_info.id) while True: data = self.shm_context.get...
class NearRewardConfig(RewardConfig): def __init__(self, coeff): self.coeff = coeff def create_reward_shaper(self): return NearRewardShaper(self.coeff)
def test_faso_error_checks(): with pytest.raises(ValueError): FASO(FASO(RMSProp(0.01))) with pytest.raises(ValueError): FASO(RMSProp(0.01), mcse_threshold=0) with pytest.raises(ValueError): FASO(RMSProp(0.01), W_min=0) with pytest.raises(ValueError): FASO(RMSProp(0.01), k...
def test_locallygrouped_self_attention_module(): LSA = LocallyGroupedSelfAttention(embed_dims=32, window_size=3) outs = LSA(torch.randn(1, 3136, 32), (56, 56)) assert (outs.shape == torch.Size([1, 3136, 32]))
def predictor_exptrsonpath_set(exptrs): from phcpy.phcpy2c3 import py2c_set_value_of_continuation_parameter as set return set(17, exptrs)
class TestInferenceDropout(unittest.TestCase): def setUp(self): (self.task, self.parser) = get_dummy_task_and_parser() TransformerModel.add_args(self.parser) self.args = self.parser.parse_args([]) self.args.encoder_layers = 2 self.args.decoder_layers = 1 def test_sets_inf...
def test_abs(args, device_id, pt, step): device = ('cpu' if (args.visible_gpus == '-1') else 'cuda') if (pt != ''): test_from = pt else: test_from = args.test_from logger.info(('Loading checkpoint from %s' % test_from)) checkpoint = torch.load(test_from, map_location=(lambda storage,...
def GetCifar10(): if (not os.path.isdir('data/')): os.system('mkdir data/') if (not os.path.exists('data/cifar10.zip')): os.system('wget -P data/') os.chdir('./data') os.system('unzip -u cifar10.zip') os.chdir('..')
def _test(): import torch pretrained = False models = [resattnet56, resattnet92, resattnet128, resattnet164, resattnet200, resattnet236, resattnet452] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.forma...
class MAMuJoCo(): def __init__(self, scenario): env_config = get_env_config(scenario) self._environment = gymnasium_robotics.mamujoco_v0.parallel_env(**env_config) self.info_spec = {'state': self._environment.state()} def reset(self): (observations, info) = self._environment.rese...
class ValueFunction(nn.Module): def __init__(self, horizon, transition_dim, cond_dim, dim=32, dim_mults=(1, 2, 4, 8), out_dim=1): super().__init__() dims = [transition_dim, *map((lambda m: (dim * m)), dim_mults)] in_out = list(zip(dims[:(- 1)], dims[1:])) time_dim = dim self....
class FakeTokyo(FakeBackend): def __init__(self): cmap = [[0, 1], [0, 5], [1, 0], [1, 2], [1, 6], [2, 1], [2, 3], [2, 6], [3, 2], [3, 8], [3, 9], [4, 8], [4, 9], [5, 0], [5, 6], [5, 10], [5, 11], [6, 1], [6, 2], [6, 5], [6, 7], [6, 10], [6, 11], [7, 1], [7, 6], [7, 8], [7, 12], [7, 13], [8, 3], [8, 4], [8, ...
class CombineDBs(data.Dataset): NUM_CLASSES = 21 def __init__(self, dataloaders, excluded=None): self.dataloaders = dataloaders self.excluded = excluded self.im_ids = [] for dl in dataloaders: for elem in dl.im_ids: if (elem not in self.im_ids): ...
class QuestionAnsweringTrainer(Trainer): def __init__(self, *args, eval_examples=None, post_process_function=None, **kwargs): super().__init__(*args, **kwargs) self.eval_examples = eval_examples self.post_process_function = post_process_function def evaluate(self, eval_dataset=None, eval...
def generate_timestep_weights(args, num_timesteps): weights = torch.ones(num_timesteps) num_to_bias = int((args.timestep_bias_portion * num_timesteps)) if (args.timestep_bias_strategy == 'later'): bias_indices = slice((- num_to_bias), None) elif (args.timestep_bias_strategy == 'earlier'): ...
_module() class VarifocalLoss(nn.Module): def __init__(self, use_sigmoid=True, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', loss_weight=1.0): super(VarifocalLoss, self).__init__() assert (use_sigmoid is True), 'Only sigmoid varifocal loss supported now.' assert (alpha >= 0.0) ...
class Exrop(): def __init__(self, binary, input, job, ropchain, bad_chars): self.binary = binary self.input = input self.job = job self.logger = job.logger self.ropchain = ropchain self.bad_chars = bad_chars def run(self, timeout): from os import environ, ...
def resnet18(pretrained=False, **kwargs): model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: pretrained_dict = model_zoo.load_url(model_urls['resnet18']) model_dict = model.state_dict() pretrained_dict = {k: v for (k, v) in pretrained_dict.items() if (k in model_dict)} ...
def ResNet50(output_stride, BatchNorm, pretrained_url=None): model = ResNet(Bottleneck, [3, 4, 6, 3], output_stride, BatchNorm, pretrained_url) return model
def get_dataset_with_opts(opts_dic, mode): dataset_opts = opts_dic['{}_dataset'.format(mode)] if isinstance(dataset_opts, list): used_datasets = [] dataset_info = [] for dataset_part_opts in dataset_opts: dataset_name = dataset_part_opts['type'] if (dataset_name i...
def get_arg_sets(arg_dict): arg_sets = [{}] for (arg, vals) in arg_dict.items(): prev_arg_sets = arg_sets arg_sets = [] if isinstance(vals, list): for val in vals: for prev_arg_set in prev_arg_sets: arg_set = copy.copy(prev_arg_set) ...
class SmoothL1(Loss): def __init__(self): self.loss = nn.SmoothL1Loss() def __call__(self, logits, targets, **kwargs): return self.loss(logits, targets)
def print_final_results(history): print_string = '\nFinal Results: ' for (name, value) in history.items(): if ('.' in name): n_split = name.split('.') name = ((n_split[1].title() + ' ') + n_split[0]) if ('acc' in name): val_str = '{:.1f}%'.format((value * 100)...
def change_transform_origin(transform, center): center = np.array(center) return np.linalg.multi_dot([translation(center), transform, translation((- center))])
def _multi_instance_helper(model, recv_queue, send_queue, next_idx): from bigdl.nano.pytorch import InferenceOptimizer with InferenceOptimizer.get_context(model): while True: try: args = recv_queue.get() if isinstance(args, DataLoader): dat...
def fliplr(img): inv_idx = torch.arange((img.size(3) - 1), (- 1), (- 1)).long() img_flip = img.index_select(3, inv_idx) return img_flip
def main(): boolean = (lambda x: bool(['False', 'True'].index(x))) parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=None) parser.add_argument('--area', nargs=2, type=int, default=(64, 64)) parser.add_argument('--view', type=int, nargs=2, default=(9, 9)) parser.a...
def compute_aff(x: Tensor, similarity: str='cosine') -> Tensor: if (similarity == 'cosine'): x = torch.mm(x, x.t()) elif (similarity == 'euclidean'): x = x.unsqueeze(0) x = torch.cdist(x, x, p=2) x = x.squeeze(0) x = (- x) else: raise NotImplementedError(f'Inc...
class Prop_Gerund_Verbs(object): def __init__(self, sentence_objs): self.sentence_objs = sentence_objs def handle(self): (tot_num_gerunds, tot_num_verbs) = (0, 0) for so in self.sentence_objs: tot_num_gerunds += num_gerund_verbs(so.stanza_doc) tot_num_verbs += so....
def get_processed_dataset(key): path = os.path.join(SOURCE_DATASET_DIR, paths[key]) processed = preprocess_functions[key](path) return processed
def MLP(channels): return Sequential(*[Sequential(Linear(channels[(i - 1)], channels[i]), SiLU()) for i in range(1, len(channels))])
_model def gluon_resnet50_v1s(pretrained=False, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 4, 6, 3], stem_width=64, stem_type='deep', **kwargs) return _create_resnet('gluon_resnet50_v1s', pretrained, **model_args)
def leaky_relu(input_, leakiness=0.2): assert (leakiness <= 1) return tf.maximum(input_, (leakiness * input_))
def get_dummy_databunch() -> ImageDataBunch: path = Path('./dummy/') return get_colorize_data(sz=1, bs=1, crappy_path=path, good_path=path, keep_pct=0.001)
class ModerateCNNCeleba(nn.Module): def __init__(self): super(ModerateCNNCeleba, self).__init__() self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(...
class AlignLinear(torch.nn.Module): def __init__(self, config, vocab, max_len_token): super(AlignLinear, self).__init__() self.config = config self.vocab = vocab self.max_len_token = max_len_token self.need_flatten = True self.EMB = EMB((vocab.size + 1), config.embedd...
class Turtlebot(Roomba): def __init__(self): super(Turtlebot, self).__init__() def start(self, tty='/dev/ttyUSB0', baudrate=57600): super(Turtlebot, self).start(tty, baudrate) self.sci.add_opcodes(CREATE_OPCODES) def control(self): logging.info('sending control opcodes.') ...
class NVDM(object): def __init__(self, vocab_size, n_hidden, n_topic, n_sample, learning_rate, batch_size, non_linearity): self.vocab_size = vocab_size self.n_hidden = n_hidden self.n_topic = n_topic self.n_sample = n_sample self.non_linearity = non_linearity self.lea...
class DiseasesLPDataset(): def __init__(self, name, val_prop, test_prop, normalize_adj, normalize_feats): self.path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', name) (G, features) = load_data(self.path, name, val_prop, test_prop, normalize_adj, normalize_feats) self.num_fea...
class QuestionProcessor(): def __init__(self, max_words=50): self.max_words = max_words def __call__(self, question): return self.pre_question(question) def pre_question(self, question): question = re.sub('([.!\\"()*#:;~])', '', question.lower()) question = question.rstrip(' ...
def parse_args(): parser = argparse.ArgumentParser(description='\nCompute metrics for trackers using MOTChallenge ground-truth data.\nFiles\n-----\nAll file content, ground truth and test files, have to comply with the\nformat described in \nMilan, Anton, et al. \n"Mot16: A benchmark for multi-object tracking." \na...
def robust_loss(net, epsilon, X, y, size_average=True, device_ids=None, parallel=False, **kwargs): if parallel: f = nn.DataParallel(RobustBounds(net, epsilon, **kwargs))(X, y) else: f = RobustBounds(net, epsilon, **kwargs)(X, y) err = (f.max(1)[1] != y) if size_average: err = (er...
def get_configs_from_pipeline_file(): pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() with tf.gfile.GFile(FLAGS.pipeline_config_path, 'r') as f: text_format.Merge(f.read(), pipeline_config) model_config = pipeline_config.model if FLAGS.eval_training_data: eval_config = pipeline_...
def pix2pix_generator(net, num_outputs, blocks=None, upsample_method='nn_upsample_conv', is_training=False): end_points = {} blocks = (blocks or _default_generator_blocks()) input_size = net.get_shape().as_list() (height, width) = (input_size[1], input_size[2]) if (height != width): raise Va...
class convnet32(): def __init__(self, model_params, nkerns=[1, 8, 4, 2], ckern=128, filter_sizes=[5, 5, 5, 5, 4]): (self.num_hid, num_dims, num_class, self.batch_size, self.num_channels) = model_params self.D = int(np.sqrt((num_dims / self.num_channels))) numpy_rng = np.random.RandomState(12...
class HubertModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class Code2VecModelBase(abc.ABC): def __init__(self, config: Config): self.config = config self.config.verify() self._log_creating_model() self._init_num_of_examples() self._log_model_configuration() self.vocabs = Code2VecVocabs(config) self.vocabs.target_voca...
class Keypoints(): COCO_NAMES = ['nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle'] COCO_CONNECTIVITY = [[16, 14], [14, 12], [17, 1...
def forward_gen(): I = torch.FloatTensor(3).normal_() def forward(): return net(I) return forward
class MegaConfig(PretrainedConfig): model_type = 'mega' def __init__(self, vocab_size=30522, hidden_size=128, num_hidden_layers=4, intermediate_size=256, ema_projection_size=16, bidirectional=True, shared_representation_size=64, use_chunking=False, chunk_size=(- 1), truncation=None, normalize_before_mega=True, ...
class RandomTransform(): def __init__(self, seed=None, p=1.0, intensity=0.5): self.p = p self.intensity = intensity self.random = random.Random() if (seed is not None): self.seed = seed self.random.seed(seed) self.last_tran = None def get_last_tran...
class ModelsClassTest(unittest.TestCase): def setUpClass(cls): cls.setup = yaml.load(open(os.path.join('tests', 'data', 'config.yml'), 'r')) cls.weights_path = {'generator': os.path.join(cls.setup['weights_dir'], 'test_gen_weights.hdf5'), 'discriminator': os.path.join(cls.setup['weights_dir'], 'test...
def load_target_item_embedding(item_ebd_path): item_embedding = np.load(item_ebd_path) return item_embedding
class LPoly(): def __init__(self, coefs, dmin=0): self.coefs = numpy.array(coefs) if (len(self.coefs) == 0): self.dmin = dmin self.iszero = True self.coefs = [0] else: assert (len(self.coefs.shape) == 1), self.coefs self.dmin = dmin...
class conv2DBatchNorm(nn.Module): def __init__(self, in_channels, n_filters, k_size, stride, padding, bias=True, dilation=1, with_bn=True): super(conv2DBatchNorm, self).__init__() if (dilation > 1): conv_mod = nn.Conv2d(int(in_channels), int(n_filters), kernel_size=k_size, padding=paddin...
def featureL2Norm(feature): epsilon = 1e-06 norm = torch.pow((torch.sum(torch.pow(feature, 2), 1) + epsilon), 0.5).unsqueeze(1).expand_as(feature) return torch.div(feature, norm)
class RepVGGBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', avg_pool=False, se_block=False, activation=nn.ReLU()): super().__init__() self.groups = groups self.stride = stride self.kernel_si...
def onclick(event, df): clicked_index = event.ind fig = plt.gca() if (None not in clicked_index): output_folders = df['EvaluationModel'].unique() nfolders = len(output_folders) while (len(fig.texts) > (nfolders + (np.math.factorial(nfolders) / (np.math.factorial(2) * np.math.factoria...
class TrainLoop(object): def __init__(self, cfg, model, data_iter, optimizer, save_dir, device): self.cfg = cfg self.model = model self.data_iter = data_iter self.optimizer = optimizer self.save_dir = save_dir self.device = device def train(self, get_loss, model_f...
def test_Beyond1Std(white_noise): a = FeatureSpace(featureList=['Beyond1Std']) a = a.calculateFeature(white_noise) assert ((a.result(method='array') >= 0.3) and (a.result(method='array') <= 0.4))
_on_pypy .parametrize('cls_name', ['PickleableWithDict', 'PickleableWithDictNew']) def test_roundtrip_with_dict(cls_name): cls = getattr(m, cls_name) p = cls('test_value') p.extra = 15 p.dynamic = 'Attribute' data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) p2 = pickle.loads(data) assert (p2....
def weight_norm(module, weights=None, dim=0): WeightNorm.apply(module, weights, dim) return module
def get_frame_count(filepath): if (filepath is not None): video = cv2.VideoCapture(filepath) frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) video.release() if (frame_count > 100): frame_count = 100 return gr.update(maximum=frame_count) else: re...
_incremental_state class WaitSegMultiheadAttention(nn.Module): def __init__(self, embed_dim, num_heads, kdim=None, vdim=None, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, self_attention=False, encoder_decoder_attention=False, q_noise=0.0, qn_block_size=8): super().__init__() self....
def train(train_queue, model, criterion, optimizer): objs = utils.AvgrageMeter() top1 = utils.AvgrageMeter() top5 = utils.AvgrageMeter() batch_time = utils.AvgrageMeter() model.train() for (step, (input, target)) in enumerate(train_queue): target = target.cuda(non_blocking=True) ...
def tokenizer(sentence: str) -> List[str]: return [stem(token) for token in simple_preprocess(sentence) if (token not in STOPWORDS)]
_registry(pattern_type='InsertBF16Node') class InsertBF16Node(Pattern): def __call__(self, model): def fp32_to_bf16(fp32_np): assert (fp32_np.dtype == np.float32) int32_np = fp32_np.view(dtype=np.int32) int32_np = (int32_np >> 16) bf16_np = int32_np.astype(np....
def popluate_word_id_from_token(token, word_to_id): list_of_ids = [] word = token.split()[0].strip() if (word not in word_to_id): word = '**UNK**' word_one_hot_vec = np.zeros(len(word_to_id)) word_id = word_to_id[word] word_one_hot_vec[word_id] = 1.0 list_of_ids.append(word_id) a...
def attack(tensor, net, eps=0.001, n_iter=50): new_tensor = tensor.detach().clone() orig_prediction = net(tensor).argmax() print(f'Original prediction: {orig_prediction.item()}') for i in range(n_iter): net.zero_grad() grad = compute_gradient(func, new_tensor, net=net, target=orig_predic...
def parse_args(): parser = argparse.ArgumentParser(description='Make csv submission file for Kaggle') parser.add_argument('--testpkl-path', type=str) parser.add_argument('--dcalphas-path', type=str) parser.add_argument('--psis-path', type=str) parser.add_argument('--phis-path', type=str) parser....
class LeNet(nn.Module): def __init__(self): super(LeNet, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(256, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): out =...
def get_identity_preconditioner(): def init_fn(_): return IdentityPreconditionerState() def update_preconditioner_fn(*args, **kwargs): return IdentityPreconditionerState() def multiply_by_m_inv_fn(vec, _): return vec def multiply_by_m_sqrt_fn(vec, _): return vec def m...
class LeNet(nn.Module): def __init__(self, **kwargs): super(LeNet, self).__init__() self.num_of_datasets = kwargs.get('num_of_datasets', 1) self.num_of_classes = kwargs.get('num_of_classes', 10) self.ds_idx = 0 self.l1 = nn.Conv2d(3, 20, kernel_size=5, padding=1) self...
def main(argv=None): parser = argparse.ArgumentParser('Training', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('solution', type=str, choices=('linear', 'MLP', 'invariant')) parser.add_argument('log_dir', type=str, help='Logging folder') parser.add_argument('--checkpoint', ...
class Encoder(nn.Module): def __init__(self): super(Encoder, self).__init__() self.E = nn.Sequential(nn.Conv2d(3, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(0.1, True), nn.Conv2d(64, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(0.1, True), nn.Conv2d(64, 128, k...
def test_digits_cosine_greedi_nn(): model1 = FacilityLocationSelection(100) model2 = GraphCutSelection(100) model = MixtureSelection(100, [model1, model2], [1.0, 0.3], metric='cosine', optimizer='greedi', optimizer_kwds={'optimizer1': 'naive', 'optimizer2': 'naive'}, random_state=0) model.fit(X_digits) ...
class Schaffer(FloatProblem): def __init__(self): super(Schaffer, self).__init__() self.obj_directions = [self.MINIMIZE, self.MINIMIZE] self.obj_labels = ['f(x)', 'f(y)'] self.lower_bound = [(- 1000)] self.upper_bound = [1000] def number_of_objectives(self) -> int: ...
def triplet_semihard_loss(labels, embeddings, margin=1.0): lshape = array_ops.shape(labels) assert (lshape.shape == 1) labels = array_ops.reshape(labels, [lshape[0], 1]) pdist_matrix = pairwise_distance(embeddings, squared=True) adjacency = math_ops.equal(labels, array_ops.transpose(labels)) adj...
def circuit_drawer(circuit, scale=0.7, filename=None, style=None, output=None, interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): image = None config = user_config.get_config() default_output = 'text' if config: default_output = config.get('circuit_drawer...
def get_command(scaffolding, command_path): (path, _, command_name) = command_path.rpartition('.') if (path not in scaffolding): raise KeyError(('Ingredient for command "%s" not found.' % command_path)) if (command_name in scaffolding[path].commands): return scaffolding[path].commands[comman...
def get_prediction_challenge_split(split: str, dataroot: str='/data/sets/nuscenes') -> List[str]: if (split not in {'mini_train', 'mini_val', 'train', 'train_val', 'val'}): raise ValueError('split must be one of (mini_train, mini_val, train, train_val, val)') if (split == 'train_val'): split_nam...
def plot_uncertainty(df, kind, threshold=None, title=None): try: from skmisc.loess import loess except ImportError: raise ImportError('Uncertainty plots with loess estimation require scikit-misc, which is not installed.') if (kind == 'tile'): df = df.sample(n=1000) (f, axes) = pl...
def BFS(block_map, current_member: List[int]): combinations = [] if (current_member == []): cur_max = (- 1) else: cur_max = max(current_member) combinations.append(current_member) member_set = set(current_member) l = len(block_map) for i in range((cur_max + 1), l): ...
class Reinforcement(object): def __init__(self, generator, predictor, get_reward): super(Reinforcement, self).__init__() self.generator = generator self.predictor = predictor self.get_reward = get_reward def policy_gradient(self, data, n_batch=10, gamma=0.97, std_smiles=False, gr...
def set_quad_double_target_system(pols, vrblvl=0): if (vrblvl > 0): print('in set_quad_double_target_system, with pols :') for pol in pols: print(pol) nvr = number_of_symbols(pols, vrblvl) set_quad_double_system(nvr, pols, vrblvl) phc = get_phcfun() aaa = pointer(c_int32(...
class TFMPNetModel(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)