code
stringlengths
101
5.91M
class CWRUFFT(object): num_classes = 10 inputchannel = 1 def __init__(self, data_dir, normlizetype): self.data_dir = data_dir self.normlizetype = normlizetype def data_preprare(self, test=False): list_data = get_files(self.data_dir, test) if test: test_dataset...
def get_remote_list(dir_in): args = (('hdfs dfs -ls ' + dir_in) + " | awk '{print $8}'") (s_output, _) = process(args) all_dart_dirs = s_output.split() names = [] for filename in all_dart_dirs: name_list = filename.split('/') names.append(name_list[(- 1)]) return names
def parse_sexpr(stream): content = [] buffer = '' instr = False while True: c = stream.read(1) assert (c != ''), 'unexpected end of file' if instr: if (c == '"'): instr = False else: buffer += c elif (c == '('): ...
class BlendLossBuilder(torch.nn.Module): def __init__(self, opt): super(BlendLossBuilder, self).__init__() self.opt = opt self.parsed_loss = [[1.0, 'face'], [1.0, 'hair']] if (opt.device == 'cuda'): use_gpu = True else: use_gpu = False self.fac...
class CustomTensorDataset(Dataset): def __init__(self, *tensors, transform=None): assert all(((tensors[0].size(0) == tensor.size(0)) for tensor in tensors)) self.tensors = tensors self.transform = transform def __getitem__(self, index): from PIL import Image (X, y) = self...
def resnet1001_cifar(**kwargs): model = ResNet_Cifar(Bottleneck, [111, 111, 111], **kwargs) return model
class LazyDropout(nn.Module): def __init__(self): super().__init__() self.mask = None def sample_mask(self, x, dropout): mask = x.data.new(x.shape).bernoulli_((1 - dropout)) self.mask = (Variable(mask, requires_grad=False) / (1 - dropout)) def forward(self, x): if (no...
def double_conv(in_channels, out_channels): return nn.Sequential(conv(in_channels, out_channels, 3, padding=1), nn.BatchNorm2d((out_channels * factor)), act(), conv(out_channels, out_channels, 3, padding=1), nn.BatchNorm2d((out_channels * factor)), act())
class CallCache(object): def __init__(self): self.callqueue_ = [] self.tensors_ = dict() self.skip = False def update_tensors(self, other): self.tensors_.update(other.tensors_) def update_calls(self, other): self.callqueue_ += other.callqueue_ def append_call(self...
class FieldEntrySelector(EntrySelector): _SPEC_DELIM = ',' _TYPE_DELIM = ':' _RANGE_DELIM = '-' _EQUAL = '=' _ERROR_PREFIX = 'Invalid field selector specifier' class _FieldEntryValuePredicate(object): def __init__(self, name: str, typespec: str, value: str): import builtins ...
def comp_oracle_combination(_filtered_doc_list, _num_edu, _absas_read_str, abs_as_read_list, map_from_new_to_ori_idx, beam_sz=4): pass
class NN_tb3(): def __init__(self): self.distance = 0 self.desired_action = 0 self.psi = 0 self.deg_phi = 0 self.global_goal = PoseStamped() self.goal = PoseStamped() self.sub_goal = Vector3() self.scan = LaserScan() self.sub_pose = rospy.Subsc...
class createDmLab(object): def __init__(self, level, config, seed, runfiles_path=None, level_cache=None): self._random_state = np.random.RandomState(seed=seed) if runfiles_path: deepmind_lab.set_runfiles_path(runfiles_path) config = {k: str(v) for (k, v) in config.items()} ...
def output_current_round_deadline(selected_clients): t_max = sys.maxsize total_user_count = len(selected_clients) complete_user_counts_per_time = [] max_complete_user_counts_per_time = (- 1) max_complete_user_counts_per_time_idx = (- 1) for i in range(1, t_max): complete_user_count = 0 ...
class Router(): def __init__(self) -> None: self.routes: Dict[(str, RoutingDefinition)] = {'workloads': RealtimeRoutingDefinition(get_workloads_list), 'workloads/delete': RealtimeRoutingDefinition(delete_workload), 'profiling': RealtimeRoutingDefinition(get_profiling_details), 'model/graph': RealtimeRouting...
class ParallelMap(object): def __init__(self, source, worker, worker_num, bufsize=100, use_process=False, memsize='3G'): self._worker_num = worker_num self._bufsize = bufsize self._use_process = use_process if (self._use_process and (sys.platform == 'win32')): logger.debu...
def _sanity_check(js): assert (len(js['evidential']) == len(js['questions']) == len(js['answers'])), js
def plot_quant_rules(qrules): for r in qrules: plot_qrule(r, plt) for i in range(len(x_points)): plt.scatter(x_points[i], y_points[i], marker=appearance[data_class[i]][1], color=appearance[data_class[i]][0], s=60) for (i, n) in enumerate(x): plt.axhline(y=y[i], color='grey', linestyl...
class BatchNormalization(tf.keras.layers.BatchNormalization): def __init__(self, momentum=BN_MOMENTUM, name=None, **kwargs): super(BatchNormalization, self).__init__(momentum=momentum, name=name, **kwargs) def call(self, inputs, training=None): return super().call(inputs=inputs, training=trainin...
def forward_torch_model_from_h5(model: torch.nn.Module, num_tests_per_file: int, additional_transform_args: Dict, batch_size: int, competition_file: str, device: str, post_transform: Callable[([np.ndarray], Union[(torch.Tensor, torch_geometric.data.Data)])], pre_transform: Callable[([np.ndarray], Union[(torch.Tensor, t...
def _convert_shape_to_list(node: Any, fix_dynamic_shape: int, tf_module: Any) -> list: try: _shape = list(tf_module.TensorShape(node.attr['shape'].shape)) if (tf_module.__version__ >= '2.0.0'): shape = [(item if (item is not None) else fix_dynamic_shape) for item in _shape] else:...
class CombineDataset(Dataset): def __init__(self, *datasets): self.datasets = datasets def __getitem__(self, i): return tuple((d[i] for d in self.datasets)) def __len__(self): return min((len(d) for d in self.datasets))
def deprecated(message=''): def deprecated_decorator(function): (function) def wrapped(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn('{} will be deprecated in future release. {}'.format(function.__name__, message), category=DeprecationWar...
def grad_overflow(param_group): for group in param_group: for p in group: if (p.grad is not None): s = float(p.grad.data.float().sum()) if ((s == float('inf')) or (s == float('-inf')) or (s != s)): return True return False
.parametrize('space', [Discrete(3), Tuple([Discrete(5), Discrete(10)]), Tuple([Discrete(5), Box(low=np.array([0, 0]), high=np.array([1, 5]), dtype=np.float32)]), Tuple((Discrete(5), Discrete(2), Discrete(2))), MultiDiscrete([2, 2, 100]), MultiBinary(10), Dict({'position': Discrete(5), 'velocity': Box(low=np.array([0, 0...
def test_CBPM_neg_correlated_features(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None: X_neg = ['sepal_width'] trans_X_neg = CBPM(corr_sign='neg', agg_method=np.mean).fit_transform(X_iris[X_neg], y_iris) trans_X_neg_neg = CBPM(corr_sign='neg', agg_method=np.mean).fit_transform(X_iris, y_iris) trans_...
class EdgeAblationType(Enum): TRANSITIVE_REDUCTION = 'transitive-reduction' TRANSITIVE_CLOSURE = 'transitive-closure' ADD_LINEAR_EDGES = 'add-linear-edges' ONLY_LINEAR_EDGES = 'only-linear-edges' NO_EDGES = 'no-edges'
def landmark_ohem(landmark_pred, landmark_target, label): ones = tf.ones_like(label, dtype=tf.float32) zeros = tf.zeros_like(label, dtype=tf.float32) valid_inds = tf.where(tf.equal(label, (- 2)), ones, zeros) square_error = tf.square((landmark_pred - landmark_target)) square_error = tf.reduce_sum(sq...
def get_coverage(args): if (args.coverage == 'neuron_coverage'): coverage = MyNeuronCoverage(threshold=args.nc_threshold) elif (args.coverage == 'top_k_coverage'): coverage = TopKNeuronCoverage(k=10) elif (args.coverage == 'strong_coverage'): coverage = StrongNeuronActivationCoverage...
def convert_state_dict(src_dict): dst_dict = {} res_id = 1 map1 = ['conv1.', 'bn1.', ' ', 'conv2.', 'bn2.'] map2 = [[' ', 'conv3.', 'bn3.'], ['shortcut.conv.', 'shortcut.bn.']] for (k, v) in src_dict.items(): toks = k.split('.') if (int(toks[0]) == 0): name = ((('res%d.' ...
class IOSpiking(): boards = [] snips = [] chips = [] lmts = [] def __init__(self): self.board = None def snip(self, chip, lmt): for i in range(len(IOSpiking.snips)): if ((IOSpiking.boards[i] == self.board.id) and (IOSpiking.chips[i] == chip) and (IOSpiking.lmts[i] == ...
class LeakyRectify(object): def __init__(self, leakiness=0.01): self.leakiness = leakiness def __call__(self, x): if self.leakiness: f1 = (0.5 * (1 + self.leakiness)) f2 = (0.5 * (1 - self.leakiness)) return ((f1 * x) + (f2 * abs(x))) else: ...
def find_pareto_front(Y, return_index=False): if (len(Y) == 0): return np.array([]) sorted_indices = np.argsort(Y.T[0]) pareto_indices = [] for idx in sorted_indices: if (not np.logical_and((Y <= Y[idx]).all(axis=1), (Y < Y[idx]).any(axis=1)).any()): pareto_indices.append(idx...
class AdaptiveInput(nn.Module): def __init__(self, vocab_size: int, padding_idx: int, initial_dim: int, factor: float, output_dim: int, cutoff: List[int]): super().__init__() if (vocab_size > cutoff[(- 1)]): cutoff = (cutoff + [vocab_size]) else: assert (vocab_size ==...
def gen_events(): for template in gen_templates(): for events in expand(template): base = list(events) for i in range(0, (len(base) + 1)): cpy = list(base) cpy.insert(i, comment('comment')) (yield cpy)
def test_add_without_overwrite(data): arbitrary_sol = (data.solution + 1) low_objective = (data.objective - 1.0) add_info = data.archive_with_elite.add_single(arbitrary_sol, low_objective, data.measures) assert (add_info['status'] == AddStatus.NOT_ADDED) assert np.isclose(add_info['value'], (low_obj...
def create_example(text): raw_sentences = sent_tokenize(text) sentences = [word_tokenize(s) for s in raw_sentences] speakers = [['' for _ in sentence] for sentence in sentences] return {'doc_key': 'nw', 'clusters': [], 'sentences': sentences, 'speakers': speakers}
def parse_paths(inputs, postfix=None): postfix = ('' if (postfix is None) else postfix) if (inputs is None): return None input_paths = [] i = 0 while (i < len(inputs)): if os.path.isfile(inputs[i]): ext = os.path.splitext(inputs[i])[1] if (ext == '.txt'): ...
def GetSegment(fx, x, u, labels, segment_label): nfx = [] nx = [] nu = [] for i in range(len(labels)): if (labels[i] == segment_label): nfx += [fx[i]] nx += [x[i]] nu += [u[i]] return (nfx, nx, nu)
class Handler(SimpleHTTPRequestHandler): def do_GET(self): if (self.path == '/detindex'): self.send_str('\n'.join([p.name[:(- 5)] for p in Path('dets/').glob('*.json')])) elif self.path.startswith('/image'): path = self.translate_path(self.path).split('image') sel...
def vgg11_bn(pretrained=False, dataset_history=[], dataset2num_classes={}, **kwargs): if pretrained: kwargs['init_weights'] = False return VGG(make_layers(cfg['A'], batch_norm=True), dataset_history, dataset2num_classes, **kwargs)
class PixelActorCritic(nn.Module): def __init__(self, obs_shape, states_shape, actions_shape, initial_std, encoder_cfg, policy_cfg): super(PixelActorCritic, self).__init__() assert (encoder_cfg is not None) emb_dim = encoder_cfg['emb_dim'] self.obs_enc = Encoder(model_name=encoder_cf...
class RobertaOnnxConfig(OnnxConfig): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: if (self.task == 'multiple-choice'): dynamic_axis = {0: 'batch', 1: 'choice', 2: 'sequence'} else: dynamic_axis = {0: 'batch', 1: 'sequence'} return OrderedDict([('input_ids'...
def check_missing_backends(): missing_backends = [] if (not is_torch_available()): missing_backends.append('PyTorch') if (not is_tf_available()): missing_backends.append('TensorFlow') if (not is_flax_available()): missing_backends.append('Flax') if (len(missing_backends) > 0)...
def convert_gqa_to_vqa(gqa_dir, out_dir): image_feat_path = os.path.join(gqa_dir, 'images') extract_image_features(image_feat_path, out_dir) questions_dir = os.path.join(gqa_dir, 'questions') if os.path.isfile(os.path.join(questions_dir, 'train_all_questions.json')): print('Using previously gene...
def intrinsic_dimension_said(module, intrinsic_dimension, output_dir, str_filter, projection, device='cpu'): IntrinsicDimensionLight.apply(module, intrinsic_dimension, output_dir, str_filter, True, projection, device) return module
class Linear(fa_constructor.Linear): def __init__(self, in_features: int, out_features: int, bias: bool=True, layer_config: dict=None) -> None: if (layer_config is None): layer_config = {} layer_config['type'] = 'fa' super(Linear, self).__init__(in_features, out_features, bias, l...
def build_detection_test_loader(cfg, dataset_name, mapper=None): _add_category_whitelists_to_metadata(cfg) _add_category_maps_to_metadata(cfg) dataset_dicts = combine_detection_dataset_dicts([dataset_name], keep_instance_predicate=_get_test_keep_instance_predicate(cfg), proposal_files=([cfg.DATASETS.PROPOSA...
class Normalizer(object): CHECK_SYNC_COUNT = 50000 def __init__(self, sess, scope, size, init_mean=None, init_std=None, eps=0.01, clip=np.inf): self._sess = sess self._scope = scope self._eps = eps self._clip = clip self._mean = np.zeros(size) self._std = np.ones(...
def stage_data(snowflake_client: SnowflakeClient, snowflake_schema: str, snowflake_table: str, data_file: str, data_folder: str): sql_query = 'PUT file://{}/{} {}.%{} auto_compress=true overwrite=true'.format(data_folder, data_file, snowflake_schema.upper(), snowflake_table.upper()) return snowflake_client.exec...
class LogEntry(): def __init__(self, entry: Union[(dict, list)]): self._ = entry def __getattr__(self, name): if (name == '_'): return self.__dict__['_'] res = self.__dict__['_'][name] if ((type(res) == dict) or (type(res) == list)): return LogEntry(res) ...
class conv_synapse(SynapseModel): def __init__(self, conn, **kwargs): super(conv_synapse, self).__init__(conn) if (('bias_flag' in conn.__dict__.keys()) and conn.bias_flag): if (conn.post.model_name == 'complex'): self._syn_operations.append([(conn.post_var_name + '[post]...
class loadImgs(data.Dataset): def __init__(self, args, imgin_list, mode='demo'): self.imgin_list = imgin_list self.args = args self.mode = mode if self.args.use_gray: self.img_loader = gray_loader else: self.img_loader = rgb_loader self.data_li...
def get_category_info_from_anno(anno_file, with_background=True): cats = [] with open(anno_file) as f: for line in f.readlines(): cats.append(line.strip()) if ((cats[0] != 'background') and with_background): cats.insert(0, 'background') if ((cats[0] == 'background') and (not ...
class TFPegasusModel(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def data_aug_for_multiple_answers(example: Batch) -> Union[(Dict, Any)]: result = {key: [] for key in examples.keys()} def update(i, answers=None): for key in result.keys(): if ((key == 'answers') and (answers is not None)): result[key].append(answers) else: ...
def load(path, model_class, suffix=''): with io.open((path + '.config'), 'r', encoding='utf8') as f: config = json.load(f) word_voca = Vocabulary() word_voca.__dict__ = config['word_voca'] config['word_voca'] = word_voca entity_voca = Vocabulary() entity_voca.__dict__ = config['entity_vo...
def write_to_csv(title, data, target_path, dir_name): if (not os.path.exists(target_path)): os.makedirs(target_path) save_path = (((target_path + os.sep) + dir_name) + '.csv') with open(save_path, 'w', encoding='utf-8', newline='') as out_csv: csv_writer = csv.writer(out_csv) csv_wri...
class BaseOptions(): def __init__(self, cmd_line=None): self.initialized = False self.cmd_line = None if (cmd_line is not None): self.cmd_line = cmd_line.split() def initialize(self, parser): parser.add_argument('--name', type=str, default='face_recon', help='name of ...
class ResnetV2101(Model): def __init__(self): raise NotImplementedError('Resnet_V2_101 is not supported yet') def model_url(self) -> str: pass def package_name(self) -> str: pass
class RLAv3_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLAv3_Bottleneck, self).__init__() if (norm_layer is None): ...
class LARS(Regularizer): def __init__(self, model, value=0.01, weight_decay=0, dim=None, p=2, min_scale=None, max_scale=None, filter={'parameter_name': is_not_bias, 'module': is_not_bn}, **kwargs): super(LARS, self).__init__(model, value, filter=filter, **kwargs) self.weight_decay = weight_decay ...
def create_dataset(dataFrame, columns, filename, save_path='../data/raw'): dataset = dataFrame[columns].dropna() dataset = dataset.drop_duplicates() initial_size = dataset.shape[0] dataset.to_csv(os.path.join(save_path, filename), index=False) remove_strange_mols(os.path.join(save_path, filename), o...
class DDPG(object): def __init__(self, actor, critic, memory, observation_shape, action_shape, param_noise=None, action_noise=None, gamma=0.99, tau=0.001, normalize_returns=False, enable_popart=False, normalize_observations=True, batch_size=128, observation_range=((- 5.0), 5.0), action_range=((- 1.0), 1.0), return_...
def multi_gpu_launcher(commands): print('WARNING: using experimental multi_gpu_launcher.') n_gpus = torch.cuda.device_count() procs_by_gpu = ([None] * n_gpus) while (len(commands) > 0): for gpu_idx in range(n_gpus): proc = procs_by_gpu[gpu_idx] if ((proc is None) or (proc...
class BlipDiffusionControlNetPipeline(DiffusionPipeline): model_cpu_offload_seq = 'qformer->text_encoder->unet->vae' def __init__(self, tokenizer: CLIPTokenizer, text_encoder: ContextCLIPTextModel, vae: AutoencoderKL, unet: UNet2DConditionModel, scheduler: PNDMScheduler, qformer: Blip2QFormerModel, controlnet: ...
def block_optimizer(args, auxiliary_model, model_name, blocks_lr): model = auxiliary_model[model_name]['model'] group = [{'params': model.gat_layers[0].parameters(), 'lr': blocks_lr[0]}, {'params': model.gat_layers[1].parameters(), 'lr': blocks_lr[1]}, {'params': model.gat_layers[2].parameters(), 'lr': blocks_l...
_module() class CrossEntropyLoss(nn.Module): def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', class_weight=None, loss_weight=1.0): super(CrossEntropyLoss, self).__init__() assert ((use_sigmoid is False) or (use_mask is False)) self.use_sigmoid = use_sigmoid sel...
def read_image(filepath: str, mode: str='RGB') -> np.array: if (not os.path.isfile(filepath)): raise ValueError(f'Invalid file "{filepath}".') return Image.open(filepath).convert(mode)
def to_dict_helper(obj): return_data = [] for field_name in obj._fields: if (field_name in ('id',)): continue data = obj._data[field_name] if isinstance(obj._fields[field_name], StringField): return_data.append((field_name, str(data))) elif isinstance(obj....
class MetricType(Enum): KeyValue = 0 KeyValue_Numeric = 1 KeyValue_Categorical = 2 KeyValue_Mixed = 3 Numeric = 4 Categorical = 5 Mixed = 6 Unknown = 7 Empty = 8
def eval(args, model=None) -> SummarizationModule: Path(args.output_dir).mkdir(exist_ok=True) if ((len(os.listdir(args.output_dir)) > 3) and args.do_train): raise ValueError('Output directory ({}) already exists and is not empty.'.format(args.output_dir)) if (model is None): if ('summarizati...
def calcELStaeckel(R, vR, vT, z, vz, pot, vc=1.0, ro=1.0): return ((((_evaluatePotentials(pot, R, z) + ((vR ** 2.0) / 2.0)) + ((vT ** 2.0) / 2.0)) + ((vz ** 2.0) / 2.0)), (R * vT))
class ResNet(Convnet): def create_layers(self, shape, conv_before_args=None, res_args=None, conv_after_args=None, fc_args=None): (dim_x, dim_y, dim_in) = shape shape = (dim_x, dim_y, dim_in) (self.conv_before_layers, self.conv_before_shape) = self.create_conv_layers(shape, conv_before_args) ...
_ARCH_REGISTRY.register() class SemanticSegmentor(nn.Module): def __init__(self, *, backbone: Backbone, sem_seg_head: nn.Module, pixel_mean: Tuple[float], pixel_std: Tuple[float]): super().__init__() self.backbone = backbone self.sem_seg_head = sem_seg_head self.register_buffer('pixe...
class CvtForImageClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def attention(query, key, value, mask=None, dropout=None): d_k = query.size((- 1)) scores = (torch.matmul(query, key.transpose((- 2), (- 1))) / math.sqrt(d_k)) if (mask is not None): scores = scores.masked_fill((mask == 0), (- .0)) p_attn = F.softmax(scores, dim=(- 1)) if (dropout is not Non...
class Modfied_Loss(nn.modules.loss._Loss): def __init__(self): super(Modfied_Loss, self).__init__() def forward(self, outputs, labels): triplet_loss = TripletLoss(margin=1.2) cross_entropy_loss = nn.CrossEntropyLoss() Triplet_Loss = triplet_loss(outputs, labels) CrossEntr...
class BDEncoder(object): def __init__(self, cols=None): self.enc = BackwardDifferenceEncoder(cols=cols, verbose=1, drop_invariant=False, return_df=True, handle_unknown='value', handle_missing='value') def fit(self, X): with warnings.catch_warnings(): warnings.simplefilter('ignore') ...
def get_args_parser(): parser = argparse.ArgumentParser('MAE pre-training', add_help=False) parser.add_argument('--batch_size', default=64, type=int, help='Batch size per GPU (effective batch size = batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=400, type=int) parser.add_argu...
def dict_product(dicts): return (dict(zip(dicts, x)) for x in itertools.product(*dicts.values()))
def need_finetuning(ft_params, param_name): if (ft_params == 'all'): return True ft_params_list = ft_params.split(',') for ft_param in ft_params_list: if (ft_param in param_name): return True return False
def clean_csv(csvfile, basedir): input_dataframe = pd.read_csv(csvfile) newframe = datacleaner.autoclean(input_dataframe, drop_nans=False, copy=False, ignore_update_check=False) newfile = ('clean_' + csvfile) newframe.to_csv(newfile, index=False) return [newfile]
def map_midi_programs(feature, codec: Codec, granularity_type: str='full', feature_key: str='inputs') -> Mapping[(str, Any)]: granularity = PROGRAM_GRANULARITIES[granularity_type] feature[feature_key] = granularity.tokens_map_fn(feature[feature_key], codec) return feature
def tweet_features_main(reaction_status_json, source_tweet_user_screen_name, source_text) -> List: num_retweets = reaction_status_json['retweet_count'] num_favorites = (reaction_status_json['favorite_count'] if (reaction_status_json['favorite_count'] is not None) else 0) if ('full_text' in reaction_status_j...
def main(_): tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) tokenizer = tokenization.FullTokenizer(vocab_file=FLAGS.vocab_file, do_lower_case=True) eval_examples = read_squad_examples(input_file=FLAGS.predict_file, is_training=False) eval_writer = FeatureWriter(filename=FLAGS.output_file,...
def test_auto_fp16(): with pytest.raises(TypeError): class ExampleObject(): _fp16() def __call__(self, x): return x model = ExampleObject() input_x = torch.ones(1, dtype=torch.float32) model(input_x) class ExampleModule(nn.Module): ...
class GANLoss(nn.Module): def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0): super(GANLoss, self).__init__() self.register_buffer('real_label', torch.tensor(target_real_label)) self.register_buffer('fake_label', torch.tensor(target_fake_label)) self.gan_mode ...
def run(p, _log): p = munchify(p) torch.manual_seed(p.seed) np.random.seed(p.seed) random.seed(p.seed) if p.write_logs: setup_log_folder(p.log_folder, p.force) save_current_script(p.log_folder) (log, logger) = setup_logger((p.log_folder if p.write_logs else None)) log('{}'.fo...
class alexnet_base(nn.Module): def __init__(self): super(alexnet_base, self).__init__() self.base = models.alexnet(pretrained=True) self.classifier = nn.Sequential(*list(self.base.classifier.children())[:(- 1)]) def forward(self, x): out = self.base.features(x) out = out....
class TestResamplingDataset(unittest.TestCase): def setUp(self): self.strings = ['ab', 'c', 'def', 'ghij'] self.weights = [4.0, 2.0, 7.0, 1.5] self.size_ratio = 2 self.dataset = ListDataset(self.strings, np.array([len(s) for s in self.strings])) def _test_common(self, resampling_...
def create_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description='This programs creates the connectivity layers.') parser.add_argument('--raw_folder', type=str, help='Points to extracted data.', required=True, default='./data/raw') parser.add_argument('--output_folder', type=str,...
def _from_file(filename): with open(filename, 'r') as f: clustering = [] for line in f: splits = line.split('\t') (l, vec) = (int(splits[0]), np.array([float(x) for x in splits[1:]])) clustering.append((vec, l)) return clustering
class WindowedIterator(CheckpointableIterator): def __init__(self, source_iterator: CheckpointableIterator, width: int): if (not isinstance(source_iterator, CheckpointableIterator)): raise ValueError('source_iterator has to be a CheckpointableIterator') self._source_iterator = source_ite...
def build_optimizer(model, optim_cfg, logger, fixed=False): if (optim_cfg.OPTIMIZER == 'adam'): optimizer = optim.Adam(model.parameters(), lr=optim_cfg.LR, weight_decay=optim_cfg.WEIGHT_DECAY) elif (optim_cfg.OPTIMIZER == 'sgd'): optimizer = optim.SGD(model.parameters(), lr=optim_cfg.LR, weight_...
class TD3(object): def __init__(self, state_dim, action_dim, max_action): self.actor = Actor(state_dim, action_dim, max_action).to(device) self.actor_target = Actor(state_dim, action_dim, max_action).to(device) self.actor_target.load_state_dict(self.actor.state_dict()) self.actor_opt...
def sobel_cam(img): gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) grad_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3) grad_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3) abs_grad_x = cv2.convertScaleAbs(grad_x) abs_grad_y = cv2.convertScaleAbs(grad_y) grad = cv2.addWeighted(abs_grad_x, 0.5, abs_g...
def segmented_scatter_(dest, indices, start_indices, values): real_indices = (start_indices + indices) dest[real_indices] = values return dest
def main(args): if (args.seed is not None): random.seed(args.seed) torch.manual_seed(args.seed) cudnn.deterministic = True warnings.warn('You have chosen to seed training. This will turn on the CUDNN deterministic setting, which can slow down your training considerably! You may see u...
def time_me(function): def wrapped(*args, **kwargs): start = time.time() r = function(*args, **kwargs) end = time.time() return (r, ((end - start) * 1000)) return wrapped