Skip to content

Tab2Vec

Tab2Vec

Tab2Vec(tab_preprocessor, model, return_dataframe=False, verbose=False)

Class to transform an input dataframe into vectorized form.

This class will take an input dataframe in the form of the dataframe used for training, and it will turn it into a vectorised form based on the processing applied by the model to the categorical and continuous columns.

ℹ️ NOTE: Currently this class is only implemented for the deeptabular component. Therefore, if the input dataframe has a text column or a column with the path to images, these will be ignored. We will be adding these functionalities in future versions

Parameters:

  • model (Union[WideDeep, BayesianWide, BayesianTabMlp]) –

    WideDeep, BayesianWide or BayesianTabMlp model. Must be trained.

  • tab_preprocessor (TabPreprocessor) –

    TabPreprocessor object. Must be fitted.

  • return_dataframe (bool, default: False ) –

    Boolean indicating of the returned object(s) will be array(s) or pandas dataframe(s)

Attributes:

  • vectorizer (Module) –

    Torch module with the categorical and continuous encoding process

Examples:

>>> import string
>>> from random import choices
>>> import numpy as np
>>> import pandas as pd
>>> from pytorch_widedeep import Tab2Vec
>>> from pytorch_widedeep.models import TabMlp, WideDeep
>>> from pytorch_widedeep.preprocessing import TabPreprocessor
>>>
>>> colnames = list(string.ascii_lowercase)[:4]
>>> cat_col1_vals = ["a", "b", "c"]
>>> cat_col2_vals = ["d", "e", "f"]
>>>
>>> # Create the toy input dataframe and a toy dataframe to be vectorised
>>> cat_inp = [np.array(choices(c, k=5)) for c in [cat_col1_vals, cat_col2_vals]]
>>> cont_inp = [np.round(np.random.rand(5), 2) for _ in range(2)]
>>> df_inp = pd.DataFrame(np.vstack(cat_inp + cont_inp).transpose(), columns=colnames)
>>> cat_t2v = [np.array(choices(c, k=5)) for c in [cat_col1_vals, cat_col2_vals]]
>>> cont_t2v = [np.round(np.random.rand(5), 2) for _ in range(2)]
>>> df_t2v = pd.DataFrame(np.vstack(cat_t2v + cont_t2v).transpose(), columns=colnames)
>>>
>>> # fit the TabPreprocessor
>>> embed_cols = [("a", 2), ("b", 4)]
>>> cont_cols = ["c", "d"]
>>> tab_preprocessor = TabPreprocessor(cat_embed_cols=embed_cols, continuous_cols=cont_cols)
>>> X_tab = tab_preprocessor.fit_transform(df_inp)
>>>
>>> # define the model (and let's assume we train it)
>>> tabmlp = TabMlp(
... column_idx=tab_preprocessor.column_idx,
... cat_embed_input=tab_preprocessor.cat_embed_input,
... continuous_cols=tab_preprocessor.continuous_cols,
... mlp_hidden_dims=[8, 4])
>>> model = WideDeep(deeptabular=tabmlp)
>>> # ...train the model...
>>>
>>> # vectorise the dataframe
>>> t2v = Tab2Vec(tab_preprocessor, model)
>>> X_vec = t2v.transform(df_t2v)
Source code in pytorch_widedeep/tab2vec.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def __init__(
    self,
    tab_preprocessor: TabPreprocessor,
    model: Union[WideDeep, BayesianWide, BayesianTabMlp],
    return_dataframe: bool = False,
    verbose: bool = False,
):
    super(Tab2Vec, self).__init__()

    self._check_inputs(tab_preprocessor, model, verbose)

    self.tab_preprocessor = tab_preprocessor
    self.return_dataframe = return_dataframe
    self.verbose = verbose

    self.vectorizer = self._set_vectorizer(model)

    self._set_dim_attributes(tab_preprocessor, model)

fit

fit(df, target_col=None)

This is an empty method i.e. Returns the unchanged object itself. Is only included for consistency in case Tab2Vec is used as part of a Pipeline

Parameters:

  • df (DataFrame) –

    DataFrame to be vectorised, i.e. the categorical and continuous columns will be encoded based on the processing applied within the model

  • target_col (Optional[str], default: None ) –

    Column name of the target_col variable. If None only the array of predictors will be returned

Returns:

