code
stringlengths
17
6.64M
@pytest.mark.parametrize('model, initializer', [(model1, Uniform), (model2, KaimingNormal())]) def test_single_initializer(model, initializer): inp_weights = model.wide.wide_linear.weight.data.detach().cpu() n_model = c(model) trainer = Trainer(n_model, objective='binary', initializers=initializer) in...
def test_warning_when_missing_initializer(): wide = Wide(100, 1) deeptabular = TabMlp(column_idx=column_idx, cat_embed_input=embed_input, continuous_cols=colnames[(- 5):], mlp_hidden_dims=[32, 16], mlp_dropout=[0.5, 0.5]) deeptext = BasicRNN(vocab_size=vocab_size, embed_dim=32, padding_idx=0) model = ...
def test_optimizer_scheduler_format(): model = WideDeep(deeptabular=tabmlp) optimizers = {'deeptabular': torch.optim.Adam(model.deeptabular.parameters(), lr=0.01)} schedulers = torch.optim.lr_scheduler.StepLR(optimizers['deeptabular'], step_size=3) with pytest.raises(ValueError): trainer = Tra...
def test_non_instantiated_callbacks(): model = WideDeep(wide=wide, deeptabular=tabmlp) callbacks = [EarlyStopping] trainer = Trainer(model, objective='binary', callbacks=callbacks) assert (trainer.callbacks[2].__class__.__name__ == 'EarlyStopping')
def test_multiple_metrics(): model = WideDeep(wide=wide, deeptabular=tabmlp) metrics = [Accuracy, Precision] trainer = Trainer(model, objective='binary', metrics=metrics) assert ((trainer.metric._metrics[0].__class__.__name__ == 'Accuracy') and (trainer.metric._metrics[1].__class__.__name__ == 'Precis...
@pytest.mark.parametrize('wide, deeptabular', [(wide, tabmlp), (wide, tabresnet), (wide, tabtransformer)]) def test_basic_run_with_metrics_binary(wide, deeptabular): model = WideDeep(wide=wide, deeptabular=deeptabular) trainer = Trainer(model, objective='binary', metrics=[Accuracy], verbose=False) trainer...
def test_basic_run_with_metrics_multiclass(): wide = Wide(np.unique(X_wide).shape[0], 3) deeptabular = TabMlp(mlp_hidden_dims=[32, 16], mlp_dropout=[0.5, 0.5], column_idx={k: v for (v, k) in enumerate(colnames)}, cat_embed_input=embed_input, continuous_cols=colnames[(- 5):]) model = WideDeep(wide=wide, de...
@pytest.mark.parametrize('wide, deeptabular, deeptext, deepimage, X_wide, X_tab, X_text, X_img, target', [(wide, None, None, None, X_wide, None, None, None, target), (None, tabmlp, None, None, None, X_tab, None, None, target), (None, tabresnet, None, None, None, X_tab, None, None, target), (None, tabtransformer, None...
def test_save_and_load(): model = WideDeep(wide=wide, deeptabular=tabmlp) trainer = Trainer(model, objective='binary', verbose=0) trainer.fit(X_wide=X_wide, X_tab=X_tab, target=target, batch_size=16) wide_weights = model.wide.wide_linear.weight.data trainer.save('tests/test_model_functioning/model...
def test_save_and_load_dict(): wide = Wide(np.unique(X_wide).shape[0], 1) tabmlp = TabMlp(mlp_hidden_dims=[32, 16], column_idx={k: v for (v, k) in enumerate(colnames)}, cat_embed_input=embed_input, continuous_cols=colnames[(- 5):]) model1 = WideDeep(wide=deepcopy(wide), deeptabular=deepcopy(tabmlp)) t...
def test_save_load_and_predict(): fpath = 'tests/test_model_functioning/test_wd_model' if (not os.path.exists(fpath)): os.makedirs(fpath) model = WideDeep(deeptabular=tabmlp) trainer = Trainer(model, objective='binary', verbose=0) trainer.fit(X_tab=X_tab, target=target, batch_size=16) ...
def create_test_dataset(input_type, input_type_2=None): df = pd.DataFrame() col1 = list(np.random.choice(input_type, 32)) if (input_type_2 is not None): col2 = list(np.random.choice(input_type_2, 32)) else: col2 = list(np.random.choice(input_type, 32)) (df['col1'], df['col2']) = (c...
def test_handle_columns_with_dots(): data = df.copy() data = data.rename(columns={'col1': 'col.1', 'a': 'a.1'}) embed_cols = [('col.1', 5), ('col2', 5)] continuous_cols = ['col3', 'col4'] tab_preprocessor = TabPreprocessor(cat_embed_cols=embed_cols, continuous_cols=continuous_cols) X_tab = tab...
def test_lds_component_with_model(): model = WideDeep(deeptabular=tabmlp) trainer = Trainer(model, objective='regression', verbose=0) trainer.fit(X_tab=X_tab, target=target, with_lds=True) preds = trainer.predict(X_tab=X_tab) assert ((preds.shape[0] == 32) and ('train_loss' in trainer.history))
def test_lds_component_with_dataset(): dataset_with_lds = WideDeepDataset(X_tab=X_tab, target=target, with_lds=True) assert (dataset_with_lds.weights.shape[0] == 32)
def test_Trainer_extract_kwargs(): (lds_args, dataloader_args, finetune_args) = Trainer._extract_kwargs({'pin_memory': True, 'lds_ks': 7, 'n_epochs': 10}) assert (lds_args == {'lds_ks': 7}) assert (dataloader_args == {'pin_memory': True}) assert (finetune_args == {'n_epochs': 10})
@pytest.mark.parametrize('model_type', ['mlp', 'transformer']) @pytest.mark.parametrize('schedulers_type, len_loss_output, len_lr_output, init_lr', [('step', 5, 5, 0.001), ('cyclic', 5, 11, 0.001), ('reducelronplateau', 5, 5, 0.001)]) def test_lr_history(model_type, schedulers_type, len_loss_output, len_lr_output, in...
@pytest.mark.parametrize('model_type', ['mlp', 'transformer']) def test_early_stop(model_type): if (model_type == 'mlp'): model = TabMlp(column_idx=non_transf_preprocessor.column_idx, cat_embed_input=non_transf_preprocessor.cat_embed_input, continuous_cols=non_transf_preprocessor.continuous_cols, mlp_hidd...
@pytest.mark.parametrize('model_type', ['mlp', 'transformer']) @pytest.mark.parametrize('fpath, save_best_only, max_save, n_files', [('tests/test_self_supervised/weights/test_weights', True, 2, 2), ('tests/test_self_supervised/weights/test_weights', False, 2, 2), ('tests/test_self_supervised/weights/test_weights', Fa...
@pytest.mark.parametrize('model_type', ['mlp', 'transformer']) def test_save_and_load(model_type): if (model_type == 'mlp'): model = TabMlp(column_idx=non_transf_preprocessor.column_idx, cat_embed_input=non_transf_preprocessor.cat_embed_input, continuous_cols=non_transf_preprocessor.continuous_cols, mlp_h...
def _build_model_and_trainer(model_type): if (model_type == 'mlp'): model = TabMlp(column_idx=non_transf_preprocessor.column_idx, cat_embed_input=non_transf_preprocessor.cat_embed_input, continuous_cols=non_transf_preprocessor.continuous_cols, mlp_hidden_dims=[16, 8]) trainer = EncoderDecoderTrain...
@pytest.mark.parametrize('model_type', ['mlp', 'transformer']) def test_save_and_load_dict(model_type): (model1, trainer1) = _build_model_and_trainer(model_type) X = (X_tab if (model_type == 'mlp') else X_tab_transf) trainer1.pretrain(X, n_epochs=5, batch_size=16) if (model_type == 'mlp'): col...
def _build_enc_models(model_type, column_idx, cat_embed_input, continuous_cols): if (model_type == 'mlp'): encoder = TabMlpEncoder(column_idx=column_idx, cat_embed_input=cat_embed_input, continuous_cols=continuous_cols, mlp_hidden_dims=[16, 8]) if (model_type == 'resnet'): encoder = TabResnetE...
def _build_dec_models(model_type, encoder): if (model_type == 'mlp'): decoder = TabMlpDecoder(embed_dim=encoder.cat_and_cont_embed.output_dim, mlp_hidden_dims=[encoder.output_dim, (encoder.output_dim * 2)]) if (model_type == 'resnet'): decoder = TabResnetDecoder(embed_dim=encoder.cat_and_cont_...
@pytest.mark.parametrize('model_type', ['mlp', 'resnet', 'tabnet']) @pytest.mark.parametrize('cat_or_cont', ['cat', 'cont', 'both']) @pytest.mark.parametrize('decoder_model', ['custom', 'auto']) def test_enc_dec_trainer(model_type, cat_or_cont, decoder_model): cat_embed_cols = (['col1', 'col2'] if (cat_or_cont in...
@pytest.mark.parametrize('method_name', ['pretrain', 'fit']) def test_enc_dec_trainer_method_name(method_name): cat_embed_cols = ['col1', 'col2'] continuous_cols = ['col3', 'col4'] preprocessor = TabPreprocessor(cat_embed_cols=cat_embed_cols, continuous_cols=continuous_cols) X_tab = preprocessor.fit_t...
@pytest.mark.parametrize('transf_model', ['tabtransformer', 'saint', 'fttransformer', 'tabfastformer', 'contextattentionmlp', 'selfattentionmlp']) @pytest.mark.parametrize('cat_or_cont', ['cat', 'cont', 'both']) @pytest.mark.parametrize('with_cls_token', [True, False]) def test_cont_den_trainer_with_defaults(transf_m...
@pytest.mark.parametrize('method_name', ['pretrain', 'fit']) def test_cont_den_trainer_method_name(method_name): cat_embed_cols = ['col1', 'col2'] continuous_cols = ['col3', 'col4'] preprocessor = TabPreprocessor(cat_embed_cols=cat_embed_cols, continuous_cols=continuous_cols, with_attention=True, with_cls...
@pytest.mark.parametrize('loss_type', ['contrastive', 'denoising', 'both']) @pytest.mark.parametrize('proj_head_dims', [None, [32, 8]]) @pytest.mark.parametrize('mlp_type', ['single', 'multiple']) @pytest.mark.parametrize('with_cls_token', [True, False]) def test_cont_den_trainer_with_varying_params(loss_type, proj_h...
@pytest.mark.parametrize('proj_head_dims', [[None, [16, 8]], [[16, 8], None], [[16, 8], [16, 8]]]) def test_projection_head_value_error(proj_head_dims): cat_embed_cols = ['col1', 'col2'] continuous_cols = ['col3', 'col4'] preprocessor = TabPreprocessor(cat_embed_cols=cat_embed_cols, continuous_cols=contin...
def create_df(): cat_cols = [np.array(choices(c, k=5)) for c in [cat_col1_vals, cat_col2_vals]] cont_cols = [np.round(np.random.rand(5), 2) for _ in range(2)] target = [np.random.choice(2, 5, p=[0.8, 0.2])] return pd.DataFrame(np.vstack(((cat_cols + cont_cols) + target)).transpose(), columns=colnames)...
@pytest.mark.parametrize('deeptabular, return_dataframe', [(tabmlp, True), (tabmlp, False), (tabresnet, True), (tabresnet, False), (tabnet, True), (tabnet, False)]) def test_non_transformer_models(deeptabular, return_dataframe): model = WideDeep(deeptabular=deeptabular) t2v = Tab2Vec(model, tab_preprocessor, ...
def _build_model(model_name, params): if (model_name == 'tabtransformer'): return TabTransformer(input_dim=8, n_heads=2, n_blocks=2, **params) if (model_name == 'saint'): return SAINT(input_dim=8, n_heads=2, n_blocks=2, **params) if (model_name == 'fttransformer'): return FTTransfo...
@pytest.mark.parametrize('model_name, with_cls_token, share_embeddings, embed_continuous', [('tabtransformer', False, False, False), ('tabtransformer', True, False, False), ('tabtransformer', False, True, False), ('tabtransformer', True, False, True)]) def test_tab_transformer_models(model_name, with_cls_token, share...
@pytest.mark.parametrize('with_cls_token', [True, False]) @pytest.mark.parametrize('share_embeddings', [True, False]) @pytest.mark.parametrize('attention_name', ['context_attention', 'self_attention']) def test_attentive_mlp(with_cls_token, share_embeddings, attention_name): embed_cols = ['a', 'b'] cont_cols ...
@pytest.mark.parametrize('model_name, with_cls_token, share_embeddings, return_dataframe', [('saint', False, True, False), ('saint', True, True, False), ('saint', False, False, False), ('saint', False, True, True), ('saint', True, True, True), ('saint', False, False, True), ('fttransformer', False, True, False), ('ft...
class Evaluator(): ' Computes intersection and union between prediction and ground-truth ' @classmethod def initialize(cls): cls.ignore_index = 255 @classmethod def classify_prediction(cls, pred_mask, batch): gt_mask = batch.get('query_mask') query_ignore_idx = batch.get(...
class AverageMeter(): ' Stores loss, evaluation results ' def __init__(self, dataset): self.benchmark = dataset.benchmark self.class_ids_interest = dataset.class_ids self.class_ids_interest = torch.tensor(self.class_ids_interest).cuda() if (self.benchmark == 'pascal'): ...
class Logger(): ' Writes evaluation results of training/testing ' @classmethod def initialize(cls, args, training): logtime = datetime.datetime.now().__format__('_%m%d_%H%M%S') logpath = (args.logpath if training else (('_TEST_' + args.load.split('/')[(- 2)].split('.')[0]) + logtime)) ...
def fix_randseed(seed): ' Set random seeds for reproducibility ' if (seed is None): seed = int((random.random() * 100000.0)) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.benchmark = False torch.b...
def mean(x): return ((sum(x) / len(x)) if (len(x) > 0) else 0.0)
def to_cuda(batch): for (key, value) in batch.items(): if isinstance(value, torch.Tensor): batch[key] = value.cuda() return batch
def to_cpu(tensor): return tensor.detach().clone().cpu()
class DatasetCOCO(Dataset): def __init__(self, datapath, fold, transform, split, shot, use_original_imgsize): self.split = ('val' if (split in ['val', 'test']) else 'trn') self.fold = fold self.nfolds = 4 self.nclass = 80 self.benchmark = 'coco' self.shot = shot ...
class FSSDataset(): @classmethod def initialize(cls, img_size, datapath, use_original_imgsize): cls.datasets = {'pascal': DatasetPASCAL, 'coco': DatasetCOCO, 'fss': DatasetFSS} cls.img_mean = [0.485, 0.456, 0.406] cls.img_std = [0.229, 0.224, 0.225] cls.datapath = datapath ...
class DatasetFSS(Dataset): def __init__(self, datapath, fold, transform, split, shot, use_original_imgsize): self.split = split self.benchmark = 'fss' self.shot = shot self.base_path = os.path.join(datapath, 'FSS-1000') with open(('./data/splits/fss/%s.txt' % split), 'r') ...
class DatasetPASCAL(Dataset): def __init__(self, datapath, fold, transform, split, shot, use_original_imgsize): self.split = ('val' if (split in ['val', 'test']) else 'trn') self.fold = fold self.nfolds = 4 self.nclass = 20 self.benchmark = 'pascal' self.shot = sho...
class CenterPivotConv4d(nn.Module): ' CenterPivot 4D conv' def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=True): super(CenterPivotConv4d, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size[:2], stride=stride[:2], bias=bias, padding...
class Correlation(): @classmethod def multilayer_correlation(cls, query_feats, support_feats, stack_ids): eps = 1e-05 corrs = [] for (idx, (query_feat, support_feat)) in enumerate(zip(query_feats, support_feats)): (bsz, ch, hb, wb) = support_feat.size() support...
def extract_feat_vgg(img, backbone, feat_ids, bottleneck_ids=None, lids=None): ' Extract intermediate features from VGG ' feats = [] feat = img for (lid, module) in enumerate(backbone.features): feat = module(feat) if (lid in feat_ids): feats.append(feat.clone()) return...
def extract_feat_res(img, backbone, feat_ids, bottleneck_ids, lids): ' Extract intermediate features from ResNet' feats = [] feat = backbone.conv1.forward(img) feat = backbone.bn1.forward(feat) feat = backbone.relu.forward(feat) feat = backbone.maxpool.forward(feat) for (hid, (bid, lid)) i...
class HPNLearner(nn.Module): def __init__(self, inch): super(HPNLearner, self).__init__() def make_building_block(in_channel, out_channels, kernel_sizes, spt_strides, group=4): assert (len(out_channels) == len(kernel_sizes) == len(spt_strides)) building_block_layers = [] ...
def test(model, dataloader, nshot): ' Test HSNet ' utils.fix_randseed(0) average_meter = AverageMeter(dataloader.dataset) for (idx, batch) in enumerate(dataloader): batch = utils.to_cuda(batch) pred_mask = model.module.predict_mask_nshot(batch, nshot=nshot) assert (pred_mask.si...
def train(epoch, model, dataloader, optimizer, training): ' Train HSNet ' (utils.fix_randseed(None) if training else utils.fix_randseed(0)) (model.module.train_mode() if training else model.module.eval()) average_meter = AverageMeter(dataloader.dataset) for (idx, batch) in enumerate(dataloader): ...
class SSFetcher(threading.Thread): def __init__(self, parent): threading.Thread.__init__(self) self.parent = parent self.rng = numpy.random.RandomState(self.parent.seed) self.indexes = numpy.arange(parent.data_len) def run(self): diter = self.parent self.rng.s...
class SSIterator(object): def __init__(self, dialogue_file, batch_size, seed, max_len=(- 1), use_infinite_loop=True, dtype='int32'): self.dialogue_file = dialogue_file self.batch_size = batch_size args = locals() args.pop('self') self.__dict__.update(args) self.loa...
def sharedX(value, name=None, borrow=False, dtype=None): if (dtype is None): dtype = theano.config.floatX return theano.shared(theano._asarray(value, dtype=dtype), name=name, borrow=borrow)
def Adam(grads, lr=0.0002, b1=0.1, b2=0.001, e=1e-08): updates = [] i = sharedX(0.0) i_t = (i + 1.0) fix1 = (1.0 - ((1.0 - b1) ** i_t)) fix2 = (1.0 - ((1.0 - b2) ** i_t)) lr_t = (lr * (T.sqrt(fix2) / fix1)) for (p, g) in grads.items(): m = sharedX((p.get_value() * 0.0)) v =...
def safe_pickle(obj, filename): if os.path.isfile(filename): logger.info(('Overwriting %s.' % filename)) else: logger.info(('Saving to %s.' % filename)) with open(filename, 'wb') as f: cPickle.dump(obj, f, protocol=cPickle.HIGHEST_PROTOCOL)
class Model(object): def __init__(self): self.floatX = theano.config.floatX self.params = [] def save(self, filename): '\n Save the model to file `filename`\n ' vals = dict([(x.name, x.get_value()) for x in self.params]) numpy.savez(filename, **vals) ...
class Timer(object): def __init__(self): self.total = 0 def start(self): self.start_time = time.time() def finish(self): self.total += (time.time() - self.start_time)
def parse_args(): parser = argparse.ArgumentParser('Sample (with beam-search) from the session model') parser.add_argument('--ignore-unk', action='store_false', help='Allows generation procedure to output unknown words (<unk> tokens)') parser.add_argument('model_prefix', help='Path to the model prefix (wi...
def main(): args = parse_args() state = prototype_state() state_path = (args.model_prefix + '_state.pkl') model_path = (args.model_prefix + '_model.npz') with open(state_path) as src: state.update(cPickle.load(src)) logging.basicConfig(level=getattr(logging, state['level']), format='%(...
def safe_pickle(obj, filename): if os.path.isfile(filename): logger.info(('Overwriting %s.' % filename)) else: logger.info(('Saving to %s.' % filename)) with open(filename, 'wb') as f: cPickle.dump(obj, f, protocol=cPickle.HIGHEST_PROTOCOL)
def _itersplit(l, splitters): current = [] for item in l: if (item in splitters): (yield current) current = [] else: current.append(item) (yield current)
def magicsplit(l, *splitters): return [subl for subl in _itersplit(l, splitters) if subl]
def prototype_state(): state = {} state['seed'] = 1234 state['level'] = 'DEBUG' state['oov'] = '<unk>' state['end_sym_utterance'] = '</s>' state['unk_sym'] = 0 state['eos_sym'] = 1 state['eod_sym'] = 2 state['first_speaker_sym'] = 3 state['second_speaker_sym'] = 4 state['th...
def prototype_test(): state = prototype_state() state['train_dialogues'] = './tests/data/ttrain.dialogues.pkl' state['test_dialogues'] = './tests/data/ttest.dialogues.pkl' state['valid_dialogues'] = './tests/data/tvalid.dialogues.pkl' state['dictionary'] = './tests/data/ttrain.dict.pkl' state[...
def prototype_test_variational(): state = prototype_state() state['train_dialogues'] = './tests/data/ttrain.dialogues.pkl' state['test_dialogues'] = './tests/data/ttest.dialogues.pkl' state['valid_dialogues'] = './tests/data/tvalid.dialogues.pkl' state['dictionary'] = './tests/data/ttrain.dict.pkl...
def prototype_twitter_lstm(): state = prototype_state() state['train_dialogues'] = '../TwitterData/Training.dialogues.pkl' state['test_dialogues'] = '../TwitterData/Test.dialogues.pkl' state['valid_dialogues'] = '../TwitterData/Validation.dialogues.pkl' state['dictionary'] = '../TwitterData/Datase...
def prototype_twitter_HRED(): state = prototype_state() state['train_dialogues'] = '../TwitterData/Training.dialogues.pkl' state['test_dialogues'] = '../TwitterData/Test.dialogues.pkl' state['valid_dialogues'] = '../TwitterData/Validation.dialogues.pkl' state['dictionary'] = '../TwitterData/Datase...
def prototype_twitter_HRED_StandardBias(): state = prototype_state() state['train_dialogues'] = '../TwitterData/Training.dialogues.pkl' state['test_dialogues'] = '../TwitterData/Test.dialogues.pkl' state['valid_dialogues'] = '../TwitterData/Validation.dialogues.pkl' state['dictionary'] = '../Twitt...
def prototype_twitter_VHRED(): state = prototype_state() state['train_dialogues'] = '../TwitterData/Training.dialogues.pkl' state['test_dialogues'] = '../TwitterData/Test.dialogues.pkl' state['valid_dialogues'] = '../TwitterData/Validation.dialogues.pkl' state['dictionary'] = '../TwitterData/Datas...
def prototype_twitter_VHRED_StandardBias(): state = prototype_state() state['train_dialogues'] = '../TwitterData/Training.dialogues.pkl' state['test_dialogues'] = '../TwitterData/Test.dialogues.pkl' state['valid_dialogues'] = '../TwitterData/Validation.dialogues.pkl' state['dictionary'] = '../Twit...
def prototype_ubuntu_LSTM(): state = prototype_state() state['end_sym_utterance'] = '__eot__' state['unk_sym'] = 0 state['eos_sym'] = 1 state['eod_sym'] = (- 1) state['first_speaker_sym'] = (- 1) state['second_speaker_sym'] = (- 1) state['third_speaker_sym'] = (- 1) state['minor_sp...
def prototype_ubuntu_HRED(): state = prototype_state() state['end_sym_utterance'] = '__eot__' state['unk_sym'] = 0 state['eos_sym'] = 1 state['eod_sym'] = (- 1) state['first_speaker_sym'] = (- 1) state['second_speaker_sym'] = (- 1) state['third_speaker_sym'] = (- 1) state['minor_sp...
def prototype_ubuntu_VHRED(): state = prototype_state() state['end_sym_utterance'] = '__eot__' state['unk_sym'] = 0 state['eos_sym'] = 1 state['eod_sym'] = (- 1) state['first_speaker_sym'] = (- 1) state['second_speaker_sym'] = (- 1) state['third_speaker_sym'] = (- 1) state['minor_s...
def DPrint(name, var): if (PRINT_VARS is False): return var return theano.printing.Print(name)(var)
def sharedX(value, name=None, borrow=False, dtype=None): if (dtype is None): dtype = theano.config.floatX return theano.shared(theano._asarray(value, dtype=dtype), name=name, borrow=borrow)
def Adam(grads, lr=0.0002, b1=0.1, b2=0.001, e=1e-08): return adam.Adam(grads, lr, b1, b2, e)
def Adagrad(grads, lr): updates = OrderedDict() for param in grads.keys(): sum_square_grad = sharedX((param.get_value() * 0.0)) if (param.name is not None): sum_square_grad.name = ('sum_square_grad_' + param.name) new_sum_squared_grad = (sum_square_grad + T.sqr(grads[param]...
def Adadelta(grads, decay=0.95, epsilon=1e-06): updates = OrderedDict() for param in grads.keys(): mean_square_grad = sharedX((param.get_value() * 0.0)) mean_square_dx = sharedX((param.get_value() * 0.0)) if (param.name is not None): mean_square_grad.name = ('mean_square_gr...
def RMSProp(grads, lr, decay=0.95, eta=0.9, epsilon=1e-06): ' \n RMSProp gradient method\n ' updates = OrderedDict() for param in grads.keys(): mean_square_grad = sharedX((param.get_value() * 0.0)) mean_grad = sharedX((param.get_value() * 0.0)) delta_grad = sharedX((param.get...
class Maxout(object): def __init__(self, maxout_part): self.maxout_part = maxout_part def __call__(self, x): shape = x.shape if (x.ndim == 2): shape1 = T.cast((shape[1] / self.maxout_part), 'int64') shape2 = T.cast(self.maxout_part, 'int64') x = x....
def UniformInit(rng, sizeX, sizeY, lb=(- 0.01), ub=0.01): ' Uniform Init ' return rng.uniform(size=(sizeX, sizeY), low=lb, high=ub).astype(theano.config.floatX)
def OrthogonalInit(rng, sizeX, sizeY, sparsity=(- 1), scale=1): ' \n Orthogonal Initialization\n ' sizeX = int(sizeX) sizeY = int(sizeY) assert (sizeX == sizeY), 'for orthogonal init, sizeX == sizeY' if (sparsity < 0): sparsity = sizeY else: sparsity = numpy.minimum(sizeY...
def GrabProbs(classProbs, target, gRange=None): if (classProbs.ndim > 2): classProbs = classProbs.reshape(((classProbs.shape[0] * classProbs.shape[1]), classProbs.shape[2])) else: classProbs = classProbs if (target.ndim > 1): tflat = target.flatten() else: tflat = targe...
def NormalInit(rng, sizeX, sizeY, scale=0.01, sparsity=(- 1)): ' \n Normal Initialization\n ' sizeX = int(sizeX) sizeY = int(sizeY) if (sparsity < 0): sparsity = sizeY sparsity = numpy.minimum(sizeY, sparsity) values = numpy.zeros((sizeX, sizeY), dtype=theano.config.floatX) f...
def ConvertTimedelta(seconds_diff): hours = (seconds_diff // 3600) minutes = ((seconds_diff % 3600) // 60) seconds = (seconds_diff % 60) return (hours, minutes, seconds)
def SoftMax(x): x = T.exp((x - T.max(x, axis=(x.ndim - 1), keepdims=True))) return (x / T.sum(x, axis=(x.ndim - 1), keepdims=True))
def VariableNormalization(x, mask=None, axes=0): if mask: mask = mask.dimshuffle(0, 1, 'x') x_masked = (x * mask) average = (T.sum(x_masked, axis=axes) / T.sum(mask, axis=axes)) if (average.ndim == 1): x_zero_average = (x_masked - average.dimshuffle('x', 'x', 0)) ...
@jit def function(x): return x
@njit def njit_f(x): return x
@jit('int32(int32, int32)') def int32_sum(a, b): return (a + b)
@jit def int32_sum_r1(a: int, b: int): return (a + b)
def list_norm_inplace(buff): r_mean = np.mean(buff) r_std = np.std(buff) for ii in range(len(buff)): buff[ii] = ((buff[ii] - r_mean) / r_std)
def plot_durations(episode_durations): plt.figure(2) plt.clf() durations_t = TC.FloatTensor(episode_durations) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) if (len(durations_t) >= 100): means = durations_t.unfold(0, 100, 1)...
def plot_durations_ii(ii, episode_durations, ee, ee_duration=100): episode_durations.append((ii + 1)) if (((ee + 1) % ee_duration) == 0): clear_output() plot_durations(episode_durations)
class PGNET(nn.Module): def __init__(self, num_state): super(PGNET, self).__init__() self.fc_in = nn.Linear(num_state, 24) self.fc_hidden = nn.Linear(24, 36) self.fc_out = nn.Linear(36, 1) def forward(self, x): x = F.relu(self.fc_in(x)) x = F.relu(self.fc_hidd...
class PGNET_AGENT(PGNET): def run(self, env): for ee in range(self.num_episode): self.run_episode(env, ee) self.train_episode(ee)