code
stringlengths
17
6.64M
class Accuracy(Metric): def __init__(self, top_k: int=1): super(Accuracy, self).__init__() self.top_k = top_k self.correct_count = 0 self.total_count = 0 self._name = 'acc' def reset(self): self.correct_count = 0 self.total_count = 0 def __call__(...
class SillyCallback(Callback): def on_train_begin(self, logs=None): self.trainer.silly_callback = {} self.trainer.silly_callback['beginning'] = [] self.trainer.silly_callback['end'] = [] def on_epoch_begin(self, epoch, logs=None): self.trainer.silly_callback['beginning'].appe...
class RayTuneReporter(Callback): 'Callback that allows reporting history and lr_history values to RayTune\n during Hyperparameter tuning\n\n Callbacks are passed as input parameters to the ``Trainer`` class. See\n :class:`pytorch_widedeep.trainer.Trainer`\n\n For examples see the examples folder at:\n...
class WnBReportBest(Callback): 'Callback that allows reporting best performance of a run to WnB\n during Hyperparameter tuning. It is an adjusted pytorch_widedeep.callbacks.ModelCheckpoint\n with added WnB and removed checkpoint saving.\n\n Callbacks are passed as input parameters to the ``Trainer`` clas...
@wandb_mixin def training_function(config, X_train, X_val): early_stopping = EarlyStopping() model_checkpoint = ModelCheckpoint(save_best_only=True) batch_size = config['batch_size'] trainer = Trainer(model, objective='binary_focal_loss', callbacks=[RayTuneReporter, WnBReportBest(wb=wandb), early_stop...
def get_coo_indexes(lil): rows = [] cols = [] for (i, el) in enumerate(lil): if (type(el) != list): el = [el] for j in el: rows.append(i) cols.append(j) return (rows, cols)
def get_sparse_features(series, shape): coo_indexes = get_coo_indexes(series.tolist()) sparse_df = coo_matrix((np.ones(len(coo_indexes[0])), (coo_indexes[0], coo_indexes[1])), shape=shape) return sparse_df
def sparse_to_idx(data, pad_idx=(- 1)): indexes = data.nonzero() indexes_df = pd.DataFrame() indexes_df['rows'] = indexes[0] indexes_df['cols'] = indexes[1] mdf = indexes_df.groupby('rows').apply((lambda x: x['cols'].tolist())) max_len = mdf.apply((lambda x: len(x))).max() return mdf.apply...
class Wide(nn.Module): def __init__(self, input_dim: int, pred_dim: int): super().__init__() self.input_dim = input_dim self.pred_dim = pred_dim self.wide_linear = nn.Linear(input_dim, pred_dim) def forward(self, X): out = self.wide_linear(X.type(torch.float32)) ...
class SimpleEmbed(nn.Module): def __init__(self, vocab_size: int, embed_dim: int, pad_idx: int): super().__init__() self.vocab_size = vocab_size self.embed_dim = embed_dim self.pad_idx = pad_idx self.embed = nn.Embedding(vocab_size, embed_dim, padding_idx=pad_idx) def...
class BayesianModule(nn.Module): "Simply a 'hack' to facilitate the computation of the KL divergence for all\n Bayesian models\n " def init(self): super().__init__()
class BaseBayesianModel(nn.Module): 'Base model containing the two methods common to all Bayesian models' def init(self): super().__init__() def _kl_divergence(self): kld = 0 for module in self.modules(): if isinstance(module, BayesianModule): kld += (...
class ScaleMixtureGaussianPrior(object): 'Defines the Scale Mixture Prior as proposed in Weight Uncertainty in\n Neural Networks (Eq 7 in the original publication)\n ' def __init__(self, pi: float, sigma1: float, sigma2: float): super().__init__() self.pi = pi self.sigma1 = sigm...
class GaussianPosterior(object): 'Defines the Gaussian variational posterior as proposed in Weight\n Uncertainty in Neural Networks\n ' def __init__(self, param_mu: Tensor, param_rho: Tensor): super().__init__() self.param_mu = param_mu self.param_rho = param_rho self.no...
class BayesianEmbedding(BayesianModule): 'A simple lookup table that looks up embeddings in a fixed dictionary and\n size.\n\n Parameters\n ----------\n n_embed: int\n number of embeddings. Typically referred as size of the vocabulary\n embed_dim: int\n Dimension of the embeddings\n ...
class BayesianLinear(BayesianModule): 'Applies a linear transformation to the incoming data as proposed in Weight\n Uncertainity on Neural Networks\n\n Parameters\n ----------\n in_features: int\n size of each input sample\n out_features: int\n size of each output sample\n use_bia...
class BayesianWide(BaseBayesianModel): 'Defines a `Wide` model. This is a linear model where the\n non-linearlities are captured via crossed-columns\n\n Parameters\n ----------\n input_dim: int\n size of the Embedding layer. `input_dim` is the summation of all the\n individual values for...
class BayesianMLP(nn.Module): def __init__(self, d_hidden: List[int], activation: str, use_bias: bool=True, prior_sigma_1: float=1.0, prior_sigma_2: float=0.002, prior_pi: float=0.8, posterior_mu_init: float=0.0, posterior_rho_init: float=(- 7.0)): super(BayesianMLP, self).__init__() self.d_hidde...
class BayesianTabMlp(BaseBayesianModel): 'Defines a `BayesianTabMlp` model.\n\n This class combines embedding representations of the categorical features\n with numerical (aka continuous) features, embedded or not. These are then\n passed through a series of probabilistic dense layers (i.e. a MLP).\n\n ...
def _get_current_time(): return datetime.datetime.now().strftime('%B %d, %Y - %I:%M%p')
def _is_metric(monitor: str): if any([(s in monitor) for s in ['acc', 'prec', 'rec', 'fscore', 'f1', 'f2']]): return True else: return False
class CallbackContainer(object): '\n Container holding a list of callbacks.\n ' def __init__(self, callbacks: Optional[List]=None, queue_length: int=10): instantiated_callbacks = [] if (callbacks is not None): for callback in callbacks: if isinstance(callback...
class Callback(object): '\n Base class used to build new callbacks.\n ' def __init__(self): pass def set_params(self, params): self.params = params def set_model(self, model: Any): self.model = model def set_trainer(self, trainer: Any): self.trainer = trai...
class History(Callback): 'Saves the metrics in the `history` attribute of the `Trainer`.\n\n This callback runs by default within `Trainer`, therefore, should not\n be passed to the `Trainer`. It is included here just for completion.\n ' def on_train_begin(self, logs: Optional[Dict]=None): s...
class LRShedulerCallback(Callback): 'Callback for the learning rate schedulers to take a step\n\n This callback runs by default within `Trainer`, therefore, should not\n be passed to the `Trainer`. It is included here just for completion.\n ' def on_batch_end(self, batch: int, logs: Optional[Dict]=N...
class MetricCallback(Callback): 'Callback that resets the metrics (if any metric is used)\n\n This callback runs by default within `Trainer`, therefore, should not\n be passed to the `Trainer`. It is included here just for completion.\n ' def __init__(self, container: MultipleMetrics): self....
class LRHistory(Callback): 'Saves the learning rates during training in the `lr_history` attribute\n of the `Trainer`.\n\n Callbacks are passed as input parameters to the `Trainer` class. See\n `pytorch_widedeep.trainer.Trainer`\n\n Parameters\n ----------\n n_epochs: int\n number of trai...
class ModelCheckpoint(Callback): 'Saves the model after every epoch.\n\n This class is almost identical to the corresponding keras class.\n Therefore, **credit** to the Keras Team.\n\n Callbacks are passed as input parameters to the `Trainer` class. See\n `pytorch_widedeep.trainer.Trainer`\n\n Para...
class EarlyStopping(Callback): 'Stop training when a monitored quantity has stopped improving.\n\n This class is almost identical to the corresponding keras class.\n Therefore, **credit** to the Keras Team.\n\n Callbacks are passed as input parameters to the `Trainer` class. See\n `pytorch_widedeep.tr...
def get_class_weights(dataset: WideDeepDataset) -> Tuple[(np.ndarray, int, int)]: "Helper function to get weights of classes in the imbalanced dataset.\n\n Parameters\n ----------\n dataset: `WideDeepDataset`\n dataset containing target classes in dataset.Y\n\n Returns\n ----------\n weig...
class DataLoaderDefault(DataLoader): def __init__(self, dataset: WideDeepDataset, batch_size: int, num_workers: int, **kwargs): self.with_lds = dataset.with_lds super().__init__(dataset=dataset, batch_size=batch_size, num_workers=num_workers, **kwargs)
class DataLoaderImbalanced(DataLoader): "Class to load and shuffle batches with adjusted weights for imbalanced\n datasets. If the classes do not begin from 0 remapping is necessary. See\n [here](https://towardsdatascience.com/pytorch-tabular-multiclass-classification-9f8211a123ab).\n\n Parameters\n -...
def load_bio_kdd04(as_frame: bool=False) -> Union[(np.ndarray, pd.DataFrame)]: 'Load and return the higly imbalanced binary classification Protein Homology\n Dataset from [KDD cup 2004](https://www.kdd.org/kdd-cup/view/kdd-cup-2004/Data).\n This datasets include only bio_train.dat part of the dataset\n\n\n ...
def load_adult(as_frame: bool=False) -> Union[(np.ndarray, pd.DataFrame)]: 'Load and return the higly imbalanced binary classification [adult income datatest](http://www.cs.toronto.edu/~delve/data/adult/desc.html).\n you may find detailed description [here](http://www.cs.toronto.edu/~delve/data/adult/adultDeta...
def load_ecoli(as_frame: bool=False) -> Union[(np.ndarray, pd.DataFrame)]: 'Load and return the higly imbalanced multiclass classification e.coli dataset\n Dataset from [UCI Machine learning Repository](https://archive.ics.uci.edu/ml/datasets/ecoli).\n\n\n 1. Title: Protein Localization Sites\n\n 2. Crea...
def load_california_housing(as_frame: bool=False) -> Union[(np.ndarray, pd.DataFrame)]: 'Load and return the higly imbalanced regression California housing dataset.\n\n Characteristics:\n Number of Instances: 20640\n Number of Attributes: 8 numeric, predictive attributes and the target\n Attribute Inf...
def load_birds(as_frame: bool=False) -> Union[(np.ndarray, pd.DataFrame)]: 'Load and return the multi-label classification bird dataset.\n\n References\n ----------\n http://mulan.sourceforge.net/datasets-mlc.html\n\n F. Briggs, Yonghong Huang, R. Raich, K. Eftaxias, Zhong Lei, W. Cukierski, S. Hadley...
def load_rf1(as_frame: bool=False) -> Union[(np.ndarray, pd.DataFrame)]: 'Load and return the multi-target regression River Flow(RF1) dataset.\n\n Characterisctics:\n The river flow data set (RF1) concerns a prediction task in which flows in a river network are\n predicted for 48 hours in the fut...
def load_womens_ecommerce(as_frame: bool=False) -> Union[(np.ndarray, pd.DataFrame)]: '\n Context\n This is a Women’s Clothing E-Commerce dataset revolving around the reviews written by customers.\n Its nine supportive features offer a great environment to parse out the text through its multiple\n dim...
def load_movielens100k(as_frame: bool=False) -> Union[(Tuple[(np.ndarray, np.ndarray, np.ndarray)], Tuple[(pd.DataFrame, pd.DataFrame, pd.DataFrame)])]: 'Load and return the MovieLens 100k dataset in 3 separate files.\n\n SUMMARY & USAGE LICENSE:\n =============================================\n MovieLen...
class Initializer(object): def __call__(self, submodel: nn.Module): raise NotImplementedError('Initializer must implement this method')
class MultipleInitializer(object): def __init__(self, initializers: Dict[(str, Union[(Initializer, object)])], verbose=True): self.verbose = verbose instantiated_initializers = {} for (model_name, initializer) in initializers.items(): if isinstance(initializer, type): ...
class Normal(Initializer): def __init__(self, mean=0.0, std=1.0, bias=False, pattern='.'): self.mean = mean self.std = std self.bias = bias self.pattern = pattern super(Normal, self).__init__() def __call__(self, submodel: nn.Module): for (n, p) in submodel.na...
class Uniform(Initializer): def __init__(self, a=0, b=1, bias=False, pattern='.'): self.a = a self.b = b self.bias = bias self.pattern = pattern super(Uniform, self).__init__() def __call__(self, submodel: nn.Module): for (n, p) in submodel.named_parameters():...
class ConstantInitializer(Initializer): def __init__(self, value, bias=False, pattern='.'): self.bias = bias self.value = value self.pattern = pattern super(ConstantInitializer, self).__init__() def __call__(self, submodel: nn.Module): for (n, p) in submodel.named_par...
class XavierUniform(Initializer): def __init__(self, gain=1, pattern='.'): self.gain = gain self.pattern = pattern super(XavierUniform, self).__init__() def __call__(self, submodel: nn.Module): for (n, p) in submodel.named_parameters(): if re.search(self.pattern, ...
class XavierNormal(Initializer): def __init__(self, gain=1, pattern='.'): self.gain = gain self.pattern = pattern super(XavierNormal, self).__init__() def __call__(self, submodel: nn.Module): for (n, p) in submodel.named_parameters(): if re.search(self.pattern, n)...
class KaimingUniform(Initializer): def __init__(self, a=0, mode='fan_in', nonlinearity='leaky_relu', pattern='.'): self.a = a self.mode = mode self.nonlinearity = nonlinearity self.pattern = pattern super(KaimingUniform, self).__init__() def __call__(self, submodel: n...
class KaimingNormal(Initializer): def __init__(self, a=0, mode='fan_in', nonlinearity='leaky_relu', pattern='.'): self.a = a self.mode = mode self.nonlinearity = nonlinearity self.pattern = pattern super(KaimingNormal, self).__init__() def __call__(self, submodel: nn....
class Orthogonal(Initializer): def __init__(self, gain=1, pattern='.'): self.gain = gain self.pattern = pattern super(Orthogonal, self).__init__() def __call__(self, submodel: nn.Module): for (n, p) in submodel.named_parameters(): if re.search(self.pattern, n): ...
class TabFromFolder(): '\n This class is used to load tabular data from disk. The current constrains are:\n\n 1. The only file format supported right now is csv\n 2. The csv file must contain headers\n\n For examples, please, see the examples folder in the repo.\n\n Parameters\n ----------\n ...
class WideFromFolder(TabFromFolder): '\n This class is mostly identical to `TabFromFolder` but exists because we\n want to separate the treatment of the wide and the deep tabular\n components\n\n Parameters\n ----------\n fname: str\n the name of the csv file\n directory: str, Optional...
class TextFromFolder(): '\n This class is used to load the text dataset (i.e. the text files) from a\n folder, or to retrieve the text given a texts column specified within the\n preprocessor object.\n\n For examples, please, see the examples folder in the repo.\n\n Parameters\n ----------\n ...
class WideDeepDatasetFromFolder(Dataset): '\n This class is the Dataset counterpart of the `WideDeepDataset` class.\n\n Given a reference tabular dataset, with columns that indicate the path to\n the images and to the text files or the texts themselves, it will use the\n `[...]FromFolder` classes to l...
class Metric(object): def __init__(self): self._name = '' def reset(self): raise NotImplementedError('Custom Metrics must implement this function') def __call__(self, y_pred: Tensor, y_true: Tensor): raise NotImplementedError('Custom Metrics must implement this function')
class MultipleMetrics(object): def __init__(self, metrics: List[Union[(Metric, object)]], prefix: str=''): instantiated_metrics = [] for metric in metrics: if isinstance(metric, type): instantiated_metrics.append(metric()) else: instantiated...
class Accuracy(Metric): 'Class to calculate the accuracy for both binary and categorical problems\n\n Parameters\n ----------\n top_k: int, default = 1\n Accuracy will be computed using the top k most likely classes in\n multiclass problems\n\n Examples\n --------\n >>> import torc...
class Precision(Metric): 'Class to calculate the precision for both binary and categorical problems\n\n Parameters\n ----------\n average: bool, default = True\n This applies only to multiclass problems. if ``True`` calculate\n precision for each label, and finds their unweighted mean.\n\n ...
class Recall(Metric): 'Class to calculate the recall for both binary and categorical problems\n\n Parameters\n ----------\n average: bool, default = True\n This applies only to multiclass problems. if ``True`` calculate recall\n for each label, and finds their unweighted mean.\n\n Exampl...
class FBetaScore(Metric): 'Class to calculate the fbeta score for both binary and categorical problems\n\n $$\n F_{\\beta} = ((1 + {\\beta}^2) * \\frac{(precision * recall)}{({\\beta}^2 * precision + recall)}\n $$\n\n Parameters\n ----------\n beta: int\n Coefficient to control the balanc...
class F1Score(Metric): 'Class to calculate the f1 score for both binary and categorical problems\n\n Parameters\n ----------\n average: bool, default = True\n This applies only to multiclass problems. if ``True`` calculate f1 for\n each label, and find their unweighted mean.\n\n Examples...
class R2Score(Metric): '\n Calculates R-Squared, the\n [coefficient of determination](https://en.wikipedia.org/wiki/Coefficient_of_determination>):\n\n $$\n R^2 = 1 - \\frac{\\sum_{j=1}^n(y_j - \\hat{y_j})^2}{\\sum_{j=1}^n(y_j - \\bar{y})^2}\n $$\n\n where $\\hat{y_j}$ is the ground truth, $y_j$...
class BaseWDModelComponent(nn.Module): @property def output_dim(self) -> int: return NotImplementedError("All models passed to the WideDeep class must contain an 'output_dim' property or attribute. This is the dimension of the output tensor coming from the backbone model that will be connected to the...
class GEGLU(nn.Module): def forward(self, x): (x, gates) = x.chunk(2, dim=(- 1)) return (x * F.gelu(gates))
class REGLU(nn.Module): def forward(self, x): (x, gates) = x.chunk(2, dim=(- 1)) return (x * F.gelu(gates))
def get_activation_fn(activation): if (activation == 'relu'): return nn.ReLU(inplace=True) elif (activation == 'leaky_relu'): return nn.LeakyReLU(inplace=True) elif (activation == 'tanh'): return nn.Tanh() elif (activation == 'gelu'): return nn.GELU() elif (activati...
def conv_layer(ni: int, nf: int, kernel_size: int=3, stride: int=1, maxpool: bool=True, adaptiveavgpool: bool=False): layer = nn.Sequential(nn.Conv2d(ni, nf, kernel_size=kernel_size, stride=stride, bias=False, padding=(kernel_size // 2)), nn.BatchNorm2d(nf, momentum=0.01), nn.LeakyReLU(negative_slope=0.1, inplace...
class Vision(BaseWDModelComponent): 'Defines a standard image classifier/regressor using a pretrained\n network or a sequence of convolution layers that can be used as the\n `deepimage` component of a Wide & Deep model or independently by\n itself.\n\n :information_source: **NOTE**: this class represe...
class BaseTabularModelWithoutAttention(BaseWDModelComponent): def __init__(self, column_idx: Dict[(str, int)], cat_embed_input: Optional[List[Tuple[(str, int, int)]]], cat_embed_dropout: float, use_cat_bias: bool, cat_embed_activation: Optional[str], continuous_cols: Optional[List[str]], cont_norm_layer: str, em...
class BaseTabularModelWithAttention(BaseWDModelComponent): def __init__(self, column_idx: Dict[(str, int)], cat_embed_input: Optional[List[Tuple[(str, int)]]], cat_embed_dropout: float, use_cat_bias: bool, cat_embed_activation: Optional[str], full_embed_dropout: bool, shared_embed: bool, add_shared_embed: bool, ...
class Wide(nn.Module): 'Defines a `Wide` (linear) model where the non-linearities are\n captured via the so-called crossed-columns. This can be used as the\n `wide` component of a Wide & Deep model.\n\n Parameters\n -----------\n input_dim: int\n size of the Embedding layer. `input_dim` is t...
class ContextAttention(nn.Module): 'Attention mechanism inspired by `Hierarchical Attention Networks for\n Document Classification\n <https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf>`_\n ' def __init__(self, input_dim: int, dropout: float, sum_along_seq: bool=False): ...
class QueryKeySelfAttention(nn.Module): 'Attention mechanism inspired by the well known multi-head attention. Here,\n rather than learning a value projection matrix that will be multiplied by\n the attention weights, we multiply such weights directly by the input\n tensor.\n\n The rationale behind thi...
class ContextAttentionEncoder(nn.Module): def __init__(self, input_dim: int, dropout: float, with_addnorm: bool, activation: str): super(ContextAttentionEncoder, self).__init__() self.with_addnorm = with_addnorm self.attn = ContextAttention(input_dim, dropout) if with_addnorm: ...
class SelfAttentionEncoder(nn.Module): def __init__(self, input_dim: int, dropout: float, use_bias: bool, n_heads: int, with_addnorm: bool, activation: str): super(SelfAttentionEncoder, self).__init__() self.with_addnorm = with_addnorm self.attn = QueryKeySelfAttention(input_dim, dropout,...
def dense_layer(inp: int, out: int, activation: str, p: float, bn: bool, linear_first: bool): act_fn = get_activation_fn(activation) layers = ([nn.BatchNorm1d((out if linear_first else inp))] if bn else []) if (p != 0): layers.append(nn.Dropout(p)) lin = [nn.Linear(inp, out, bias=(not bn)), ac...
class SLP(nn.Module): def __init__(self, input_dim: int, dropout: float, activation: str, normalise: bool): super(SLP, self).__init__() self.lin = nn.Linear(input_dim, ((input_dim * 2) if activation.endswith('glu') else input_dim)) self.dropout = nn.Dropout(dropout) self.activatio...
class MLP(nn.Module): def __init__(self, d_hidden: List[int], activation: str, dropout: Optional[Union[(float, List[float])]], batchnorm: bool, batchnorm_last: bool, linear_first: bool): super(MLP, self).__init__() if (not dropout): dropout = ([0.0] * len(d_hidden)) elif isins...
class TabMlp(BaseTabularModelWithoutAttention): 'Defines a `TabMlp` model that can be used as the `deeptabular`\n component of a Wide & Deep model or independently by itself.\n\n This class combines embedding representations of the categorical features\n with numerical (aka continuous) features, embedded...
class TabMlpDecoder(nn.Module): 'Companion decoder model for the `TabMlp` model (which can be considered\n an encoder itself).\n\n This class is designed to be used with the `EncoderDecoderTrainer` when\n using self-supervised pre-training (see the corresponding section in the\n docs). The `TabMlpDeco...
class BasicBlock(nn.Module): def __init__(self, inp: int, out: int, dropout: float=0.0, simplify: bool=False, resize: nn.Module=None): super(BasicBlock, self).__init__() self.simplify = simplify self.resize = resize self.lin1 = nn.Linear(inp, out, bias=False) self.bn1 = nn...
class DenseResnet(nn.Module): def __init__(self, input_dim: int, blocks_dims: List[int], dropout: float, simplify: bool): super(DenseResnet, self).__init__() if (input_dim != blocks_dims[0]): self.dense_resnet = nn.Sequential(OrderedDict([('lin_inp', nn.Linear(input_dim, blocks_dims[0...
class TabResnet(BaseTabularModelWithoutAttention): 'Defines a `TabResnet` model that can be used as the `deeptabular`\n component of a Wide & Deep model or independently by itself.\n\n This class combines embedding representations of the categorical features\n with numerical (aka continuous) features, em...
class TabResnetDecoder(nn.Module): 'Companion decoder model for the `TabResnet` model (which can be\n considered an encoder itself)\n\n This class is designed to be used with the `EncoderDecoderTrainer` when\n using self-supervised pre-training (see the corresponding section in the\n docs). This class...
def cut_mix(x: Tensor, lam: float=0.8) -> Tensor: batch_size = x.size()[0] mask = torch.from_numpy(np.random.choice(2, x.shape, p=[lam, (1 - lam)])).to(x.device) rand_idx = torch.randperm(batch_size).to(x.device) x_ = x[rand_idx].clone() x_[(mask == 0)] = x[(mask == 0)] return x_
def mix_up(p: Tensor, lam: float=0.8) -> Tensor: batch_size = p.size()[0] rand_idx = torch.randperm(batch_size).to(p.device) p_ = ((lam * p) + ((1 - lam) * p[(rand_idx, ...)])) return p_
class RandomObfuscator(nn.Module): 'Creates and applies an obfuscation masks\n\n Note that the class will return a mask tensor with 1s IF the feature value\n is considered for reconstruction\n\n Parameters:\n ----------\n p: float\n Ratio of features that will be discarded for reconstruction...
class EncoderDecoderModel(nn.Module): "This Class, which is referred as a 'Model', implements an Encoder-Decoder\n Self Supervised 'routine' inspired by `TabNet: Attentive Interpretable\n Tabular Learning <https://arxiv.org/abs/1908.07442>_`\n\n This class is in principle not exposed to the user and its ...
def create_explain_matrix(model: WideDeep) -> csc_matrix: '\n Returns a sparse matrix used to compute the feature importances after\n training\n\n Parameters\n ----------\n model: WideDeep\n object of type ``WideDeep``\n\n Examples\n --------\n >>> from pytorch_widedeep.models impor...
def extract_cat_setup(backbone: nn.Module) -> List: cat_cols: List = backbone.cat_embed_input if (cat_cols is not None): return cat_cols else: return []
def extract_cont_setup(backbone: nn.Module) -> List: cont_cols: List = backbone.continuous_cols embed_continuous = backbone.embed_continuous if (cont_cols is not None): if embed_continuous: cont_embed_dim = ([backbone.cont_embed_dim] * len(cont_cols)) cont_setup: List = [(c...
def _make_ix_like(input, dim=0): d = input.size(dim) rho = torch.arange(1, (d + 1), device=input.device, dtype=input.dtype) view = ([1] * input.dim()) view[0] = (- 1) return rho.view(view).transpose(0, dim)
class SparsemaxFunction(Function): '\n An implementation of sparsemax (Martins & Astudillo, 2016). See\n :cite:`DBLP:journals/corr/MartinsA16` for detailed description.\n By Ben Peters and Vlad Niculae\n ' @staticmethod def forward(ctx, input, dim=(- 1)): 'sparsemax: normalizing spars...
class Sparsemax(nn.Module): def __init__(self, dim=(- 1)): self.dim = dim super(Sparsemax, self).__init__() def forward(self, input): return sparsemax(input, self.dim)
class Entmax15Function(Function): '\n An implementation of exact Entmax with alpha=1.5 (B. Peters, V. Niculae, A. Martins). See\n :cite:`https://arxiv.org/abs/1905.05702 for detailed description.\n Source: https://github.com/deep-spin/entmax\n ' @staticmethod def forward(ctx, input, dim=(- 1)...
class Entmax15(nn.Module): def __init__(self, dim=(- 1)): self.dim = dim super(Entmax15, self).__init__() def forward(self, input): return entmax15(input, self.dim)
class TabNet(BaseTabularModelWithoutAttention): 'Defines a [TabNet model](https://arxiv.org/abs/1908.07442) that\n can be used as the `deeptabular` component of a Wide & Deep model or\n independently by itself.\n\n The implementation in this library is fully based on that\n [here](https://github.com/d...
class TabNetPredLayer(nn.Module): def __init__(self, inp, out): "This class is a 'hack' required because TabNet is a very particular\n model within `WideDeep`.\n\n TabNet's forward method within `WideDeep` outputs two tensors, one\n with the last layer's activations and the sparse re...
class TabNetDecoder(nn.Module): "Companion decoder model for the `TabNet` model (which can be\n considered an encoder itself)\n\n This class is designed to be used with the `EncoderDecoderTrainer` when\n using self-supervised pre-training (see the corresponding section in the\n docs). This class will ...
class FeedForward(nn.Module): def __init__(self, input_dim: int, dropout: float, mult: float, activation: str, *, ff_hidden_dim: Optional[int]=None): super(FeedForward, self).__init__() ff_hid_dim = (ff_hidden_dim if (ff_hidden_dim is not None) else int((input_dim * mult))) self.w_1 = nn....