Source code in pytorch_widedeep/tab2vec.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def fit(self, df: pd.DataFrame, target_col: Optional[str] = None) -> "Tab2Vec":
    r"""This is an empty method i.e. Returns the unchanged object itself. Is
    only included for consistency in case `Tab2Vec` is used as part of a
    Pipeline

    Parameters
    ----------
    df: pd.DataFrame
        DataFrame to be vectorised, i.e. the categorical and continuous
        columns will be encoded based on the processing applied within
        the model
    target_col: str, Optional
        Column name of the target_col variable. If `None` only the array of
        predictors will be returned

    Returns
    -------
    Tab2Vec
    """

    return self

transform

transform(df, target_col=None)

Transforms the input dataframe into vectorized form. If a target column name is passed the target values will be returned separately in their corresponding type (np.ndarray or pd.DataFrame)

Parameters:

  • df (DataFrame) –

    DataFrame to be vectorised, i.e. the categorical and continuous columns will be encoded based on the processing applied within the model

  • target_col (Optional[str], default: None ) –

    Column name of the target_col variable. If None only the array of predictors will be returned

Returns:

  • Union[np.ndarray, Tuple[np.ndarray, np.ndarray], pd.DataFrame, Tuple[pd.DataFrame, pd.Series]

    Returns eiter a numpy array with the vectorised values, or a Tuple of numpy arrays with the vectorised values and the target. The same applies to dataframes in case we choose to set return_dataframe = True

Source code in pytorch_widedeep/tab2vec.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def transform(
    self,
    df: pd.DataFrame,
    target_col: Optional[str] = None,
) -> Union[
    np.ndarray,
    Tuple[np.ndarray, np.ndarray],
    pd.DataFrame,
    Tuple[pd.DataFrame, pd.Series],
]:
    r"""Transforms the input dataframe into vectorized form. If a target
    column name is passed the target values will be returned separately
    in their corresponding type (np.ndarray or pd.DataFrame)

    Parameters
    ----------
    df: pd.DataFrame
        DataFrame to be vectorised, i.e. the categorical and continuous
        columns will be encoded based on the processing applied within
        the model
    target_col: str, Optional
        Column name of the target_col variable. If `None` only the array of
        predictors will be returned

    Returns
    -------
    Union[np.ndarray, Tuple[np.ndarray, np.ndarray], pd.DataFrame, Tuple[pd.DataFrame, pd.Series]
        Returns eiter a numpy array with the vectorised values, or a Tuple
        of numpy arrays with the vectorised values and the target. The
        same applies to dataframes in case we choose to set
        `return_dataframe = True`
    """

    X_tab = self.tab_preprocessor.transform(df)
    X = torch.from_numpy(X_tab.astype("float")).to(device)

    with torch.no_grad():
        if self.is_tab_transformer:
            x_vec, x_cont_not_embed = self.vectorizer(X)
        else:
            x_vec = self.vectorizer(X)
            x_cont_not_embed = None

    if self.tab_preprocessor.with_cls_token:
        x_vec = x_vec[:, 1:, :]

    if self.tab_preprocessor.with_attention:
        x_vec = einops.rearrange(x_vec, "s c e -> s (c e)")

    if x_cont_not_embed is not None:
        x_vec = torch.cat([x_vec, x_cont_not_embed], 1).detach().cpu().numpy()
    else:
        x_vec = x_vec.detach().cpu().numpy()

    if self.return_dataframe:
        new_colnames = self._new_colnames()
        if target_col:
            return pd.DataFrame(data=x_vec, columns=new_colnames), df[[target_col]]
        else:
            return pd.DataFrame(data=x_vec, columns=new_colnames)
    else:
        if target_col:
            return x_vec, df[target_col].values
        else:
            return x_vec

fit_transform

fit_transform(df, target_col=None)

Combines fit and transform

Source code in pytorch_widedeep/tab2vec.py
202
203
204
205
206
207
208
209
210
211
def fit_transform(
    self, df: pd.DataFrame, target_col: Optional[str] = None
) -> Union[
    np.ndarray,
    Tuple[np.ndarray, np.ndarray],
    pd.DataFrame,
    Tuple[pd.DataFrame, pd.Series],
]:
    r"""Combines `fit` and `transform`"""
    return self.fit(df, target_col).transform(df, target_col)