code
stringlengths
101
5.91M
def test_orbits_method_returntype_scalar(): from galpy.orbit import Orbit o = Orbit([[(10.0 * units.kpc), (((- 20.0) * units.km) / units.s), ((210.0 * units.km) / units.s), (500.0 * units.pc), (((- 12.0) * units.km) / units.s), (45.0 * units.deg)], [((- 20.0) * units.kpc), ((10.0 * units.km) / units.s), ((230.0...
class LabelSmoothingLoss(nn.Module, ABC): def __init__(self, epsilon, reduction='mean'): super(LabelSmoothingLoss, self).__init__() self.epsilon = epsilon self.reduction = reduction def __call__(self, output_dict, targets): assert (isinstance(output_dict, dict) and (KEY_OUTPUT in...
def test_init(g1, g2): assert (g1.num_v == 4) assert (g1.num_e == 2) assert ((0, 1) in g1.e[0]) assert (g1.A[(0, 1)] == 1) assert ((1, 0) in g1.e_both_side[0]) assert (g1.A[(1, 0)] == 1) assert (g2.num_v == 4) assert (g2.num_e == 3) assert ((0, 3) in g2.e[0]) assert (g2.A[(0, 3)]...
def make_attention_block(in_planes, reduction, attention_type, **kwargs): if (attention_type == 'GlobalContextBlock2D'): return GlobalContextBlock2D(in_channels=in_planes, reduction=reduction) elif (attention_type == 'SqueezeAndExcitationBlock2D'): return SqueezeAndExcitationBlock2D(in_channels=...
class BertJapaneseTokenizer(BertTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_low...
class TestBinaryOp(unittest.TestCase): def setUpClass(self): pass def tearDownClass(self): pass def test_binary_op(self): model = Graph() input_tensors = [Tensor(name='any', source_op=[], dest_op=['anyop'])] output_tensors = [Tensor(name='any_out', source_op=['anyop']...
class Kukaiiwa(Robot): def __init__(self, name: str, id_num: int, world, sim_step: float, use_physics_sim: bool, base_position: Union[(list, np.ndarray)], base_orientation: Union[(list, np.ndarray)], resting_angles: Union[(list, np.ndarray)], control_mode: Union[(int, str)], ik_xyz_delta: float=0.005, ik_rpy_delta:...
def osnet_x1_0_efdmix23_a0d3(num_classes=1000, pretrained=True, loss='softmax', **kwargs): model = OSNet(num_classes, blocks=[OSBlock, OSBlock, OSBlock], layers=[2, 2, 2], channels=[64, 256, 384, 512], loss=loss, efdmix_layers=['conv2', 'conv3'], efdmix_alpha=0.3, **kwargs) if pretrained: init_pretraine...
class GoldenFeaturesTransformerOriginal(object): def __init__(self, features_count=None): self._new_features = [] self._new_columns = [] self._features_count = features_count self._scorer = get_logloss_score self._error = None def fit(self, X, y): if self._new_fea...
def prepare_for_retracing(gm: GraphModule) -> Tuple[(GraphModule, Dict[(str, Any)])]: attributes = _cache_attributes(gm) _patch_arguments_(gm, gm.dynamic2static) return (gm, attributes)
class GeneratorWithLongSkipsExtraConv(torch.nn.Module): def __init__(self, input_dim, num_filter, output_dim, num_resnet): super(GeneratorWithLongSkipsExtraConv, self).__init__() self.pad = torch.nn.ReflectionPad2d(3) self.conv1 = ConvBlock(input_dim, num_filter, kernel_size=7, stride=1, pad...
.timeout(30) def test_init_with_crashed_worker(): max_path_length = 16 env = GarageEnv(PointEnv()) policy = FixedPolicy(env.spec, scripted_actions=[env.action_space.sample() for _ in range(max_path_length)]) tasks = SetTaskSampler((lambda : GarageEnv(PointEnv()))) n_workers = 2 workers = WorkerF...
def mkdir_p(path): if (not path): return try: os.makedirs(path) except OSError as exc: if ((exc.errno == errno.EEXIST) and os.path.isdir(path)): pass else: raise
class MultiSparseMap3D(genpy.Message): _md5sum = '2e3d76c98ee3e2b23a422f64965f6418' _type = 'multi_map_server/MultiSparseMap3D' _has_header = False _full_text = "SparseMap3D[] maps\ngeometry_msgs/Pose[] origins\n\n\nMSG: multi_map_server/SparseMap3D\nHeader header\nnav_msgs/MapMetaData info\nVerticalOcc...
class Segmenter(): def __init__(self): segm_cfg = Munch.fromDict(rospy.get_param('segmentation')) segm_model = segmentation_models.DRNSeg(segm_cfg.arch, segm_cfg.data.classes, None, pretrained=True) segm_model = torch.nn.DataParallel(segm_model).cuda() cudnn.benchmark = True ...
def test(loader, model, criterion, epoch, noise_sd, device, writer=None, print_freq=10): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() end = time.time() model.eval() with torch.no_grad(): for (i, (inputs...
class _ResBlockSR(nn.Module): def __init__(self, inchannel, outchannel, stride=1): super(_ResBlockSR, self).__init__() self.layers = nn.Sequential(nn.Conv2d(inchannel, outchannel, 3, stride, 1, bias=True), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(outchannel, outchannel, 3, stride, 1, bias=True)) ...
_module class Compose(object): def __init__(self, transforms): assert isinstance(transforms, collections.abc.Sequence) self.transforms = [] for transform in transforms: if isinstance(transform, dict): if (transform['type'] == 'Empty'): continue...
_arg_scope def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None): with tf.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc: depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4) if (depth == depth_in): shortcut = resnet...
def safe_convert_to_torch_tensor(x, device=None): def mapping(item): if torch.is_tensor(item): return (item if (device is None) else item.to(device)) elif isinstance(item, RepeatedValues): return RepeatedValues(tree.map_structure(mapping, item.values), item.lengths, item.max_...
def find_most_similar(input_str, list_strings): if (input_str == 'all'): return list(range(len(pde_list))) substrings = re.split('\\W+', input_str) result_indices = [] for substring in substrings: distances = [lev.distance(substring, list_string) for list_string in list_strings] ...
(interaction_name=str, receiver='Component', supplier='Component', dt_rungs=dict, rank_supplier='int', only_supply='bint', pairing_level=str, tile_indices_receiver='Py_ssize_t[::1]', tile_indices_supplier_paired='Py_ssize_t**', tile_indices_supplier_paired_N='Py_ssize_t*', extra_args=dict, apply_to_i='bint', apply_to_j...
class LowRankAdapter(nn.Module): def __init__(self, config): super().__init__() self.config = config self.input_dim = config.input_dim self.down_sample_size = (self.input_dim // config.reduction_factor) self.activation = Activations(config.non_linearity.lower()) self....
def test(epoch): global best_acc net.eval() test_loss = 0 correct = 0 total = 0 with torch.no_grad(): for (batch_idx, (inputs, inputs1, inputs2, inputs3, targets, targets1, targets2, targets3, path)) in enumerate(testloader): (inputs, inputs1, targets, targets1) = (inputs.to(...
def rejection_sampling(command, seed=0): proc = sp.run(command, stdout=sp.PIPE) facet_list = [] for line in proc.stdout.decode().split('\n')[1:(- 1)]: if (line.find('#') == 0): (yield facet_list) facet_list = [] else: facet_list.append([int(x) for x in lin...
_CODERS.register_module() class PseudoBBoxCoder(BaseBBoxCoder): def __init__(self, **kwargs): super(BaseBBoxCoder, self).__init__(**kwargs) def encode(self, bboxes, gt_bboxes): return gt_bboxes def decode(self, bboxes, pred_bboxes): return pred_bboxes
def hernquist_ppf(r, a_scale=1.0): ppf = (((a_scale - (a_scale * r)) + np.sqrt(((a_scale ** 2) - (r * (a_scale ** 2))))) / r) return ppf
def main(args, override_args=None): utils.import_user_module(args) assert ((args.max_tokens is not None) or (args.max_sentences is not None)), 'Must specify batch size either with --max-tokens or --max-sentences' use_fp16 = args.fp16 use_cuda = (torch.cuda.is_available() and (not args.cpu)) if (over...
class ResNetNoPadding(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(ResNetNoPadding, self).__init__() self.in_planes = 64 self.conv1 = Conv2d_NoPadding(3, 64, kernel_size=7, stride=2, padding=0, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 ...
class ArcsinhFlow(Flow): def __init__(self, init_a: float, init_b: float, init_c: float, init_d: float, add_init_f0: bool, set_restrictions: bool) -> None: super(ArcsinhFlow, self).__init__() self.a = nn.Parameter(torch.tensor(init_a, dtype=cg.dtype)) self.b = nn.Parameter(torch.tensor(init_...
class Conv3d_wd(nn.Conv3d): def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1, 1), padding=(0, 0, 0), dilation=(1, 1, 1), groups=1, bias=True): super(Conv3d_wd, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias) def forward(self, x): ...
class DataLoaderX(DataLoader): def __init__(self, local_rank, **kwargs): super(DataLoaderX, self).__init__(**kwargs) self.stream = torch.cuda.Stream(local_rank) self.local_rank = local_rank def __iter__(self): self.iter = super(DataLoaderX, self).__iter__() self.iter = Ba...
class PytorchRayWorker(TorchRunner): def __init__(self, model_creator, optimizer_creator, loss_creator=None, metrics=None, scheduler_creator=None, config=None, sync_stats=True, log_level=logging.INFO): super().__init__(model_creator=model_creator, optimizer_creator=optimizer_creator, loss_creator=loss_creat...
def edge_flip(F, FF, FFi, f0, e0, AdjMat_lil): f1 = int(FF[(f0, e0)]) if (f1 == (- 1)): assert False e1 = int(FFi[(f0, e0)]) e01 = ((e0 + 1) % 3) e02 = ((e0 + 2) % 3) e11 = ((e1 + 1) % 3) e12 = ((e1 + 2) % 3) f01 = int(FF[(f0, e01)]) f02 = int(FF[(f0, e02)]) f11 = int(FF[...
def get_optimizer(model, lr=0.001, wd=0.0): parameters = filter((lambda p: p.requires_grad), model.parameters()) optim = torch.optim.Adam(parameters, lr=lr, weight_decay=wd) return optim
def domain_encoding(loaders, args, encoder): statistics = [] for loader in loaders: ind = 0 labels = None S = [] for (batch, label) in loader: if args.cuda: batch = Variable(batch.cuda()) S.append(encoder(batch)) if (ind == 0): ...
def main(): for (i, lvl) in enumerate([logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]): log_name = str(lvl) init_log(log_name, lvl) logger = logging.getLogger(log_name) print('****cur lvl:{}'.format(lvl)) logger.debug('debug') logger.in...
def AddSamplerLayer(x, num_samples, traj_length, feature_size, activation=None): x = Dense(((num_samples * traj_length) * feature_size))(x) if (activation is not None): x = activation(x) x = Reshape((num_samples, traj_length, feature_size))(x) return x
class Uniform(object): def __init__(self, a, b): self.a = a self.b = b def sample(self): return random.uniform(self.a, self.b)
class CIFAR100(CIFAR10): base_folder = 'cifar-100-python' url = ' filename = 'cifar-100-python.tar.gz' tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85' train_list = [['train', '16019d7e3df5f24257cddd939b257f8d']] test_list = [['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc']] meta = {'filename': 'tin...
def resize(): for item in dirs: if os.path.isfile((path + item)): im = Image.open((path + item)) (f, e) = os.path.splitext((path + item)) imResize = im.resize((64, 64), Image.ANTIALIAS) imResize.save((f + ' resized.jpg'), 'JPEG', quality=90)
(version='2.0') def reset_non_value_to_default(obj, key, default): if isinstance(obj, dict): if ((key not in obj.keys()) or (obj[key] is None)): return default else: return obj[key] elif ((not hasattr(obj, key)) or (getattr(obj, key) is None)): return default ...
class Pipeline2D(): def __init__(self, cfg): self.cfg = cfg print('Use visdom:', cfg.visdom.use) print('Use virtual view:', (not cfg.dataset.real_view)) def train(self): device = self.get_device() scene_dataset = self.get_scene_dataset(mode='train', use_transform=True) ...
def reset(nn): def _reset(item): if hasattr(item, 'reset_parameters'): item.reset_parameters() if (nn is not None): if (hasattr(nn, 'children') and (len(list(nn.children())) > 0)): for item in nn.children(): _reset(item) else: _reset(nn...
def vote_last_response(states, vote_type, model_selectors, request: gr.Request): with open(get_conv_log_filename(), 'a') as fout: data = {'tstamp': round(time.time(), 4), 'type': vote_type, 'models': [x for x in model_selectors], 'states': [x.dict() for x in states], 'ip': request.client.host} fout....
class RoIAwarePool3dFunction(Function): def forward(ctx, rois, pts, pts_feature, out_size, max_pts_per_voxel, mode): if isinstance(out_size, int): out_x = out_y = out_z = out_size else: assert (len(out_size) == 3) assert mmcv.is_tuple_of(out_size, int) ...
def test_mildnonaxi_oortA_grid_tlist(): idf = dehnendf(beta=0.0) pot = [LogarithmicHaloPotential(normalize=1.0), EllipticalDiskPotential(twophio=0.001)] edf = evolveddiskdf(idf, pot=pot, to=(- 10.0)) (oa, grid, dgridR, dgridphi) = edf.oortA(0.9, t=[0.0, (- 2.5), (- 5.0), (- 7.5), (- 10.0)], phi=0.2, int...
def inTopk(scores, ans, k): result = False topk = torch.topk(scores, k)[1] for x in topk: if (x in ans): result = True return result
class ReplaceExpression(TraverseAction): expr_to_replace: TreeNode replacement_expr: TreeNode inserted_node: List[id] def __init__(self, expr_to_replace: TreeNode, replacement_expr: TreeNode): super().__init__() self.expr_to_replace = expr_to_replace self.replacement_expr = repla...
class Dataset(object): def __init__(self, path): self.path = path files = glob.glob((path + '/*.csv')) self.collections = {file_name(file): file for file in files} def rows(self, collection_name, num_epochs=None): if (collection_name not in self.collections): raise Va...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, RepCONCFinetuneArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, dat...
def get_chatgpt_response(model, prompt): response = '' for data in model.ask(prompt): response = data['message'] model.delete_conversation(model.conversation_id) model.reset_chat() return response
class Polygon(): def __init__(self, pos, length, height, space, mass=5.0): moment = 1000 body = pm.Body(mass, moment) body.position = Vec2d(pos) shape = pm.Poly.create_box(body, (length, height)) shape.color = (0, 0, 255) shape.friction = 0.5 shape.collision_t...
_arg_scope def masked_separable_convolution2d(inputs, num_outputs, kernel_size, depth_multiplier, stride=1, padding='SAME', data_format=None, rate=1, activation_fn=nn.relu, normalizer_fn=None, normalizer_params=None, weights_initializer=initializers.xavier_initializer(), weights_regularizer=None, biases_initializer=ini...
def infer_failure(inst) -> bool: lib = ('torch' if ('torch' in inst.name_index) else 'tf') judge_result_dir = os.path.join(RULE_DIR, f'{lib}_rules_validity') try: with open(os.path.join(judge_result_dir, f'{inst.name_index}.pkl'), 'rb') as f: valid = pickle.load(f)[0] except Exceptio...
def train_loader_creator(config, batch_size): train_transform = A.Compose([A.Resize(width=128, height=128, p=1.0), A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5), A.RandomRotate90(p=0.5), A.ShiftScaleRotate(shift_limit=0.01, scale_limit=0.04, rotate_limit=0, p=0.25)]) train_ds = BrainDataset(config['train'], tr...
class RandomSampler(Sampler): def __init__(self, data_source, replacement=False, num_samples=None): super(RandomSampler, self).__init__(data_source) self.replacement = replacement self._num_samples = num_samples if (not isinstance(self.replacement, bool)): raise ValueErro...
class VarSkipRNNBase(nn.Module): def __init__(self, Cell, input_size, hidden_size, num_layers=1, bias=True, batch_first=False, dropout=(0, 0), bidirectional=False, **kwargs): super(VarSkipRNNBase, self).__init__() self.Cell = Cell self.input_size = input_size self.hidden_size = hidde...
def build_vocab(cfg: Dict, dataset: BaseDataset=None, model_dir: Path=None) -> Tuple[(Vocabulary, Vocabulary)]: if ((model_dir is not None) and (cfg['src'].get('voc_file', None) is None)): assert (model_dir / 'src_vocab.txt').is_file() cfg['src']['voc_file'] = (model_dir / 'src_vocab.txt').as_posix(...
def compute_hashes(X, A, H=None): device = X.device if (H is None): H = torch.zeros(len(X), dtype=torch.int64, device=device) else: H.zero_() if (A.shape[1] != (X.shape[1] + 1)): raise ValueError('The hash requires a bias') if (device.type == 'cpu'): compute_hashes_cp...
def hard_volume(box_tensor: BoxTensor, log_scale: bool=True) -> torch.Tensor: if log_scale: return torch.sum(torch.log((box_tensor.Z - box_tensor.z).clamp_min(eps)), dim=(- 1)) return torch.prod((box_tensor.Z - box_tensor.z).clamp_min(0), dim=(- 1))
def create_log_dir(exp_prefix, exp_id=0, seed=0, base_log_dir=None, include_exp_prefix_sub_dir=True): exp_name = create_exp_name(exp_prefix, exp_id=exp_id, seed=seed) if (base_log_dir is None): base_log_dir = conf.LOCAL_LOG_DIR if include_exp_prefix_sub_dir: log_dir = osp.join(base_log_dir, ...
class CLIPConfig(PretrainedConfig): model_type = 'clip' is_composition = True def __init__(self, text_config_dict=None, vision_config_dict=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs): super().__init__(text_config_dict=text_config_dict, vision_config_dict=vision_config_dict, **...
def bit2dB(x): ret = 0 if bit(x, 3): ret += 24 if bit(x, 2): ret += 12 if bit(x, 1): ret += 6 if bit(x, 0): ret += 3 ret = (- ret) return ret
def evaluate_simple(eval_file, answer_dict): reference_corpus = [] translation_corpus = [] rouges = [] meteor = Meteor() (res, gts) = ([], []) for (key, answers) in answer_dict.items(): answers = sorted(answers, key=(lambda x: x[0]), reverse=True) ground_truths = [list(map((lambd...
class Args(): model_id: str = 'google/bigbird-roberta-base' logging_steps: int = 3000 save_steps: int = 10500 block_size: int = 128 num_random_blocks: int = 3 batch_size_per_device: int = 1 max_epochs: int = 5 lr: float = 3e-05 init_lr: float = 0.0 warmup_steps: int = 20000 w...
def print_cluster_extra(out_errors, out_context, out, text, auto_cluster_set, covered, gold_parses, gold_heads): print('Extra:', file=out_errors) print('Extra:', file=out_context) for entity in auto_cluster_set: printed = 0 for mention in entity: if (mention not in covered): ...
class BaseArgs(ABC): def __init__(self): self.args = None self.parser = argparse.ArgumentParser() self.logger = logging.getLogger(self.__class__.__name__) self.add_args() self.parse() self.validate() self.process() self.str_args = self.log() def ad...
def summary(model, *inputs, batch_size=(- 1), show_input=True): def register_hook(module): def hook(module, input, output=None): class_name = str(module.__class__).split('.')[(- 1)].split("'")[0] module_idx = len(summary) m_key = f'{class_name}-{(module_idx + 1)}' ...
class PurePursuitParam(): look_ahead_minmax: tuple[(float, float)] = (3, 30) k_lookahead: float = 0.8 min_distance: float = 2 max_extra_distance: float = 20 length: float = 3.5 lr: float = (3.5 / 2) def from_vehicle_geo(cls, params: VehicleGeometry) -> 'PurePursuitParam': return Pure...
def res2net50_v1b_26w_4s(pretrained=False, **kwargs): model = Res2Net(Bottle2neck, [3, 4, 6, 3], baseWidth=26, scale=4, **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['res2net50_v1b_26w_4s'], map_location='cpu')) return model
class Database(): signature_collection = 'signature' similarity_collection = 'similarity' argdef_collection = 'api_args' def __init__(self) -> None: pass def database_config(self, host, port, database_name): self.DB = pymongo.MongoClient(host=host, port=port)[database_name] def i...
class MolGraph(): def __init__(self, smiles_list, args, path_input=None, path_mask=None): self.smiles_list = smiles_list self.args = args self.device = args.device self.mols = [] self.scope = [] self.rd_mols = [] self.path_input = path_input self.path_...
def generate_rating_matrix_test(user_seq, num_users, num_items): row = [] col = [] data = [] for (user_id, item_list) in enumerate(user_seq): for item in item_list[:(- 1)]: row.append(user_id) col.append(item) data.append(1) row = np.array(row) col = n...
def replace_oov(x, oov_char, max_words): return [(oov_char if (w >= max_words) else w) for w in x]
def load_raw_spotting_predictions(saved_path: (Path | str), video_indexes: List[int], device: Any='cpu') -> Dict[(int, Dict[(int, Tensor)])]: predictions = {video_index: None for video_index in video_indexes} saved_path = Path(saved_path) from_zip = zipfile.is_zipfile(saved_path) if from_zip: wi...
def weights_init(module): for m in module.children(): if (not init_std_modules(m)): weights_init(m)
def jitter(obj: Union[(bpy.types.Object, str)], translate_range: Tuple[Tuple[float]]=((0, 0), (0, 0), (0, 0)), rotate_range: Tuple[Tuple[float]]=((0, 0), (0, 0), (0, 0)), scale_range: Tuple[Tuple[float]]=((1.0, 1.0), (1.0, 1.0), (1.0, 1.0))) -> None: obj = verify(obj) translate(obj, translation=(random.uniform(...
class TransformerDecoderLayer(nn.Module): def __init__(self, embed_dims, num_heads, feedforward_channels, dropout=0.0, order=('selfattn', 'norm', 'multiheadattn', 'norm', 'ffn', 'norm'), act_cfg=dict(type='ReLU', inplace=True), norm_cfg=dict(type='LN'), num_fcs=2): super(TransformerDecoderLayer, self).__ini...
def _evaluatelinearPotentials(Pot, x, t=0.0): if isinstance(Pot, list): sum = 0.0 for pot in Pot: sum += pot._call_nodecorator(x, t=t) return sum elif isinstance(Pot, linearPotential): return Pot._call_nodecorator(x, t=t) else: raise PotentialError("Input ...
class VisdomPlotLogger(BaseVisdomLogger): def __init__(self, plot_type, fields=None, win=None, env=None, opts={}, port=8097, server='localhost', name=None, log_to_filename=None): super(VisdomPlotLogger, self).__init__(fields, win, env, opts, port, server, log_to_filename) valid_plot_types = {'scatte...
def scale_arr(arr, mode='minmax'): if (mode == 'minmax'): from sklearn.preprocessing import MinMaxScaler scaled = MinMaxScaler().fit_transform(arr).astype('float32') elif (mode == 'standard'): from sklearn.preprocessing import StandardScaler scaled = StandardScaler().fit_transfor...
def batchnorm(x): (mean, variance) = tf.nn.moments(x, [0, 1, 2, 3]) return tf.nn.batch_normalization(x, mean=mean, variance=variance, offset=0, scale=1, variance_epsilon=1e-06)
class Conv1DLayer(BaseConvLayer): def __init__(self, incoming, num_filters, filter_size, stride=1, pad=0, untie_biases=False, W=init.GlorotUniform(), b=init.Constant(0.0), nonlinearity=nonlinearities.rectify, flip_filters=True, convolution=conv.conv1d_mc0, **kwargs): super(Conv1DLayer, self).__init__(incomi...
class nnUNetTrainerV2_SGD_fixedSchedule2(nnUNetTrainerV2): def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False): super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, ...
def create_dataset_batch_queue(dataset): from preprocessing import ssd_vgg_preprocessing with tf.device('/cpu:0'): with tf.name_scope((FLAGS.dataset_name + '_data_provider')): provider = slim.dataset_data_provider.DatasetDataProvider(dataset, num_readers=FLAGS.num_readers, common_queue_capac...
def main_worker(gpu, ngpus_per_node, args): args.gpu = gpu if (args.multiprocessing_distributed and (args.gpu != 0)): def print_pass(*args): pass builtins.print = print_pass if (args.gpu is not None): print('Use GPU: {} for training'.format(args.gpu)) if args.distribu...
class DensePASS13Segmentation(SegmentationDataset): NUM_CLASS = 13 def __init__(self, root='datasets/DensePASS', split='val', mode=None, transform=None, fov=360, **kwargs): super(DensePASS13Segmentation, self).__init__(root, split, mode, transform, **kwargs) assert os.path.exists(self.root), 'Pl...
def process_mmcif(mmcif_path: str, max_resolution: int, max_len: int, write_dir: str): metadata = {} mmcif_name = os.path.basename(mmcif_path).replace('.cif', '') metadata['pdb_name'] = mmcif_name mmcif_subdir = os.path.join(write_dir, mmcif_name[1:3].lower()) if (not os.path.isdir(mmcif_subdir)): ...
def test_crate(): gt_prefix = 'CrateModel' (gt_data_root, gt_download_dir, gt_extract_dir) = get_test_data_dirs(gt_prefix) crate = o3d.data.CrateModel() assert Path(gt_download_dir).is_dir() gt_path_map = {'crate_material': (Path(gt_extract_dir) / 'crate.mtl'), 'crate_model': (Path(gt_extract_dir) /...
def add_flops_counter_hook_function(module): if is_supported_instance(module): if hasattr(module, '__flops_handle__'): return for (mod_type, counter_hook) in hook_mapping.items(): if issubclass(type(module), mod_type): handle = module.register_forward_hook(cou...
def build_fake_yaml_footprint(): fake_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: x\n outputs: op_to_store\n device: cpu\n evaluation:\n accuracy:\n metric:\n topk: 1\n performance: {}\n ...
def get_input_data_amount(name: available_models, l: str) -> list[int]: if (name in ['resnet-50', 'resnet18']): layer_loc = l.split('.', maxsplit=1)[0] rows_adapted = [] if (layer_loc in ['layer1']): rows_adapted = [1, 2, 4, 8] elif (layer_loc == 'layer2'): ro...
def next_varbprec_solution(wanted, maxprec, maxit, verbose): from phcpy.phcpy2c3 import py2c_next_varbprec_solution sol = py2c_next_varbprec_solution(wanted, maxprec, maxit, verbose) return sol
def show_ae(autoencoder): encoder = autoencoder.Encoder() decoder = autoencoder.Decoder() encoded_imgs = encoder.predict(x_test) decoded_imgs = decoder.predict(encoded_imgs) n = 10 plt.figure(figsize=(20, 6)) for i in range(n): ax = plt.subplot(3, n, (i + 1)) plt.imshow(x_tes...
class GazeboEnv(gym.Env): def __init__(self, ns: str, reward_fnc: str, is_action_space_discrete, safe_dist: float=None, goal_radius: float=0.1, max_steps_per_episode=100, train_mode: bool=True, debug: bool=False, task_mode: str='staged', PATHS: dict=dict(), extended_eval: bool=False, *args, **kwargs): super...
_SAMPLERS.register_module() class OHEMPixelSampler(BasePixelSampler): def __init__(self, context, thresh=None, min_kept=100000): super(OHEMPixelSampler, self).__init__() self.context = context assert (min_kept > 1) self.thresh = thresh self.min_kept = min_kept def sample(...
def initialize_models(params: dict, vocab: Set[str], batch_first: bool, unk_token='UNK'): if ('embedding_file' in params['embeddings']): (embeddings, word_interner, de_interner) = extract_embeddings(vocab, params['embeddings']['embedding_file'], unk_token=unk_token) if torch.cuda.is_available(): ...
_ENCODERS.register_module() class SparseEncoder(nn.Module): def __init__(self, in_channels, sparse_shape, order=('conv', 'norm', 'act'), norm_cfg=dict(type='BN1d', eps=0.001, momentum=0.01), base_channels=16, output_channels=128, encoder_channels=((16,), (32, 32, 32), (64, 64, 64), (64, 64, 64)), encoder_paddings=(...
def exp_rampup(rampup_length): 'Exponential rampup from def warpper(epoch): if (epoch < rampup_length): epoch = np.clip(epoch, 0.0, rampup_length) phase = (1.0 - (epoch / rampup_length)) return float(np.exp((((- 5.0) * phase) * phase))) else: retu...