﻿# Tabular learner


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

The main function you probably want to use in this module is
[`tabular_learner`](https://docs.fast.ai/tabular.learner.html#tabular_learner).
It will automatically create a
[`TabularModel`](https://docs.fast.ai/tabular.model.html#tabularmodel)
suitable for your data and infer the right loss function. See the
[tabular tutorial](http://docs.fast.ai/tutorial.tabular.html) for an
example of use in context.

## Main functions

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/learner.py#L17"
target="_blank" style="float:right; font-size:smaller">source</a>

### TabularLearner

``` python
def TabularLearner(
    dls:DataLoaders, # `DataLoaders` containing fastai or PyTorch `DataLoader`s
    model:Callable, # PyTorch model for training or inference
    loss_func:Optional=None, # Loss function. Defaults to `dls` loss
    opt_func:fastai.optimizer.Optimizer | fastai.optimizer.OptimWrapper=Adam, # Optimization function for training
    lr:float | slice=0.001, # Default learning rate
    splitter:Callable=trainable_params, # Split model into parameter groups. Defaults to one parameter group
    cbs:fastai.callback.core.Callback | collections.abc.MutableSequence | None=None, # `Callback`s to add to `Learner`
    metrics:Union=None, # `Metric`s to calculate on validation set
    path:str | pathlib.Path | None=None, # Parent directory to save, load, and export models. Defaults to `dls` `path`
    model_dir:str | pathlib.Path='models', # Subdirectory to save and load models
    wd:float | int | None=None, # Default weight decay
    wd_bn_bias:bool=False, # Apply weight decay to normalization and bias parameters
    train_bn:bool=True, # Train frozen normalization layers
    moms:tuple=(0.95, 0.85, 0.95), # Default momentum for schedulers
    default_cbs:bool=True, # Include default `Callback`s
):
```

*[`Learner`](https://docs.fast.ai/learner.html#learner) for tabular
data*

It works exactly as a normal
[`Learner`](https://docs.fast.ai/learner.html#learner), the only
difference is that it implements a `predict` method specific to work on
a row of data.

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/learner.py#L32"
target="_blank" style="float:right; font-size:smaller">source</a>

### tabular_learner

``` python
def tabular_learner(
    dls:TabularDataLoaders, layers:list=None, # Size of the layers generated by `LinBnDrop`
    emb_szs:list=None, # Tuples of `n_unique, embedding_size` for all categorical features
    config:dict=None, # Config params for TabularModel from `tabular_config`
    n_out:int=None, # Final output size of the model
    y_range:Tuple=None, # Low and high for the final sigmoid function
    loss_func:Optional=None, # Loss function. Defaults to `dls` loss
    opt_func:fastai.optimizer.Optimizer | fastai.optimizer.OptimWrapper=Adam, # Optimization function for training
    lr:float | slice=0.001, # Default learning rate
    splitter:Callable=trainable_params, # Split model into parameter groups. Defaults to one parameter group
    cbs:fastai.callback.core.Callback | collections.abc.MutableSequence | None=None, # `Callback`s to add to `Learner`
    metrics:Union=None, # `Metric`s to calculate on validation set
    path:str | pathlib.Path | None=None, # Parent directory to save, load, and export models. Defaults to `dls` `path`
    model_dir:str | pathlib.Path='models', # Subdirectory to save and load models
    wd:float | int | None=None, # Default weight decay
    wd_bn_bias:bool=False, # Apply weight decay to normalization and bias parameters
    train_bn:bool=True, # Train frozen normalization layers
    moms:tuple=(0.95, 0.85, 0.95), # Default momentum for schedulers
    default_cbs:bool=True, # Include default `Callback`s
):
```

*Get a [`Learner`](https://docs.fast.ai/learner.html#learner) using
`dls`, with `metrics`, including a
[`TabularModel`](https://docs.fast.ai/tabular.model.html#tabularmodel)
created using the remaining params.*

If your data was built with fastai, you probably won’t need to pass
anything to `emb_szs` unless you want to change the default of the
library (produced by
[`get_emb_sz`](https://docs.fast.ai/tabular.model.html#get_emb_sz)),
same for `n_out` which should be automatically inferred. `layers` will
default to `[200,100]` and is passed to
[`TabularModel`](https://docs.fast.ai/tabular.model.html#tabularmodel)
along with the `config`.

Use
[`tabular_config`](https://docs.fast.ai/tabular.model.html#tabular_config)
to create a `config` and customize the model used. There is just easy
access to `y_range` because this argument is often used.

All the other arguments are passed to
[`Learner`](https://docs.fast.ai/learner.html#learner).

``` python
path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv')
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']
cont_names = ['age', 'fnlwgt', 'education-num']
procs = [Categorify, FillMissing, Normalize]
dls = TabularDataLoaders.from_df(df, path, procs=procs, cat_names=cat_names, cont_names=cont_names, 
                                 y_names="salary", valid_idx=list(range(800,1000)), bs=64)
learn = tabular_learner(dls)
```

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/learner.py#L19"
target="_blank" style="float:right; font-size:smaller">source</a>

### TabularLearner.predict

``` python
def predict(
    row:Series, # Features to be predicted
):
```

*Predict on a single sample*

We can pass in an individual row of data into our
[`TabularLearner`](https://docs.fast.ai/tabular.learner.html#tabularlearner)’s
`predict` method. It’s output is slightly different from the other
`predict` methods, as this one will always return the input as well:

``` python
row, clas, probs = learn.predict(df.iloc[0])
```

``` python
row.show()
```

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">education-num_na</th>
<th data-quarto-table-cell-role="th">age</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education-num</th>
<th data-quarto-table-cell-role="th">salary</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>Private</td>
<td>Assoc-acdm</td>
<td>Married-civ-spouse</td>
<td>#na#</td>
<td>Wife</td>
<td>White</td>
<td>False</td>
<td>49.0</td>
<td>101320.001685</td>
<td>12.0</td>
<td>&lt;50k</td>
</tr>
</tbody>
</table>

``` python
clas, probs
```

    (tensor(0), tensor([0.5264, 0.4736]