tabular.transform

Transforms to clean and preprocess tabular data

Tabular data preprocessing

Overview

This package contains the basic class to define a transformation for preprocessing dataframes of tabular data, as well as basic TabularProc. Preprocessing includes things like

  • replacing non-numerical variables by categories, then their ids,
  • filling missing values,
  • normalizing continuous variables.

In all those steps we have to be careful to use the correspondence we decide on our training set (which id we give to each category, what is the value we put for missing data, or how the mean/std we use to normalize) on our validation or test set. To deal with this, we use a special class called TabularProc.

The data used in this document page is a subset of the adult dataset. It gives a certain amount of data on individuals to train a model to predict whether their salary is greater than $50k or not.

  1. path = untar_data(URLs.ADULT_SAMPLE)
  2. df = pd.read_csv(path/'adult.csv')
  3. train_df, valid_df = df.iloc[:800].copy(), df.iloc[800:1000].copy()
  4. train_df.head()
ageworkclassfnlwgteducationeducation-nummarital-statusoccupationrelationshipracesexcapital-gaincapital-losshours-per-weeknative-countrysalary
049Private101320Assoc-acdm12.0Married-civ-spouseNaNWifeWhiteFemale0190240United-States>=50k
144Private236746Masters14.0DivorcedExec-managerialNot-in-familyWhiteMale10520045United-States>=50k
238Private96185HS-gradNaNDivorcedNaNUnmarriedBlackFemale0032United-States<50k
338Self-emp-inc112847Prof-school15.0Married-civ-spouseProf-specialtyHusbandAsian-Pac-IslanderMale0040United-States>=50k
442Self-emp-not-inc822977th-8thNaNMarried-civ-spouseOther-serviceWifeBlackFemale0050United-States<50k

We see it contains numerical variables (like age or education-num) as well as categorical ones (like workclass or relationship). The original dataset is clean, but we removed a few values to give examples of dealing with missing variables.

  1. cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country']
  2. cont_names = ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']

Transforms for tabular data

class TabularProc[source][test]

TabularProc(cat_names:StrList, cont_names:StrList) No tests found for TabularProc. To contribute a test please refer to this guide and this discussion.

A processor for tabular dataframes.

Base class for creating transforms for dataframes with categorical variables cat_names and continuous variables cont_names. Note that any column not in one of those lists won’t be touched.

__call__[source][test]

__call__(df:DataFrame, test:bool=False) No tests found for __call__. To contribute a test please refer to this guide and this discussion.

Apply the correct function to df depending on test.

apply_train[source][test]

apply_train(df:DataFrame) Tests found for apply_train:

