code
stringlengths
17
6.64M
class NormAdd(nn.Module): 'aka PreNorm' def __init__(self, input_dim: int, dropout: float): super(NormAdd, self).__init__() self.dropout = nn.Dropout(dropout) self.ln = nn.LayerNorm(input_dim) def forward(self, X: Tensor, sublayer: nn.Module) -> Tensor: return (X + self.d...
class AddNorm(nn.Module): 'aka PosNorm' def __init__(self, input_dim: int, dropout: float): super(AddNorm, self).__init__() self.dropout = nn.Dropout(dropout) self.ln = nn.LayerNorm(input_dim) def forward(self, X: Tensor, sublayer: nn.Module) -> Tensor: return self.ln((X ...
class MultiHeadedAttention(nn.Module): def __init__(self, input_dim: int, n_heads: int, use_bias: bool, dropout: float, query_dim: Optional[int]=None, use_linear_attention: bool=False, use_flash_attention: bool=False): super(MultiHeadedAttention, self).__init__() assert ((input_dim % n_heads) == ...
class LinearAttentionLinformer(nn.Module): 'Linear Attention implementation from [Linformer: Self-Attention with\n Linear Complexity](https://arxiv.org/abs/2006.04768)\n ' def __init__(self, input_dim: int, n_feats: int, n_heads: int, use_bias: bool, dropout: float, kv_compression_factor: float, kv_sha...
class AdditiveAttention(nn.Module): 'Additive Attention Implementation from [FastFormer]\n (https://arxiv.org/abs/2108.09084)\n ' def __init__(self, input_dim: int, n_heads: int, use_bias: bool, dropout: float, share_qv_weights: bool): super(AdditiveAttention, self).__init__() assert ((...
class TransformerEncoder(nn.Module): def __init__(self, input_dim: int, n_heads: int, use_bias: bool, attn_dropout: float, ff_dropout: float, ff_factor: int, activation: str, use_linear_attention: bool, use_flash_attention: bool): super(TransformerEncoder, self).__init__() self.attn = MultiHeaded...
class SaintEncoder(nn.Module): def __init__(self, input_dim: int, n_heads: int, use_bias: bool, attn_dropout: float, ff_dropout: float, ff_factor: int, activation: str, n_feat: int): super(SaintEncoder, self).__init__() self.n_feat = n_feat self.col_attn = MultiHeadedAttention(input_dim, ...
class FTTransformerEncoder(nn.Module): def __init__(self, input_dim: int, n_feats: int, n_heads: int, use_bias: bool, attn_dropout: float, ff_dropout: float, ff_factor: float, kv_compression_factor: float, kv_sharing: bool, activation: str, first_block: bool): super(FTTransformerEncoder, self).__init__()...
class PerceiverEncoder(nn.Module): def __init__(self, input_dim: int, n_heads: int, use_bias: bool, attn_dropout: float, ff_dropout: float, ff_factor: int, activation: str, query_dim: Optional[int]=None): super(PerceiverEncoder, self).__init__() self.attn = MultiHeadedAttention(input_dim, n_heads...
class FastFormerEncoder(nn.Module): def __init__(self, input_dim: int, n_heads: int, use_bias: bool, attn_dropout: float, ff_dropout: float, ff_factor: int, share_qv_weights: bool, activation: str): super(FastFormerEncoder, self).__init__() self.attn = AdditiveAttention(input_dim, n_heads, use_bi...
class TabPerceiver(BaseTabularModelWithAttention): 'Defines an adaptation of a [Perceiver](https://arxiv.org/abs/2103.03206)\n that can be used as the `deeptabular` component of a Wide & Deep model\n or independently by itself.\n\n :information_source: **NOTE**: while there are scientific publications ...
class ContextAttentionEncoder(nn.Module): def __init__(self, rnn: nn.Module, input_dim: int, attn_dropout: float, attn_concatenate: bool, with_addnorm: bool, sum_along_seq: bool): super(ContextAttentionEncoder, self).__init__() self.rnn = rnn self.bidirectional = self.rnn.bidirectional ...
class AttentiveRNN(BasicRNN): 'Text classifier/regressor comprised by a stack of RNNs\n (LSTMs or GRUs) plus an attention layer. This model can be used as the\n `deeptext` component of a Wide & Deep model or independently by\n itself.\n\n In addition, there is the option to add a Fully Connected (FC) ...
class BasicRNN(BaseWDModelComponent): 'Standard text classifier/regressor comprised by a stack of RNNs\n (LSTMs or GRUs) that can be used as the `deeptext` component of a Wide &\n Deep model or independently by itself.\n\n In addition, there is the option to add a Fully Connected (FC) set of\n dense l...
class StackedAttentiveRNN(BaseWDModelComponent): 'Text classifier/regressor comprised by a stack of blocks:\n `[RNN + Attention]`. This can be used as the `deeptext` component of a\n Wide & Deep model or independently by itself.\n\n In addition, there is the option to add a Fully Connected (FC) set of\n ...
class WideDeep(nn.Module): 'Main collector class that combines all `wide`, `deeptabular`\n `deeptext` and `deepimage` models.\n\n Note that all models described so far in this library must be passed to\n the `WideDeep` class once constructed. This is because the models output\n the last layer before t...
class BasePreprocessor(): 'Base Class of All Preprocessors.' def __init__(self, *args): pass def fit(self, df: pd.DataFrame): raise NotImplementedError('Preprocessor must implement this method') def transform(self, df: pd.DataFrame): raise NotImplementedError('Preprocessor m...
def check_is_fitted(estimator: Union[(BasePreprocessor, Any)], attributes: List[str]=None, all_or_any: str='all', condition: bool=True): 'Checks if an estimator is fitted\n\n Parameters\n ----------\n estimator: ``BasePreprocessor``,\n An object of type ``BasePreprocessor``\n attributes: List, ...
class ImagePreprocessor(BasePreprocessor): "Preprocessor to prepare the ``deepimage`` input dataset.\n\n The Preprocessing consists simply on resizing according to their\n aspect ratio\n\n Parameters\n ----------\n img_col: str\n name of the column with the images filenames\n img_path: st...
def embed_sz_rule(n_cat: int, embedding_rule: Literal[('google', 'fastai_old', 'fastai_new')]='fastai_new') -> int: "Rule of thumb to pick embedding size corresponding to ``n_cat``. Default rule is taken\n from recent fastai's Tabular API. The function also includes previously used rule by fastai\n and rule...
class Quantizer(): "Helper class to perform the quantization of continuous columns. It is\n included in this docs for completion, since depending on the value of the\n parameter `'quantization_setup'` of the `TabPreprocessor` class, that\n class might have an attribute of type `Quantizer`. However, this ...
class TabPreprocessor(BasePreprocessor): 'Preprocessor to prepare the `deeptabular` component input dataset\n\n Parameters\n ----------\n cat_embed_cols: List, default = None\n List containing the name of the categorical columns that will be\n represented by embeddings (e.g. _[\'education\'...
class ChunkTabPreprocessor(TabPreprocessor): 'Preprocessor to prepare the `deeptabular` component input dataset\n\n Parameters\n ----------\n n_chunks: int\n Number of chunks that the tabular dataset is divided by.\n cat_embed_cols: List, default = None\n List containing the name of the ...
class TextPreprocessor(BasePreprocessor): 'Preprocessor to prepare the ``deeptext`` input dataset\n\n Parameters\n ----------\n text_col: str\n column in the input dataframe containing the texts\n max_vocab: int, default=30000\n Maximum number of tokens in the vocabulary\n min_freq: i...
class ChunkTextPreprocessor(TextPreprocessor): 'Preprocessor to prepare the ``deeptext`` input dataset\n\n Parameters\n ----------\n text_col: str\n column in the input dataframe containing either the texts or the\n filenames where the text documents are stored\n n_chunks: int\n N...
class BaseContrastiveDenoisingTrainer(ABC): def __init__(self, model: ModelWithAttention, preprocessor: TabPreprocessor, optimizer: Optional[Optimizer], lr_scheduler: Optional[LRScheduler], callbacks: Optional[List[Callback]], loss_type: Literal[('contrastive', 'denoising', 'both')], projection_head1_dims: Optio...
class BaseEncoderDecoderTrainer(ABC): def __init__(self, encoder: ModelWithoutAttention, decoder: DecoderWithoutAttention, masked_prob: float, optimizer: Optional[Optimizer], lr_scheduler: Optional[LRScheduler], callbacks: Optional[List[Callback]], verbose: int, seed: int, **kwargs): (self.device, self.n...
class ContrastiveDenoisingTrainer(BaseContrastiveDenoisingTrainer): 'This class trains a Contrastive, Denoising Self Supervised \'routine\' that\n is based on the one described in\n [SAINT: Improved Neural Networks for Tabular Data via Row Attention and\n Contrastive Pre-Training](https://arxiv.org/abs/2...
class EncoderDecoderTrainer(BaseEncoderDecoderTrainer): "This class implements an Encoder-Decoder self-supervised 'routine'\n inspired by\n [TabNet: Attentive Interpretable Tabular Learning](https://arxiv.org/abs/1908.07442).\n See Figure 1 above.\n\n Parameters\n ----------\n encoder: ModelWith...
class BaseBayesianTrainer(ABC): def __init__(self, model: BaseBayesianModel, objective: str, custom_loss_function: Optional[Module], optimizer: Optimizer, lr_scheduler: LRScheduler, callbacks: Optional[List[Callback]], metrics: Optional[Union[(List[Metric], List[TorchMetric])]], verbose: int, seed: int, **kwargs...
class BaseTrainer(ABC): def __init__(self, model: WideDeep, objective: str, custom_loss_function: Optional[Module], optimizers: Optional[Union[(Optimizer, Dict[(str, Optimizer)])]], lr_schedulers: Optional[Union[(LRScheduler, Dict[(str, LRScheduler)])]], initializers: Optional[Union[(Initializer, Dict[(str, Init...
class FineTune(): 'Fine-tune methods to be applied to the individual model components.\n\n Note that they can also be used to "warm-up" those components before\n the joined training.\n\n There are 3 fine-tune/warm-up routines available:\n\n 1) Fine-tune all trainable layers at once\n\n 2) Gradual f...
class classproperty(): "In python 3.9 you can just use\n\n @classmethod\n @property\n\n Given that we support 3.7, 3.8 as well as 3.9, let's use this hack\n " def __init__(self, func): self.func = func def __get__(self, decorated_self, decorated_cls): return self.func(decorat...
class _LossAliases(): loss_aliases = {'binary': ['binary', 'logistic', 'binary_logloss', 'binary_cross_entropy'], 'multiclass': ['multiclass', 'multi_logloss', 'cross_entropy', 'categorical_cross_entropy'], 'regression': ['regression', 'mse', 'l2', 'mean_squared_error'], 'mean_absolute_error': ['mean_absolute_err...
class _ObjectiveToMethod(): objective_to_method = {'binary': 'binary', 'logistic': 'binary', 'binary_logloss': 'binary', 'binary_cross_entropy': 'binary', 'binary_focal_loss': 'binary', 'multiclass': 'multiclass', 'multi_logloss': 'multiclass', 'cross_entropy': 'multiclass', 'categorical_cross_entropy': 'multicla...
class MultipleLRScheduler(object): def __init__(self, scheds: Dict[(str, LRScheduler)]): self._schedulers = scheds def step(self): for (_, sc) in self._schedulers.items(): sc.step()
class MultipleOptimizer(object): def __init__(self, opts: Dict[(str, Optimizer)]): self._optimizers = opts def zero_grad(self): for (_, op) in self._optimizers.items(): op.zero_grad() def step(self): for (_, op) in self._optimizers.items(): op.step()
class MultipleTransforms(object): def __init__(self, transforms: List[Transforms]): instantiated_transforms = [] for transform in transforms: if isinstance(transform, type): instantiated_transforms.append(transform()) else: instantiated_tran...
def tabular_train_val_split(seed: int, method: str, X: np.ndarray, y: np.ndarray, X_val: Optional[np.ndarray]=None, y_val: Optional[np.ndarray]=None, val_split: Optional[float]=None): "\n Function to create the train/val split for the BayesianTrainer where only\n tabular data is used\n\n Parameters\n ...
def wd_train_val_split(seed: int, method: str, X_wide: Optional[np.ndarray]=None, X_tab: Optional[np.ndarray]=None, X_text: Optional[np.ndarray]=None, X_img: Optional[np.ndarray]=None, X_train: Optional[Dict[(str, np.ndarray)]]=None, X_val: Optional[Dict[(str, np.ndarray)]]=None, val_split: Optional[float]=None, targ...
def _build_train_dict(X_wide, X_tab, X_text, X_img, target): X_train = {'target': target} if (X_wide is not None): X_train['X_wide'] = X_wide if (X_tab is not None): X_train['X_tab'] = X_tab if (X_text is not None): X_train['X_text'] = X_text if (X_img is not None): ...
def print_loss_and_metric(pb: tqdm, loss: float, score: Optional[Dict]=None): "\n Function to improve readability and avoid code repetition in the\n training/validation loop within the Trainer's fit method\n\n Parameters\n ----------\n pb: tqdm\n tqdm object defined as trange(...)\n loss:...
def save_epoch_logs(epoch_logs: Dict, loss: float, score: Dict, stage: str): "\n Function to improve readability and avoid code repetition in the\n training/validation loop within the Trainer's fit method\n\n Parameters\n ----------\n epoch_logs: Dict\n Dict containing the epoch logs\n lo...
def bayesian_alias_to_loss(loss_fn: str, **kwargs): 'Function that returns the corresponding loss function given an alias.\n To be used with the ``BayesianTrainer``\n\n Parameters\n ----------\n loss_fn: str\n Loss name\n\n Returns\n -------\n Object\n loss function\n\n Examp...
def alias_to_loss(loss_fn: str, **kwargs): 'Function that returns the corresponding loss function given an alias\n\n Parameters\n ----------\n loss_fn: str\n Loss name or alias\n\n Returns\n -------\n Object\n loss function\n\n Examples\n --------\n >>> from pytorch_widede...
class LabelEncoder(): 'Label Encode categorical values for multiple columns at once\n\n :information_source: **NOTE**:\n LabelEncoder reserves 0 for `unseen` new categories. This is convenient\n when defining the embedding layers, since we can just set padding idx to 0.\n\n Parameters\n ----------\...
def find_bin(bin_edges: Union[(np.ndarray, Tensor)], values: Union[(np.ndarray, Tensor)], ret_value: bool=True) -> Union[(np.ndarray, Tensor)]: "Returns indices that are the results of applying the 'searchsorted' algo\n to 'bin_edges' and 'values' or the left edge of the bins (i.e. bin_edges[indices])\n\n P...
def _laplace(x, sigma: Union[(int, float)]=2): return (np.exp(((- abs(x)) / sigma)) / (2.0 * sigma))
def get_kernel_window(kernel: Literal[('gaussian', 'triang', 'laplace')]='gaussian', ks: int=5, sigma: Union[(int, float)]=2) -> List[float]: "Procedure to prepare the window of values from symetrical kernel function\n for smoothing of the distribution in Label and Feature Distribution\n Smoothing (LDS & FD...
def partition(a: Collection, sz: int) -> List[Collection]: 'Split iterables `a` in equal parts of size `sz`' return [a[i:(i + sz)] for i in range(0, len(a), sz)]
def partition_by_cores(a: Collection, n_cpus: int) -> List[Collection]: 'Split data in `a` equally among `n_cpus` cores' return partition(a, ((len(a) // n_cpus) + 1))
def ifnone(a: Any, b: Any) -> Any: '`a` if `a` is not None, otherwise `b`.' return (b if (a is None) else a)
def num_cpus() -> Optional[int]: 'Get number of cpus' try: return len(os.sched_getaffinity(0)) except AttributeError: return os.cpu_count()
class BaseTokenizer(): 'Basic class for a tokenizer function.' def __init__(self, lang: str): self.lang = lang def tokenizer(self, t: str) -> List[str]: return t.split(' ') def add_special_cases(self, toks: Collection[str]): pass
class SpacyTokenizer(BaseTokenizer): def __init__(self, lang: str): 'Wrapper around a spacy tokenizer to make it a :obj:`BaseTokenizer`.\n\n Parameters\n ----------\n lang: str\n Language of the text to be tokenized\n ' self.tok = spacy.blank(lang) def ...
def spec_add_spaces(t: str) -> str: 'Add spaces around / and # in `t`. \n' return re.sub('([/#\\n])', ' \\1 ', t)
def rm_useless_spaces(t: str) -> str: 'Remove multiple spaces in `t`.' return re.sub(' {2,}', ' ', t)
def replace_rep(t: str) -> str: 'Replace repetitions at the character level in `t`.' def _replace_rep(m: Match[str]) -> str: (c, cc) = m.groups() return f' {TK_REP} {(len(cc) + 1)} {c} ' re_rep = re.compile('(\\S)(\\1{3,})') return re_rep.sub(_replace_rep, t)
def replace_wrep(t: str) -> str: 'Replace word repetitions in `t`.' def _replace_wrep(m: Match[str]) -> str: (c, cc) = m.groups() return f' {TK_WREP} {(len(cc.split()) + 1)} {c} ' re_wrep = re.compile('(\\b\\w+\\W+)(\\1{3,})') return re_wrep.sub(_replace_wrep, t)
def fix_html(x: str) -> str: 'List of replacements from html strings in `x`.' re1 = re.compile(' +') x = x.replace('#39;', "'").replace('amp;', '&').replace('#146;', "'").replace('nbsp;', ' ').replace('#36;', '$').replace('\\n', '\n').replace('quot;', "'").replace('<br />', '\n').replace('\\"', '"').repl...
def replace_all_caps(x: Collection[str]) -> Collection[str]: 'Replace tokens in ALL CAPS in `x` by their lower version and add `TK_UP` before.' res = [] for t in x: if (t.isupper() and (len(t) > 1)): res.append(TK_UP) res.append(t.lower()) else: res.appe...
def deal_caps(x: Collection[str]) -> Collection[str]: 'Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before.' res = [] for t in x: if (t == ''): continue if (t[0].isupper() and (len(t) > 1) and t[1:].islower()): res.append(TK_MAJ) ...
class Tokenizer(): 'Class to combine a series of rules and a tokenizer function to tokenize\n text with multiprocessing.\n\n Setting some of the parameters of this class require perhaps some\n familiarity with the source code.\n\n Parameters\n ----------\n tok_func: Callable, default = ``SpacyTo...
class Vocab(): "Contains the correspondence between numbers and tokens.\n\n Parameters\n ----------\n max_vocab: int\n maximum vocabulary size\n min_freq: int\n minimum frequency for a token to be considereds\n pad_idx: int, Optional, default = None\n padding index. If `None`, ...
class ChunkVocab(): def __init__(self, max_vocab: int, min_freq: int, n_chunks: int, pad_idx: Optional[int]=None): self.max_vocab = max_vocab self.min_freq = min_freq self.n_chunks = n_chunks self.pad_idx = pad_idx self.chunk_counter = 0 self.is_fitted = False ...
class Alias(): def __init__(self, primary_name: str, aliases: Union[(str, List[str])]): 'Convert uses of `aliases` to `primary_name` upon calling the decorated\n function/method\n\n Parameters\n ----------\n primary_name: String\n Preferred name for the parameter, t...
def set_default_attr(obj: Any, name: str, value: Any): 'Set the `name` attribute of `obj` to `value` if the attribute does not\n already exist\n\n Parameters\n ----------\n obj: Object\n Object whose `name` attribute will be returned (after setting it to\n `value`, if necessary)\n nam...
def simple_preprocess(doc: str, lower: bool=False, deacc: bool=False, min_len: int=2, max_len: int=15) -> List[str]: "\n This is `Gensim`'s `simple_preprocess` with a `lower` param to\n indicate wether or not to lower case all the token in the doc\n\n For more information see: `Gensim` [utils module](htt...
def get_texts(texts: List[str], already_processed: Optional[bool]=False, n_cpus: Optional[int]=None) -> List[List[str]]: "Tokenization using `Fastai`'s `Tokenizer` because it does a\n series of very convenients things during the tokenization process\n\n See `pytorch_widedeep.utils.fastai_utils.Tokenizer`\n\...
def pad_sequences(seq: List[int], maxlen: int, pad_first: bool=True, pad_idx: int=1) -> np.ndarray: "\n Given a List of tokenized and `numericalised` sequences it will return\n padded sequences according to the input parameters.\n\n Parameters\n ----------\n seq: List\n List of int with the ...
def build_embeddings_matrix(vocab: Union[(Vocab, ChunkVocab)], word_vectors_path: str, min_freq: int, verbose: int=1) -> np.ndarray: 'Build the embedding matrix using pretrained word vectors.\n\n Returns pretrained word embeddings. If a word in our vocabulary is not\n among the pretrained embeddings it will...
def requirements(fname): return [line.strip() for line in open(os.path.join(os.path.dirname(__file__), fname))]
def test_mse_based_losses(): y_true = np.array([3, 5, 2.5, 7]).reshape((- 1), 1) y_pred = np.array([2.5, 5, 4, 8]).reshape((- 1), 1) t_true = torch.from_numpy(y_true) t_pred = torch.from_numpy(y_pred) are_close = np.isclose(mean_squared_error(y_true, y_pred), (BayesianSELoss()(t_pred, t_true).item...
def test_wide(): out = model(inp) assert ((out.size(0) == 10) and (out.size(1) == 1))
@pytest.mark.parametrize('model', [bwide, btabmlp]) @pytest.mark.parametrize('scheduler_name', ['step', 'cyclic']) def test_history_callback(model, scheduler_name): init_lr = 0.001 optimizer = torch.optim.Adam(model.parameters(), lr=init_lr) if (scheduler_name == 'cyclic'): scheduler = CyclicLR(op...
@pytest.mark.parametrize('model', [bwide, btabmlp]) def test_early_stop(model): btrainer = BayesianTrainer(model=model, objective='binary', callbacks=[EarlyStopping(min_delta=10000.0, patience=3, restore_best_weights=True, verbose=1)], verbose=0) btrainer.fit(X_tab=X_tab, target=target, val_split=0.2, n_epoch...
@pytest.mark.parametrize('fpath, save_best_only, max_save, n_files', [('tests/test_bayesian_models/test_model_functioning/weights/test_weights', True, 2, 2), ('tests/test_bayesian_models/test_model_functioning/weights/test_weights', False, 2, 2), ('tests/test_bayesian_models/test_model_functioning/weights/test_weight...
def test_filepath_error(): btabmlp = BayesianTabMlp(column_idx=column_idx, cat_embed_input=embed_input, continuous_cols=colnames[(- 5):], mlp_hidden_dims=[16, 4]) with pytest.raises(ValueError): trainer = BayesianTrainer(model=btabmlp, objective='binary', callbacks=[ModelCheckpoint(filepath='wrong_fil...
@pytest.mark.parametrize('model, X_tab, target, X_tab_val, target_val , val_split', [(wide, X_wide, target, None, None, 0.2), (wide, X_wide_tr, y_train, X_wide_val, y_val, None), (tabmlp, X_tabmlp, target, None, None, 0.2), (tabmlp, X_tabmlp_tr, y_train, X_tabmlp_val, y_val, None)]) def test_data_input_options(model,...
@pytest.mark.parametrize('model_name', ['wide', 'tabmlp']) @pytest.mark.parametrize('objective', ['binary', 'multiclass']) @pytest.mark.parametrize('return_samples', [True, False]) @pytest.mark.parametrize('embed_continuous', [True, False]) def test_classification(model_name, objective, return_samples, embed_continuo...
@pytest.mark.parametrize('model_name', ['wide', 'tabmlp']) @pytest.mark.parametrize('return_samples', [True, False]) def test_regression(model_name, return_samples): bsz = 32 n_samples = 5 if (model_name == 'wide'): X_tab = X_wide model = BayesianWide(np.unique(X_wide).shape[0], 1) eli...
@pytest.mark.parametrize('model', [bwide, btabmlp]) def test_save_and_load(model): btrainer = BayesianTrainer(model=model, objective='binary', verbose=0) X = (X_wide if (model.__class__.__name__ == 'BayesianWide') else X_tab) btrainer.fit(X_tab=X, target=target, n_epochs=5, batch_size=16) if (model.__...
@pytest.mark.parametrize('model_name', ['wide', 'tabmlp']) def test_save_and_load_dict(model_name): (model1, btrainer1) = _build_model_and_trainer(model_name) X = (X_wide if (model_name == 'wide') else X_tab) btrainer1.fit(X_tab=X, target=target, n_epochs=5, batch_size=16) btrainer1.save('tests/test_b...
def _build_model_and_trainer(model_name): if (model_name == 'wide'): model = BayesianWide(np.unique(X_wide).shape[0], 1) elif (model_name == 'tabmlp'): model = BayesianTabMlp(column_idx=column_idx, cat_embed_input=embed_input, continuous_cols=colnames[(- 5):], mlp_hidden_dims=[32, 16]) tra...
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('return_dataframe', [True, False]) @pytest.mark.parametrize('embed_continuous', [True, False]) def test_bayesian_mlp_models(return_dataframe, embed_continuous): tab_preprocessor = TabPreprocessor(cat_embed_cols=embed_cols, continuous_cols=cont_cols) X_tab = tab_preprocessor.fit_transf...
class DummyPreprocessor(BasePreprocessor): def __init__(self): super().__init__() def fit(self, df): self.att1 = 1 self.att2 = 2 return df def transform(self, df): check_is_fitted(self, attributes=['att1', 'att2'], all_or_any='any') return df def fit...
class IncompletePreprocessor(BasePreprocessor): def __init__(self): super().__init__() def fit(self, df): return df def transform(self, df): return df
def test_check_is_fitted(): dummy_preprocessor = DummyPreprocessor() with pytest.raises(NotFittedError): dummy_preprocessor.transform(df)
def test_base_non_implemented_error(): with pytest.raises(NotImplementedError): incomplete_preprocessor = IncompletePreprocessor() incomplete_preprocessor.fit_transform(df)
def test_aap_ssp(): img = cv2.imread('/'.join([imd_dir, 'galaxy1.png'])) aap = AspectAwarePreprocessor(128, 128) spp = SimplePreprocessor(128, 128) out1 = aap.preprocess(img) out2 = aap.preprocess(img.transpose(1, 0, 2)) out3 = spp.preprocess(img) assert ((out1.shape[0] == 128) and (out2.s...
def test_sizes(): img_width = X_imgs.shape[1] img_height = X_imgs.shape[2] assert np.all(((img_width == processor.width), (img_height == processor.height)))
def test_notimplementederror(): with pytest.raises(NotImplementedError): org_df = processor.inverse_transform(X_imgs)
def test_pad_sequences(): out = [] seq = [1, 2, 3] padded_seq_1 = text_utils.pad_sequences(seq, maxlen=5, pad_idx=0) out.append(all([(el == 0) for el in padded_seq_1[:2]])) padded_seq_2 = text_utils.pad_sequences(seq, maxlen=5, pad_idx=1, pad_first=False) out.append(all([(el == 1) for el in pa...
def test_inverse_transform(): df = pd.DataFrame({'text_column': ['life is like a box of chocolates', "You never know what you're going to get"]}) text_preprocessor = TextPreprocessor(text_col='text_column', max_vocab=25, min_freq=1, maxlen=10, verbose=False) padded_seq = text_preprocessor.fit_transform(df...
def test_notfittederror(): processor = TextPreprocessor(min_freq=0, text_col='texts') with pytest.raises(NotFittedError): processor.transform(df)
def create_test_dataset(input_type, with_crossed=True): df = pd.DataFrame() col1 = list(np.random.choice(input_type, 3)) col2 = list(np.random.choice(input_type, 3)) (df['col1'], df['col2']) = (col1, col2) if with_crossed: crossed = ['_'.join([str(c1), str(c2)]) for (c1, c2) in zip(col1, c...
@pytest.mark.parametrize('input_df, expected_shape', [(df_letters, unique_letters), (df_numbers, unique_numbers)]) def test_preprocessor1(input_df, expected_shape): wide_mtx = preprocessor1.fit_transform(input_df) assert (np.unique(wide_mtx).shape[0] == expected_shape)
@pytest.mark.parametrize('input_df, expected_shape', [(df_letters_wo_crossed, unique_letters_wo_crossed), (df_numbers_wo_crossed, unique_numbers_wo_crossed)]) def test_prepare_wide_wo_crossed(input_df, expected_shape): wide_mtx = preprocessor2.fit_transform(input_df) assert (np.unique(wide_mtx).shape[0] == ex...
@pytest.mark.parametrize('input_df', [df_letters, df_numbers]) def test_inverse_transform(input_df): wide_mtx = preprocessor1.fit_transform(input_df) org_df = preprocessor1.inverse_transform(wide_mtx) org_df = org_df[input_df.columns.tolist()] for c in org_df.columns: org_df[c] = org_df[c].ast...