code
stringlengths
101
5.91M
class _opener(object): def __init__(self, file_like): self.file_like = file_like def __enter__(self): return self.file_like def __exit__(self, *args): pass
class LambdaLayer(kbase.ZooKerasLayer): def __init__(self, input_vars, out_var, input_shape=None, **kwargs): super(LambdaLayer, self).__init__(None, input_vars, out_var, (list(input_shape) if input_shape else None), **kwargs)
def main(): parser = argparse.ArgumentParser(description='Convert keys in official pretrained segformer to MMSegmentation style.') parser.add_argument('src', help='src model path or url') parser.add_argument('dst', help='save path') args = parser.parse_args() checkpoint = CheckpointLoader.load_check...
def eval_directory(embs_dir: str, eval_script: str, output_dir: str): emb_list: List[str] = [os.path.join(embs_dir, f) for f in os.listdir(embs_dir) if os.path.isfile(os.path.join(embs_dir, f))] for emb in tqdm(emb_list, desc='Evaluating embeddings'): eval_embedding(eval_script=eval_script, embedding_pa...
def vgg_fc_layer(x, out_dim, var_list, apply_relu=True, name='fc'): in_dim = x.get_shape().as_list()[1] stdv = (1.0 / math.sqrt(in_dim)) with tf.variable_scope(name): w = tf.get_variable('weights', [in_dim, out_dim], tf.float32, initializer=tf.random_uniform_initializer((- stdv), stdv)) b = ...
def morgan_similarity(smiles_1: List[str], smiles_2: List[str], radius: int, sample_rate: float): similarities = [] num_pairs = (len(smiles_1) * len(smiles_2)) if (sample_rate < 1.0): sample_num_pairs = (sample_rate * num_pairs) sample_size = math.ceil(math.sqrt(sample_num_pairs)) sa...
def extract_losses(line): chunks = line.split('\t') total_loss = chunks[1].split(':')[1] iou_loss = chunks[2].split(':')[1] return (total_loss, iou_loss)
def main(): if (len(sys.argv) > 1): configFile = sys.argv[1] else: configFile = 'test_configuration' print('Configuration File = ', (configFile + '.txt')) config = ConfigParser() config.read((configFile + '.txt')) BUFFER_SIZE = config.getint('hyperparam', 'BUFFER_SIZE') BA...
class black_box_benchmarks(object): def __init__(self, shadow_train_performance, shadow_test_performance, target_train_performance, target_test_performance, num_classes): self.num_classes = num_classes (self.s_tr_outputs, self.s_tr_labels) = shadow_train_performance (self.s_te_outputs, self....
def sum_metric(tensor, name): sum_var = tf.compat.v1.Variable(initial_value=tf.zeros(shape=(), dtype=tensor.dtype), trainable=False, collections=[tf.compat.v1.GraphKeys.LOCAL_VARIABLES, tf.compat.v1.GraphKeys.METRIC_VARIABLES], name='{}_total'.format(name), aggregation=tf.VariableAggregation.SUM) update_op = tf...
class EnvBatch(object): def __init__(self, connectivity_dir, scan_data_dir=None, feat_db=None, batch_size=100): self.feat_db = feat_db self.image_w = 640 self.image_h = 480 self.vfov = 60 self.sims = [] for i in range(batch_size): sim = MatterSim.Simulator...
_task('denoising') class DenoisingTask(LegacyFairseqTask): def add_args(parser): parser.add_argument('data', help='path to data directory') parser.add_argument('--tokens-per-sample', default=512, type=int, help='max number of total tokens over all segments per sample for dataset') parser.add...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--dataset_root', default='data/3DMatch/rgbd') parser.add_argument('--out_root', default='data/3DMatch/rgbd_fragments/') parser.add_argument('--depth_scale', type=float, default=1000.0) parser.add_argument('--depth_trunc', type...
class colors(): RED = '\x1b[31;1m' GREEN = '\x1b[32;1m' YELLOW = '\x1b[33;1m' BLUE = '\x1b[34;1m' MAGENTA = '\x1b[35;1m' CYAN = '\x1b[36;1m' BOLD = '\x1b[1m' UNDERLINE = '\x1b[4m' ENDC = '\x1b[0m'
def replan(agent, destination, origin_map): agent.set_destination((destination.location.x, destination.location.y, destination.location.z)) plan_map = draw_route(agent, destination, origin_map) return plan_map
def word_tokenize(text, language='english'): if (sys.version_info[0] < 3): return [token for token in _treebank_word_tokenize(text)] else: return [token for token in _treebank_word_tokenize(text.decode('UTF-8'))]
def parse_paired_list_value(value): if re.match(MULTI_DEPS_PATTERN, value): return [(part.split(':', 1)[1], parse_int_value(part.split(':', 1)[0])) for part in value.split('|')] return parse_nullable_value(value)
class StringIndex(): def __init__(self, df: 'SparkDataFrame', col_name: str) -> None: cols = df.columns invalidInputError((len(cols) >= 2), 'StringIndex should have >= 2 columns: col_name, id and other columns') invalidInputError(('id' in cols), 'id should be a column of the DataFrame') ...
class EncModule(nn.Module): def __init__(self, in_channels, nclass, ncodes=32, se_loss=True, norm_layer=nn.BatchNorm2d, norm_kwargs=None): super(EncModule, self).__init__() self.se_loss = se_loss self.encoding = nn.Sequential(nn.Conv2d(in_channels, in_channels, 1, bias=False), norm_layer(in_...
def simpleTokenize_software(text): splitPunctText = splitEdgePunct_software(text) textLength = len(splitPunctText) bads = [] badSpans = [] for match in Protected.finditer(splitPunctText): if (match.start() != match.end()): bads.append([splitPunctText[match.start():match.end()]]) ...
def load_svhn(path_train, path_test): svhn_train = loadmat(path_train) svhn_test = loadmat(path_test) svhn_train_im = svhn_train['X'] svhn_train_im = svhn_train_im.transpose(3, 2, 0, 1).astype(np.float32) svhn_label = dense_to_one_hot(svhn_train['y']) svhn_test_im = svhn_test['X'] svhn_test_...
def angle_distance(theta_a: np.ndarray, theta_b: np.ndarray) -> float: diff = np.abs(np.arctan2(np.sin((theta_a - theta_b)), np.cos((theta_a - theta_b)))) return diff.mean()
def idletime(idletime, frequency): l = len(idletime) vgg19 = ([0] * l) for i in range(l): vgg19[i] = (((idletime[i] * frequency[i]) / 1530) / 29) fp = [] x = np.array([2, 3, 4, 5]) for i in range(1, len(vgg19)): fp.append((vgg19[i] - vgg19[0])) fp = np.array(fp) f1 = np.p...
def IS_FILE_NAME(token): list_test = file_rule.findall(token) if (len(list_test) > 0): return True return False
def get_spectrum_hdulist(HDUlist): data_in_hdu = False for extname in flux_HDU_names: if (extname in HDUlist): data = HDUlist[extname].data data_hdr = HDUlist[extname].header data_in_hdu = True if (not data_in_hdu): raise FormatError('Could not find Flux A...
def compute_additional_loss(result_index, row_width, row_height, widget_list, max_w_list, min_w_list, max_h_list, min_h_list, add_index=0): loss = 0 for i in range(len(result_index)): for j in range(len(result_index[i])): index = (result_index[i][j] + add_index) if (row_width[i][...
def reset_decola_cls_test(model, cls_path, num_classes): model.num_classes = num_classes model.detr.num_classes = num_classes model.detr.transformer.num_classes = num_classes if (type(cls_path) == str): print('Resetting zs_weight', cls_path) zs_weight = torch.tensor(np.load(cls_path), dt...
class CellPinCombArc(BBAStruct): from_pin: int delay: TimingValue = field(default_factory=TimingValue) def serialise_lists(self, context: str, bba: BBAWriter): pass def serialise(self, context: str, bba: BBAWriter): bba.u32(self.from_pin.index) self.delay.serialise(context, bba)
class TFGPT2PreTrainedModel(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class FMClassification(BaseFMClassifier): def __init__(self, n_iter=100, init_stdev=0.1, rank=8, random_state=123, l2_reg_w=0, l2_reg_V=0, l2_reg=None, step_size=0.1): super(FMClassification, self).__init__(n_iter=n_iter, init_stdev=init_stdev, rank=rank, random_state=random_state) if (l2_reg is not...
def fft2(inp, norm=None): s = inp.shape[(- 3):(- 1)] cond_norm = _unitary(norm) scaling = 1 if (cond_norm == 'ortho'): scaling = T.sqrt(s.prod().astype(inp.dtype)) return (fft2_op(inp, s) / scaling)
class Identity(torch.nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return x
def path_to_name(path): _file = path.split('/')[(- 1)] if (len(_file.split('.')) == 1): return _file else: return '.'.join(_file.split('.')[:(- 1)])
class _RCParallelOpFirstBound(): def __init__(self, discardNonchemical: bool, first: RCExpExp) -> None: self.discardNonchemical = discardNonchemical self.first = first def __mul__(self, second: RCExpExp) -> RCExpExp: return RCExpComposeParallel(rcExp(self.first), rcExp(second), self.disc...
def compute_context_embeddings(model, eval_dataset, opt): model.eval() eval_dataset.set_data_mode('context') context_eval_loader = DataLoader(eval_dataset, collate_fn=retrieval_collate, batch_size=opt.eval_ctx_bsz, num_workers=opt.num_workers, shuffle=False, pin_memory=opt.pin_memory) n_videos = len(eva...
class UNet_Attention(nn.Module): def __init__(self, input_dim=3, num_classes=1): super(UNet_Attention, self).__init__() self.input_dim = input_dim self.num_classes = num_classes n1 = 64 filters = [n1, (n1 * 2), (n1 * 4), (n1 * 8), (n1 * 16)] self.Maxpool1 = nn.MaxPool...
.parametrize('X_types,apply_to,error', [({}, ['duck'], True), ({'duck': 'B'}, ['duck'], False), ({}, ['continuous'], False), (None, ['continuous'], False), ({'continuous': 'A', 'cat': 'B'}, ['continuous', 'cat'], False), ({'continuous': 'A', 'cat': 'B'}, ['continuous'], True), ({'continuous': 'A', 'cat': 'B'}, ['*'], F...
class AutoConfig(): def __init__(self): raise EnvironmentError('AutoConfig is designed to be instantiated using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method.') def for_model(cls, model_type: str, *args, **kwargs): if (model_type in CONFIG_MAPPING): config_cl...
def load_data(store, name, name_buys): store = pd.HDFStore(store) data = store[name] buys = store[name_buys] del data['Time'] data['SessionId'] = data['SessionDay'] data['ItemId'] = data['Item'] data['Time'] = data['TimeObject'].apply((lambda t: t.timestamp())) data['UserId'] = data['Use...
def IPOT_torch(C, n, m, miu, nu, beta=0.5): sigma = (torch.ones(int(m), 1).float().cuda() / m) T = torch.ones(n, m).cuda() C = torch.exp(((- C) / beta)).float() for t in range(20): T = (C * T) for k in range(1): delta = (miu / torch.squeeze(torch.matmul(T, sigma))) ...
def get_dataset(*args): dset = SequenceList() for name in args: dset.extend(load_dataset(name)) return dset
def pose_decoder_mlp(params): init_fn = (utils.normal_init_ if (params['init_fn'] == 'normal_init') else utils.xavier_init_) pose_decoder = nn.Linear(params['model_dim'], params['pose_dim']) utils.weight_init(pose_decoder, init_fn_=init_fn) return pose_decoder
_start_docstrings('\n VAN Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ', VAN_START_DOCSTRING) class VanForImageClassification(VanPreTrainedModel): def __init__(self, config): super().__init__(config) self.van = VanMod...
def dec_prior_uniform(samples, min_value=((- np.pi) / 2.0), max_value=(np.pi / 2.0)): lower = (samples['dec'] > min_value) upper = (samples['dec'] < max_value) return np.logical_and(lower, upper)
def convert_onnx(net, path_module, output, opset=11, simplify=False): assert isinstance(net, torch.nn.Module) img = np.random.randint(0, 255, size=(112, 112, 3), dtype=np.int32) img = img.astype(np.float) img = (((img / 255.0) - 0.5) / 0.5) img = img.transpose((2, 0, 1)) img = torch.from_numpy(i...
class DenoisingConfig(FairseqDataclass): data: str = field(default=MISSING, metadata={'help': 'path to data directory'}) bpe: Optional[str] = field(default=None, metadata={'help': 'TODO'}) tokens_per_sample: int = field(default=512, metadata={'help': 'max number of total tokens over all segments per sample ...
def accuracy(logits, targets, weights=None): if (logits.ndim != (targets.ndim + 1)): raise ValueError(('Incorrect shapes. Got shape %s logits and %s targets' % (str(logits.shape), str(targets.shape)))) loss = jnp.equal(jnp.argmax(logits, axis=(- 1)), targets) loss *= weights return (loss.sum(), ...
class Block(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention(dim, num_heads=num_heads, qkv_bi...
def mobilenet_v2(**config): dataset = config.pop('dataset', 'imagenet') assert (dataset == 'imagenet') if ('depth' in config): config.pop('depth') return MobileNetV2(**config)
def _spherical_kmeans_single_lloyd(X, n_clusters, sample_weight=None, max_iter=300, init='k-means++', verbose=False, x_squared_norms=None, random_state=None, tol=0.0001, precompute_distances=True): random_state = check_random_state(random_state) sample_weight = _check_sample_weight(sample_weight, X) (best_l...
def quaternion_multiply(q1, q2): (w1, x1, y1, z1) = (q1[(..., 0)], q1[(..., 1)], q1[(..., 2)], q1[(..., 3)]) (w2, x2, y2, z2) = (q2[(..., 0)], q2[(..., 1)], q2[(..., 2)], q2[(..., 3)]) w = ((((w1 * w2) - (x1 * x2)) - (y1 * y2)) - (z1 * z2)) x = ((((w1 * x2) + (x1 * w2)) + (y1 * z2)) - (z1 * y2)) y =...
def eval_redwood_scene(model, dloader, config, posegraph_name, use_icp): pose_graph = o3d.registration.PoseGraph() odometry = np.identity(4) pose_graph.nodes.append(o3d.registration.PoseGraphNode(odometry)) orig_points_dict = {} num_pair = dloader.dataset.__len__() dloader_iter = dloader.__iter_...
def beam_decode(data, model, device): (name, feat, feat_len, txt) = data feat = feat.to(device) feat_len = feat_len.to(device) txt = txt.to(device) txt_len = torch.sum((txt != 0), dim=(- 1)) model = model.to(device) with torch.no_grad(): hyps = model(feat, feat_len) hyp_seqs = [h...
class SubnetLeNet_Default(nn.Module): def __init__(self, taskcla, sparsity): super(SubnetLeNet_Default, self).__init__() self.in_channel = [] self.conv1 = SubnetConv2d(1, 10, 5, sparsity=sparsity, bias=False, padding=2) s = compute_conv_output_size(32, 5, 1, 2) s = compute_co...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('dump_dir') parser.add_argument('stage') parser.add_argument('--dump_paths', default=None, help='Relative to `dump_dir/phrase`. If specified, creates subindex dir and save there with same name') parser.add_argument('--subindex_na...
def plane_rcnn_loss(plane_pred, instances, loss_weight=1.0, smooth_l1_beta=0.0, plane_normal_only=False): gt_param = [] for instances_per_image in instances: if (len(instances_per_image) == 0): continue gt_param.append(instances_per_image.gt_planes) if (len(gt_param) == 0): ...
class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, bn=False, nonlin=True): super(ConvBlock, self).__init__() self.conv = Conv3x3(in_channels, out_channels) if nonlin: self.nonlin = nn.ELU(inplace=True) else: self.nonlin = None if...
def run(config): print('slac non-rigid optimization.') o3d.utility.set_verbosity_level(o3d.utility.VerbosityLevel.Debug) path_dataset = config['path_dataset'] ply_file_names = get_file_list(join(config['path_dataset'], config['folder_fragment']), '.ply') if (len(ply_file_names) == 0): raise ...
def np_mp_array(shape, dtype): size = int(np.prod(shape)) nbytes = (size * np.dtype(dtype).itemsize) mp_array = mp.RawArray(ctypes.c_char, nbytes) return np.frombuffer(mp_array, dtype=dtype, count=size).reshape(shape)
.slow def test_alternating_autocorr_per_chain(): ntiles = 100 samples = jnp.tile(jnp.array([[1, 2], [(- 1), (- 2)]]), (ntiles, 1)) autocorr = statistics.per_chain_autocorr_fast(samples) expected_autocorr = jnp.tile(jnp.array([[1.0, 1.0], [(- 1.0), (- 1.0)]]), (ntiles, 1)) np.testing.assert_allclose(...
def _test(): import torch pretrained = False models = [spnasnet] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.format(model.__name__, weight_count)) assert ((model != spnasnet) or (weight_count ...
def tf_efficientnet_b2_ns(pretrained=False, **kwargs): kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' model = _gen_efficientnet('tf_efficientnet_b2_ns', channel_multiplier=1.1, depth_multiplier=1.2, pretrained=pretrained, **kwargs) return model
def reduce(l): n = 10 res = [] (low, high) = ([], []) for i in range(0, len(l)): res.append(statistics.mean(l[max(0, (i - n)):min(len(l), (i + n))])) low.append(min(l[max(0, (i - n)):min(len(l), (i + n))])) high.append(max(l[max(0, (i - n)):min(len(l), (i + n))])) return (res...
def create_dictionaries(filename): image_to_tag = {i: [] for i in ss} tag_to_image = {} with open(filename) as f: f.readline() for r in f: (imageid, source, tag, confidence) = r.split(',') tag = tag_to_name[tag] if ((imageid in ss) and (int(confidence) == ...
class CarlaSensorListMaster(object): def __init__(self): self.sensor_list = [] def append(self, sensor, transform, binded): sensor_master = CarlaSensorMaster(sensor, transform, binded) self.sensor_list.append(sensor_master) def destroy(self): for sensor_master in self.sensor_...
def _weight_align(tp_model, ref_model): sd = ref_model.state_dict() new_sd = dict() for (k, tensor) in sd.items(): if k.endswith('attn.c_attn.weight'): new_tensor = torch.empty((tensor.shape[1] // 2), tensor.shape[0], device=tensor.device) _initialize_affine_weight(new_tensor...
def _test_skipping_update_params_nonfinite_loss(rank, world_size): os.environ['LOCAL_RANK'] = str(rank) os.environ['RANK'] = str(rank) os.environ['WORLD_SIZE'] = str(world_size) os.environ['NPROC_PER_NODE'] = str(world_size) dist.init_process_group(backend='nccl', rank=rank, world_size=world_size) ...
class ResConvLayer(tf.keras.layers.Layer): def __init__(self, num_filters, *args, **kwargs): self.num_filters = num_filters super(ResConvLayer, self).__init__(*args, **kwargs) def build(self, input_shape): self.initial_conv = [tf.keras.layers.Conv2D(self.num_filters[0], (7, 7), input_sha...
class W2lKenLMDecoder(W2lDecoder): def __init__(self, args, tgt_dict): super().__init__(args, tgt_dict) self.silence = tgt_dict.index(args.silence_token) self.lexicon = load_words(args.lexicon) self.word_dict = create_word_dict(self.lexicon) self.unk_word = self.word_dict.get...
def DrawLegend(legend_labels, filename): fig = pylab.figure() ax1 = fig.add_subplot(111) FIGURE_LABEL = legend_labels LEGEND_FP = FontProperties(style='normal', size=26) bars = ([None] * len(FIGURE_LABEL)) data = [1] x_values = [1] width = 0.3 for i in range(len(FIGURE_LABEL)): ...
def downsize(scan): (intrinsics, _) = camera_parameters(scan) pano_ids = list(set([item.split('_')[0] for item in intrinsics.keys()])) print(('Processing scan %s with %d panoramas' % (scan, len(pano_ids)))) for pano in pano_ids: for skybox_ix in range(6): skybox = cv2.imread((skybox_...
def read_and_decode(filename_queue, IMG_HEIGHT, IMG_WIDTH): reader = tf.TFRecordReader() (_, serialized_example) = reader.read(filename_queue) features = tf.parse_single_example(serialized_example, features={'img1_raw': tf.FixedLenFeature([IMG_HEIGHT, IMG_WIDTH, 3], tf.float32), 'img2_raw': tf.FixedLenFeatu...
class Layer(): def __init__(self, qregs, cregs): self.qregs = qregs self.cregs = cregs self.qubit_layer = ([None] * len(qregs)) self.connections = [] self.clbit_layer = ([None] * len(cregs)) def full_layer(self): return (self.qubit_layer + self.clbit_layer) de...
class AutoAdapterConfig(nn.Module): def get(cls, config_name: str): if (config_name in ADAPTER_CONFIG_MAPPING): return ADAPTER_CONFIG_MAPPING[config_name]() raise ValueError('Unrecognized adapter config type identifier: {}. Should contain one of {}'.format(config_name, ', '.join(ADAPTER_...
class FineTuningConfig(): dataset: DataConfig = DataConfig() stage1: Stage1Config = Stage1Config() stage2: Stage2Config = Stage2Config() optimizer: OptConfig = OptConfig() experiment: ExpConfig = ExpConfig()
def convert_orig_tf1_checkpoint_to_pytorch(tf_checkpoint_path, convbert_config_file, pytorch_dump_path): conf = ConvBertConfig.from_json_file(convbert_config_file) model = ConvBertModel(conf) model = load_tf_weights_in_convbert(model, conf, tf_checkpoint_path) model.save_pretrained(pytorch_dump_path) ...
def goToGoal(env, lastObs): goal = lastObs['desired_goal'] objectPos = lastObs['observation'][3:6] gripperPos = lastObs['observation'][:3] gripperState = lastObs['observation'][9:11] object_rel_pos = lastObs['observation'][6:9] episodeAcs = [] episodeObs = [] episodeInfo = [] object_...
def get_runid(path): name = Path(path).name if (not os.path.exists(Path(path).parent)): return '00001' files = os.listdir(Path(path).parent) runid = 0 for f in files: try: (id, val) = f.split('_', 1) runid = max(runid, int(id)) except: pass...
def D_wgan(G, D, opt, training_set, minibatch_size, reals, labels, wgan_epsilon=0.001): _ = (opt, training_set) latents = tf.random_normal(([minibatch_size] + G.input_shapes[0][1:])) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, i...
(nopython=True) def _draw_loop(top_down_map, fog_of_war_mask, current_point, current_angle, max_line_len, angles): for angle in angles: draw_fog_of_war_line(top_down_map, fog_of_war_mask, current_point, (current_point + (max_line_len * np.array([np.cos((current_angle + angle)), np.sin((current_angle + angle...
def print_measures(auroc, aupr, fpr, method_name='Ours', recall_level=recall_level_default): print(('\t\t\t\t' + method_name)) print('FPR{:d}:\t\t\t{:.2f}'.format(int((100 * recall_level)), (100 * fpr))) print('AUROC: \t\t\t{:.2f}'.format((100 * auroc))) print('AUPR: \t\t\t{:.2f}'.format((100 * aupr)))
class BaseModule(nn.Module, metaclass=ABCMeta): def __init__(self, init_cfg=None): super(BaseModule, self).__init__() self._is_init = False self.init_cfg = init_cfg def is_init(self): return self._is_init def init_weights(self): from ..cnn import initialize if...
(version='2.0') class Sampler(object): def __init__(self, data_source): pass def __iter__(self): raise NotImplementedError
def pick_examples(dataset): if (FLAGS.model_type == 'retrieval'): return dataset.enumerate_comp() else: return dataset.enumerate_freq()
def get_connection(): if (not _db.connection): _db.connection = connector.connect(**config_sql) if (not _db.connection.is_connected()): _db.connection.reconnect() return _db.connection
def vgg_munit(vgg, img, rec): ff = torch.nn.functional.instance_norm(vgg.fw_relu(img, 13)[(- 1)]) fn = torch.nn.functional.instance_norm(vgg.fw_relu(rec, 13)[(- 1)]) vgg_imgs = [] vgg_imgs.append((ff - fn).pow(2).mean(dim=1, keepdim=True)) loss = vgg_imgs[(- 1)].mean() return (loss, vgg_imgs)
class FPN(nn.Module): def __init__(self, norm_layer, num_filters=128, pretrained=True): super().__init__() net = MobileNetV2(n_class=1000) if pretrained: state_dict = torch.load('mobilenetv2.pth.tar') net.load_state_dict(state_dict) self.features = net.feature...
class ResNeXtBottleneck(nn.Module): def __init__(self, in_channels, out_channels, stride, cardinality, widen_factor): super(ResNeXtBottleneck, self).__init__() D = ((cardinality * out_channels) // widen_factor) self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=1, padding=0, ...
def get_root_logger(log_file=None, log_level=logging.INFO, name='main'): logger = get_logger(name=name, log_file=log_file, log_level=log_level) logging_filter = logging.Filter(name) logging_filter.filter = (lambda record: (record.find(name) != (- 1))) return logger
class Controller(): def __init__(self, dispatch_method: str): self.worker_info = {} self.dispatch_method = DispatchMethod.from_str(dispatch_method) self.heart_beat_thread = threading.Thread(target=heart_beat_controller, args=(self,)) self.heart_beat_thread.start() logger.info...
def set_double_double_start_solutions(nvr, sols, vrblvl=0): if (vrblvl > 0): print('in set_double_double_start_solutions, with nvr :', nvr) print('the solutions :') for (idx, sol) in enumerate(sols): print('Solution', idx, ':') print(sol) clear_double_double_solut...
class VQModel(ModelMixin, ConfigMixin): _to_config def __init__(self, in_channels: int=3, out_channels: int=3, down_block_types: Tuple[(str, ...)]=('DownEncoderBlock2D',), up_block_types: Tuple[(str, ...)]=('UpDecoderBlock2D',), block_out_channels: Tuple[(int, ...)]=(64,), layers_per_block: int=1, act_fn: str='...
def reduction_a(net, k, l, m, n): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, n, 3, stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, k, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_...
def find_LL_channel(h5): LL_candidates = ['valiset.spl100.LL', 'valiset.spl25.LL', 'valiset.spl10.LL', 'valiset.spl5.LL', 'dataset.spl100.LL', 'dataset.spl25.LL', 'dataset.spl10.LL', 'dataset.spl5.LL'] for name in LL_candidates: if (name in h5): return name raise ValueError('Could not fi...
def _find_image_bounding_boxes(filenames, image_to_bboxes): num_image_bbox = 0 bboxes = [] for f in filenames: basename = os.path.basename(f) if (basename in image_to_bboxes): bboxes.append(image_to_bboxes[basename]) num_image_bbox += 1 else: bboxe...
def ghostnet(): data_shape = (1, 3, 224, 224) cfg_file_list = ['configs/benchmarks/ghostnet/ghostnet_x1_0_zcls_imagenet_224.yaml'] name_list = ['ghostnet_x1_0_zcls'] assert (len(name_list) == len(cfg_file_list)) for (name, cfg_file) in zip(name_list, cfg_file_list): main(data_shape, cfg_file...
def vgg19_bn(cuda=True, model_root=None): print('Building vgg19_bn parameters') from imagenet import vgg m = vgg.vgg19_bn(model_root) if cuda: m = m.cuda() return (m, dataset.get, True)
def get_class_in_module(class_name, module_path): module_path = module_path.replace(os.path.sep, '.') module = importlib.import_module(module_path) if (class_name is None): return find_pipeline_class(module) return getattr(module, class_name)
def get_logger(logdir): logger = logging.getLogger('smnet') ts = str(datetime.datetime.now()).split('.')[0].replace(' ', '_') ts = ts.replace(':', '_').replace('-', '_') file_path = os.path.join(logdir, 'run_{}.log'.format(ts)) hdlr = logging.FileHandler(file_path) formatter = logging.Formatter(...
class InfBallProjBounded(InfBallProj): def __init__(self, X, epsilon, k, l=0, u=1): self.epsilon = epsilon self.nu_one_l = [(X - epsilon).clamp(min=l)] self.nu_one_u = [(X + epsilon).clamp(max=u)] self.nu_x = [X] self.l = self.nu_one_l[(- 1)].view(X.size(0), 1, (- 1)) ...