﻿# Tabular data


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

The main class to get your data ready for model training is
[`TabularDataLoaders`](https://docs.fast.ai/tabular.data.html#tabulardataloaders)
and its factory methods. Checkout the [tabular
tutorial](http://docs.fast.ai/tutorial.tabular.html) for examples of
use.

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

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

### TabularDataLoaders

``` python
def TabularDataLoaders(
    *loaders, # `DataLoader` objects to wrap
    path:str | pathlib.Path='.', # Path to store export objects
    device:NoneType=None, # Device to put `DataLoaders`
):
```

*Basic wrapper around several
[`DataLoader`](https://docs.fast.ai/data.load.html#dataloader)s with
factory methods for tabular data*

This class should not be used directly, one of the factory methods
should be preferred instead. All those factory methods accept as
arguments:

- `cat_names`: the names of the categorical variables
- `cont_names`: the names of the continuous variables
- `y_names`: the names of the dependent variables
- `y_block`: the
  [`TransformBlock`](https://docs.fast.ai/data.block.html#transformblock)
  to use for the target
- `valid_idx`: the indices to use for the validation set (defaults to a
  random split otherwise)
- `bs`: the batch size
- `val_bs`: the batch size for the validation
  [`DataLoader`](https://docs.fast.ai/data.load.html#dataloader)
  (defaults to `bs`)
- `shuffle_train`: if we shuffle the training
  [`DataLoader`](https://docs.fast.ai/data.load.html#dataloader) or not
- `n`: overrides the numbers of elements in the dataset
- `device`: the PyTorch device to use (defaults to
  [`default_device()`](https://docs.fast.ai/torch_core.html#default_device))

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

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

### TabularDataLoaders.from_df

``` python
def from_df(
    df:DataFrame, path:str | pathlib.Path='.', # Location of `df`, defaults to current working directory
    procs:list=None, # List of `TabularProc`s
    cat_names:list=None, # Column names pertaining to categorical variables
    cont_names:list=None, # Column names pertaining to continuous variables
    y_names:list=None, # Names of the dependent variables
    y_block:TransformBlock=None, # `TransformBlock` to use for the target(s)
    valid_idx:list=None, # List of indices to use for the validation set, defaults to a random split
    bs:int=64, # Batch size
    shuffle_train:bool=None, # (Deprecated, use `shuffle`) Shuffle training `DataLoader`
    shuffle:bool=True, # Shuffle training `DataLoader`
    val_shuffle:bool=False, # Shuffle validation `DataLoader`
    n:int=None, # Size of `Datasets` used to create `DataLoader`
    device:device=None, # Device to put `DataLoaders`
    drop_last:bool=None, # Drop last incomplete batch, defaults to `shuffle`
    val_bs:int=None, # Validation batch size, defaults to `bs`
):
```

*Create
[`TabularDataLoaders`](https://docs.fast.ai/tabular.data.html#tabulardataloaders)
from `df` in `path` using `procs`*

Let’s have a look on an example with the adult dataset:

``` python
path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv', skipinitialspace=True)
df.head()
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<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">age</th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">education-num</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">sex</th>
<th data-quarto-table-cell-role="th">capital-gain</th>
<th data-quarto-table-cell-role="th">capital-loss</th>
<th data-quarto-table-cell-role="th">hours-per-week</th>
<th data-quarto-table-cell-role="th">native-country</th>
<th data-quarto-table-cell-role="th">salary</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>49</td>
<td>Private</td>
<td>101320</td>
<td>Assoc-acdm</td>
<td>12.0</td>
<td>Married-civ-spouse</td>
<td>NaN</td>
<td>Wife</td>
<td>White</td>
<td>Female</td>
<td>0</td>
<td>1902</td>
<td>40</td>
<td>United-States</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>44</td>
<td>Private</td>
<td>236746</td>
<td>Masters</td>
<td>14.0</td>
<td>Divorced</td>
<td>Exec-managerial</td>
<td>Not-in-family</td>
<td>White</td>
<td>Male</td>
<td>10520</td>
<td>0</td>
<td>45</td>
<td>United-States</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>38</td>
<td>Private</td>
<td>96185</td>
<td>HS-grad</td>
<td>NaN</td>
<td>Divorced</td>
<td>NaN</td>
<td>Unmarried</td>
<td>Black</td>
<td>Female</td>
<td>0</td>
<td>0</td>
<td>32</td>
<td>United-States</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>38</td>
<td>Self-emp-inc</td>
<td>112847</td>
<td>Prof-school</td>
<td>15.0</td>
<td>Married-civ-spouse</td>
<td>Prof-specialty</td>
<td>Husband</td>
<td>Asian-Pac-Islander</td>
<td>Male</td>
<td>0</td>
<td>0</td>
<td>40</td>
<td>United-States</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>42</td>
<td>Self-emp-not-inc</td>
<td>82297</td>
<td>7th-8th</td>
<td>NaN</td>
<td>Married-civ-spouse</td>
<td>Other-service</td>
<td>Wife</td>
<td>Black</td>
<td>Female</td>
<td>0</td>
<td>0</td>
<td>50</td>
<td>United-States</td>
<td>&lt;50k</td>
</tr>
</tbody>
</table>

</div>

``` python
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']
cont_names = ['age', 'fnlwgt', 'education-num']
procs = [Categorify, FillMissing, Normalize]
```

``` python
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)
```

``` python
dls.show_batch()
```

<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>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Adm-clerical</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>24.0</td>
<td>121312.998272</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>Private</td>
<td>HS-grad</td>
<td>Never-married</td>
<td>Other-service</td>
<td>Not-in-family</td>
<td>White</td>
<td>False</td>
<td>19.0</td>
<td>198320.000325</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>Private</td>
<td>Bachelors</td>
<td>Married-civ-spouse</td>
<td>Sales</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>66.0</td>
<td>169803.999308</td>
<td>13.0</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>Private</td>
<td>HS-grad</td>
<td>Divorced</td>
<td>Adm-clerical</td>
<td>Unmarried</td>
<td>White</td>
<td>False</td>
<td>40.0</td>
<td>799280.980929</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>Local-gov</td>
<td>10th</td>
<td>Never-married</td>
<td>Other-service</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>18.0</td>
<td>55658.003629</td>
<td>6.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5</td>
<td>Private</td>
<td>HS-grad</td>
<td>Never-married</td>
<td>Handlers-cleaners</td>
<td>Other-relative</td>
<td>White</td>
<td>False</td>
<td>30.0</td>
<td>375827.003847</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>Private</td>
<td>Some-college</td>
<td>Never-married</td>
<td>Handlers-cleaners</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>20.0</td>
<td>173723.999335</td>
<td>10.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">7</td>
<td>?</td>
<td>Some-college</td>
<td>Never-married</td>
<td>?</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>21.0</td>
<td>107800.997986</td>
<td>10.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">8</td>
<td>Private</td>
<td>HS-grad</td>
<td>Never-married</td>
<td>Handlers-cleaners</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>19.0</td>
<td>263338.000072</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">9</td>
<td>Private</td>
<td>Some-college</td>
<td>Married-civ-spouse</td>
<td>Tech-support</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>35.0</td>
<td>194590.999986</td>
<td>10.0</td>
<td>&lt;50k</td>
</tr>
</tbody>
</table>

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

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

### TabularDataLoaders.from_csv

``` python
def from_csv(
    csv:str | pathlib.Path | _io.BufferedReader, # A csv of training data
    skipinitialspace:bool=True, # Skip spaces after delimiter
    path:str | pathlib.Path='.', # Location of `df`, defaults to current working directory
    procs:list=None, # List of `TabularProc`s
    cat_names:list=None, # Column names pertaining to categorical variables
    cont_names:list=None, # Column names pertaining to continuous variables
    y_names:list=None, # Names of the dependent variables
    y_block:TransformBlock=None, # `TransformBlock` to use for the target(s)
    valid_idx:list=None, # List of indices to use for the validation set, defaults to a random split
    bs:int=64, # Batch size
    shuffle_train:bool=None, # (Deprecated, use `shuffle`) Shuffle training `DataLoader`
    shuffle:bool=True, # Shuffle training `DataLoader`
    val_shuffle:bool=False, # Shuffle validation `DataLoader`
    n:int=None, # Size of `Datasets` used to create `DataLoader`
    device:device=None, # Device to put `DataLoaders`
    drop_last:bool=None, # Drop last incomplete batch, defaults to `shuffle`
    val_bs:int=None, # Validation batch size, defaults to `bs`
):
```

*Create
[`TabularDataLoaders`](https://docs.fast.ai/tabular.data.html#tabulardataloaders)
from `csv` file in `path` using `procs`*

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

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

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

### TabularDataLoaders.test_dl

``` python
def test_dl(
    test_items, # Items to create new test `TabDataLoader` formatted the same as the training data
    rm_type_tfms:NoneType=None, # Number of `Transform`s to be removed from `procs`
    process:bool=True, # Apply validation `TabularProc`s to `test_items` immediately
    inplace:bool=False, # Keep separate copy of original `test_items` in memory if `False`
    bs:int=16, # Size of batch
    shuffle:bool=False, # Whether to shuffle data
    after_batch:NoneType=None, num_workers:int=0, verbose:bool=False, # Whether to print verbose logs
    do_setup:bool=True, # Whether to run `setup()` for batch transform(s)
    pin_memory:bool=False, timeout:int=0, batch_size:NoneType=None, drop_last:bool=False, indexed:NoneType=None,
    n:NoneType=None, device:NoneType=None, persistent_workers:bool=False, pin_memory_device:str='',
    wif:NoneType=None, before_iter:NoneType=None, after_item:NoneType=None, before_batch:NoneType=None,
    after_iter:NoneType=None, create_batches:NoneType=None, create_item:NoneType=None, create_batch:NoneType=None,
    retain:NoneType=None, get_idxs:NoneType=None, sample:NoneType=None, shuffle_fn:NoneType=None,
    do_batch:NoneType=None
):
```

*Create test
[`TabDataLoader`](https://docs.fast.ai/tabular.core.html#tabdataloader)
from `test_items` using validation `procs`*

External structured data files can contain unexpected spaces, e.g. after
a comma. We can see that in the first row of adult.csv
`"49, Private,101320, ..."`. Often trimming is needed. Pandas has a
convenient parameter `skipinitialspace` that is exposed by
[`TabularDataLoaders.from_csv()`](https://docs.fast.ai/tabular.data.html#tabulardataloaders.from_csv).
Otherwise category labels use for inference later such as
`workclass`:`Private` will be categorized wrongly to *0* or `"#na#"` if
training label was read as `" Private"`. Let’s test this feature.

``` python
test_data = {
    'age': [49], 
    'workclass': ['Private'], 
    'fnlwgt': [101320],
    'education': ['Assoc-acdm'], 
    'education-num': [12.0],
    'marital-status': ['Married-civ-spouse'], 
    'occupation': [''],
    'relationship': ['Wife'],
    'race': ['White'],
}
input = pd.DataFrame(test_data)
tdl = dls.test_dl(input)

test_ne(0, tdl.dataset.iloc[0]['workclass'])
`