Some other tests where apply_train is used:

  • pytest -sv tests/test_tabular_transform.py::test_categorify [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_leaves_no_na_values [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_returns_correct_medians [source]

To run tests please refer to this guide.

Function applied to df if it’s the train set.

apply_test[source][test]

apply_test(df:DataFrame) Tests found for apply_test:

Some other tests where apply_test is used:

  • pytest -sv tests/test_tabular_transform.py::test_categorify [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_leaves_no_na_values [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_returns_correct_medians [source]

To run tests please refer to this guide.

Function applied to df if it’s the test set.

Important: Those two functions must be implemented in a subclass. apply_test defaults to apply_train.

The following TabularProc are implemented in the fastai library. Note that the replacement from categories to codes as well as the normalization of continuous variables are automatically done in a TabularDataBunch.

class Categorify[source][test]

Categorify(cat_names:StrList, cont_names:StrList) :: TabularProc Tests found for Categorify:

  • pytest -sv tests/test_tabular_transform.py::test_categorify [source]

To run tests please refer to this guide.

Transform the categorical variables to that type.

Variables in cont_names aren’t affected.

apply_train[source][test]

apply_train(df:DataFrame) Tests found for apply_train:

Some other tests where apply_train is used:

  • pytest -sv tests/test_tabular_transform.py::test_categorify [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_leaves_no_na_values [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_returns_correct_medians [source]

To run tests please refer to this guide.

Transform self.cat_names columns in categorical.

apply_test[source][test]

apply_test(df:DataFrame) Tests found for apply_test:

Some other tests where apply_test is used:

  • pytest -sv tests/test_tabular_transform.py::test_categorify [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_leaves_no_na_values [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_returns_correct_medians [source]

To run tests please refer to this guide.

Transform self.cat_names columns in categorical using the codes decided in apply_train.

  1. tfm = Categorify(cat_names, cont_names)
  2. tfm(train_df)
  3. tfm(valid_df, test=True)

Since we haven’t changed the categories by their codes, nothing visible has changed in the dataframe yet, but we can check that the variables are now categorical and view their corresponding codes.

  1. train_df['workclass'].cat.categories
  1. Index([' ?', ' Federal-gov', ' Local-gov', ' Private', ' Self-emp-inc',
  2. ' Self-emp-not-inc', ' State-gov', ' Without-pay'],
  3. dtype='object')

The test set will be given the same category codes as the training set.

  1. valid_df['workclass'].cat.categories
  1. Index([' ?', ' Federal-gov', ' Local-gov', ' Private', ' Self-emp-inc',
  2. ' Self-emp-not-inc', ' State-gov', ' Without-pay'],
  3. dtype='object')

class FillMissing[source][test]

FillMissing(cat_names:StrList, cont_names:StrList, fill_strategy:FillStrategy=<FillStrategy.MEDIAN: 1>, add_col:bool=True, fill_val:float=0.0) :: TabularProc Tests found for FillMissing:

  • pytest -sv tests/test_tabular_transform.py::test_default_fill_strategy_is_median [source]

Some other tests where FillMissing is used:

  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_leaves_no_na_values [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_returns_correct_medians [source]

To run tests please refer to this guide.

Fill the missing values in continuous columns.

cat_names variables are left untouched (their missing value will be replaced by code 0 in the TabularDataBunch). fill_strategy is adopted to replace those nans and if add_col is True, whenever a column c has missing values, a column named c_nan is added and flags the line where the value was missing.

apply_train[source][test]

apply_train(df:DataFrame) Tests found for apply_train:

  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_leaves_no_na_values [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_returns_correct_medians [source]

Some other tests where apply_train is used:

  • pytest -sv tests/test_tabular_transform.py::test_categorify [source]

To run tests please refer to this guide.

Fill missing values in self.cont_names according to self.fill_strategy.

apply_test[source][test]

apply_test(df:DataFrame) Tests found for apply_test:

  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_leaves_no_na_values [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_returns_correct_medians [source]

Some other tests where apply_test is used:

  • pytest -sv tests/test_tabular_transform.py::test_categorify [source]

To run tests please refer to this guide.

Fill missing values in self.cont_names like in apply_train.

Fills the missing values in the cont_names columns with the ones picked during train.

  1. train_df[cont_names].head()
agefnlwgteducation-numcapital-gaincapital-losshours-per-week
04910132012.00190240
14423674614.010520045
23896185NaN0032
33811284715.00040
44282297NaN0050
  1. tfm = FillMissing(cat_names, cont_names)
  2. tfm(train_df)
  3. tfm(valid_df, test=True)
  4. train_df[cont_names].head()
agefnlwgteducation-numcapital-gaincapital-losshours-per-week
04910132012.00190240
14423674614.010520045
2389618510.00032
33811284715.00040
4428229710.00050

Values missing in the education-num column are replaced by 10, which is the median of the column in train_df. Categorical variables are not changed, since nan is simply used as another category.

  1. valid_df[cont_names].head()
agefnlwgteducation-numcapital-gaincapital-losshours-per-week
800459697510.00040
8014619277910.015024060
8023637645510.00038
803255005310.00045
8043716452610.00040

FillStrategy[test]

Enum = [MEDIAN, COMMON, CONSTANT] Tests found for FillStrategy:

Some other tests where FillStrategy is used:

  • pytest -sv tests/test_tabular_transform.py::test_default_fill_strategy_is_median [source]

To run tests please refer to this guide.

Enum flag represents determines how FillMissing should handle missing/nan values

  • MEDIAN: nans are replaced by the median value of the column
  • COMMON: nans are replaced by the most common value of the column
  • CONSTANT: nans are replaced by fill_val

class Normalize[source][test]

Normalize(cat_names:StrList, cont_names:StrList) :: TabularProc Tests found for Normalize:

  • pytest -sv tests/test_tabular_transform.py::test_normalize [source]

To run tests please refer to this guide.

Normalize the continuous variables.

  1. norm = Normalize(cat_names, cont_names)

apply_train[source][test]

apply_train(df:DataFrame) Tests found for apply_train:

Some other tests where apply_train is used:

  • pytest -sv tests/test_tabular_transform.py::test_categorify [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_leaves_no_na_values [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_returns_correct_medians [source]

To run tests please refer to this guide.

Compute the means and stds of self.cont_names columns to normalize them.

  1. norm.apply_train(train_df)
  2. train_df[cont_names].head()
agefnlwgteducation-numcapital-gaincapital-losshours-per-week
00.829039-0.8125890.981643-0.1362714.416656-0.050230
10.4439770.3555322.0784501.153121-0.2287600.361492
2-0.018098-0.856881-0.115165-0.136271-0.228760-0.708985
3-0.018098-0.7131622.626854-0.136271-0.228760-0.050230
40.289952-0.976672-0.115165-0.136271-0.2287600.773213

apply_test[source][test]

apply_test(df:DataFrame) Tests found for apply_test:

Some other tests where apply_test is used:

  • pytest -sv tests/test_tabular_transform.py::test_categorify [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_leaves_no_na_values [source]
  • pytest -sv tests/test_tabular_transform.py::test_fill_missing_returns_correct_medians [source]

To run tests please refer to this guide.

Normalize self.cont_names with the same statistics as in apply_train.

  1. norm.apply_test(valid_df)
  2. valid_df[cont_names].head()
agefnlwgteducation-numcapital-gaincapital-losshours-per-week
8000.520989-0.850066-0.115165-0.136271-0.22876-0.050230
8010.598002-0.023706-0.1151651.705157-0.228761.596657
802-0.1721231.560596-0.115165-0.136271-0.22876-0.214919
803-1.019260-1.254793-0.115165-0.136271-0.228760.361492
804-0.095110-0.267403-0.115165-0.136271-0.22876-0.050230

Treating date columns

add_datepart[source][test]

add_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False) Tests found for add_datepart:

  • pytest -sv tests/test_tabular_transform.py::test_add_datepart [source]

To run tests please refer to this guide.

Helper function that adds columns relevant to a date in the column field_name of df.

Will drop the column in df if the flag is True. The time flag decides if we go down to the time parts or stick to the date parts.

  1. df = pd.DataFrame({'col1': ['02/03/2017', '02/04/2017', '02/05/2017'], 'col2': ['a', 'b', 'a']})
  2. add_datepart(df, 'col1') # inplace
  3. df.head()
col2col1Yearcol1Monthcol1Weekcol1Daycol1Dayofweekcol1Dayofyearcol1Is_month_endcol1Is_month_startcol1Is_quarter_endcol1Is_quarter_startcol1Is_year_endcol1Is_year_startcol1Elapsed
0a2017253434FalseFalseFalseFalseFalseFalse1486080000
1b2017254535FalseFalseFalseFalseFalseFalse1486166400
2a2017255636FalseFalseFalseFalseFalseFalse1486252800
  1. show_doc(add_cyclic_datepart)

add_cyclic_datepart[source][test]

add_cyclic_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False, add_linear:bool=False) No tests found for add_cyclic_datepart. To contribute a test please refer to this guide and this discussion.

Helper function that adds trigonometric date/time features to a date in the column field_name of df.

  1. df = pd.DataFrame({'col1': ['02/03/2017', '02/04/2017', '02/05/2017'], 'col2': ['a', 'b', 'a']})
  2. df = add_cyclic_datepart(df, 'col1') # returns a dataframe
  3. df.head()
col2col1weekday_coscol1weekday_sincol1day_month_coscol1day_month_sincol1month_year_coscol1month_year_sincol1day_year_coscol1day_year_sin
0a-0.900969-0.4338840.9009690.4338840.8660250.50.8429420.538005
1b-0.222521-0.9749280.7818310.6234900.8660250.50.8335560.552435
2a0.623490-0.7818310.6234900.7818310.8660250.50.8239230.566702

Splitting data into cat and cont

cont_cat_split[source][test]

cont_cat_split(df, max_card=20, dep_var=None) → Tuple[List[T], List[T]] Tests found for cont_cat_split:

  • pytest -sv tests/test_tabular_transform.py::test_cont_cat_split [source]

To run tests please refer to this guide.

Helper function that returns column names of cont and cat variables from given df.

Parameters:

  • df: A pandas data frame.
  • max_card: Maximum cardinality of a numerical categorical variable.
  • dep_var: A dependent variable.

Return:

  • cont_names: A list of names of continuous variables.
  • cat_names: A list of names of categorical variables.
  1. df = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['a', 'b', 'a'], 'col3': [0.5, 1.2, 7.5], 'col4': ['ab', 'o', 'o']})
  2. df
col1col2col3col4
01a0.5ab
12b1.2o
23a7.5o
  1. cont_list, cat_list = cont_cat_split(df=df, max_card=20, dep_var='col4')
  2. cont_list, cat_list
  1. (['col3'], ['col1', 'col2'])

Company logo

©2021 fast.ai. All rights reserved.
Site last generated: Jan 5, 2021