Sub topic 2
What makes tabular data different
This chapter assumes you know basic pandas, the scikit-learn fit/predict interface, and what features, labels, and train/test splits are. It explains the properties of rows-and-columns data that drive the model choices in the rest of the tutorial. Knowing these properties lets you predict which models will struggle before you run them.
What "tabular" means in practice
Tabular data is a table where each row is one example (a customer, a loan, a machine reading) and each column is a feature with its own meaning. Images, audio, and text have a different structure. Neighboring pixels or words are related, and the same pattern can appear anywhere in the input. In a table, the columns have no natural order or neighborhood. Swapping age and income changes nothing about the problem.
This has a direct consequence. Models built to exploit spatial or sequential structure, such as convolutions, have little to work with here. Models that treat each column on its own terms, such as trees, fit the data well.
Heterogeneous columns
A single table usually mixes several kinds of columns:
| Column kind | Example | Typical issue |
|---|---|---|
| Continuous numeric | `income` | Skewed, outliers, very different scale from other columns |
| Discrete numeric | `number_of_children` | Counts, many ties |
| Low-cardinality categorical | `city` with 3 values | Needs encoding, rarely a problem |
| High-cardinality categorical | `zip_code` with thousands of values | One-hot encoding explodes the width |
| Ordinal | `education_level` | Order matters, spacing may not |
| Identifiers and timestamps | `customer_id`, `signup_date` | Often useless or leaky as raw values |
A neural network or a linear model wants every input to be a number on a comparable scale. A tree wants only that values can be compared with a threshold. This is why preprocessing (covered in a later chapter) matters more for some model families than others.
The diagram shows how each column kind is usually routed.
Profiling a table before choosing a model
Look at the data before you pick a model family. The following code builds a small table and reports the properties that matter: dtype, missing fraction, number of distinct values, and skew.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 500
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.lognormal(10.8, 0.5, n),
"city": rng.choice(["a", "b", "c"], n),
"zip_code": rng.integers(10000, 10400, n).astype(str),
})
X.loc[rng.choice(n, 25, replace=False), "income"] = np.nan
profile = pd.DataFrame({
"dtype": X.dtypes.astype(str),
"missing_frac": X.isna().mean().round(3),
"n_unique": X.nunique(),
})
print(profile)
print(X.select_dtypes("number").agg(["min", "max", "skew"]).round(2))Read the output with these questions in mind:
- Does any column have missing values? If so, you need an imputation strategy, or a model that handles missing values natively.
- Is
n_uniquelarge for a string column?zip_codehere has about 400 values. One-hot encoding it adds about 400 columns, and most categories have only a handful of rows. - Is the skew large?
incomeis right-skewed, so a few large values will dominate any distance or gradient computed on the raw scale. - Do two numeric columns differ by orders of magnitude in range? Here
agespans tens andincomespans tens of thousands.
Scale, skew, and which models care
Models differ in how they react to the shape of the numbers.
- Linear models, neural networks, support vector machines, and nearest-neighbor methods depend on the magnitude of values. Unscaled features slow optimization, make regularization penalize columns unevenly, or let one column dominate a distance.
- Decision trees and the ensembles built on them (random forests, gradient boosting) only compare a value to a threshold. Any strictly increasing transform of a column, such as taking a log, gives the same ordering of values and therefore essentially the same splits.
You can check this directly. The example below compares a tree and a nearest-neighbor model on income on its raw scale and after a log transform. The labels depend on both columns.
import numpy as np
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
rng = np.random.default_rng(0)
n = 500
age = rng.integers(18, 80, n).astype(float)
income = rng.lognormal(10.8, 0.5, n)
y = ((age > 45) ^ (income > np.median(income))).astype(int)
X_raw = np.column_stack([age, income])
X_log = np.column_stack([age, np.log(income)])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for name, model in [
("tree", DecisionTreeClassifier(max_depth=4, random_state=0)),
("knn", KNeighborsClassifier()),
]:
raw = cross_val_score(model, X_raw, y, cv=cv).mean()
log = cross_val_score(model, X_log, y, cv=cv).mean()
print(f"{name}: raw={raw:.3f} log={log:.3f}")Expect the tree's two scores to be close. They are not guaranteed to match exactly, because split thresholds are placed between training values and a test point can fall on a different side after the transform. Expect the nearest-neighbor scores to differ clearly. On the raw scale, income dominates the distance and age is almost ignored.
Missing values carry information
In tabular data, a missing value is often not random. A blank income may mean the applicant declined to answer, which can itself predict the outcome. Two practical points follow:
- Median or mean imputation hides the fact that a value was missing. Adding a missing-indicator column (scikit-learn's
SimpleImputer(add_indicator=True)) preserves that signal. - Some tree implementations, including
HistGradientBoostingClassifier, acceptNaNdirectly and learn which side of a split missing values should go to.
Categorical features and cardinality
Low-cardinality categories are easy: one-hot encoding turns each value into a 0/1 column. High-cardinality columns need more care.
- One-hot encoding thousands of values creates a wide, sparse matrix. Linear models cope, but trees waste splits on rare categories.
- Frequency encoding replaces each category with how often it appears. It is simple and does not use the label.
- Target encoding replaces each category with the average label for that category. It is compact but uses the label, so it must be fitted inside each training fold. Fitting it on all the data leaks the answer into the features.
Interactions, irregular functions, and uninformative columns
Tabular targets often depend on thresholds and interactions: a risk jumps above a certain age, and only for certain regions. Trees represent such step-like, interacting patterns directly. A linear model represents them only if you add the right interaction and transformed columns by hand. Neural networks can learn smooth functions well, but they tend to struggle with the abrupt, irregular boundaries common in tables, which is one reason they are not the default (the chapter on neural networks returns to this).
Tables also commonly contain many columns that carry no signal. Tree ensembles tend to tolerate these, because splits choose the useful columns. Distance-based models treat every column as equally important and degrade as irrelevant columns pile up.
Size and noise
Most real tables have hundreds to a few million rows, which is small next to the data sets used for images or text. With few rows, flexible models overfit easily and the variance of your validation score is high. Labels are often noisy, and the achievable ceiling may be modest. Keep two habits in mind:
- Report the spread across folds, not only the mean. A difference smaller than the fold-to-fold standard deviation is weak evidence.
- Compare against a simple baseline. On noisy tables, a regularized linear model often lands close to far more complex ones.
Common errors
- Scaling all columns "just in case" and then reporting that scaling mattered for a tree. It did not, and you only added code.
- Fitting imputers, scalers, or encoders on the full table before cross-validation. Use a pipeline so they are fitted inside each fold.
- One-hot encoding a high-cardinality column and not noticing that the matrix grew from 10 columns to thousands.
- Treating an ordinal column as plain categories, or a category code as a number. Integer codes such as
city = 1, 2, 3imply an order and spacing that do not exist. - Ignoring that missingness is informative and discarding it during imputation.
Summary of implications for model choice
| Property of the table | Favors | Be careful with |
|---|---|---|
| Mixed types, thresholds, interactions | Tree ensembles | Linear models without feature engineering |
| Skewed, differently scaled numerics | Trees, or any model after scaling | Distance-based models on raw values |
| Many missing values | Models with native `NaN` handling, or imputation with indicators | Dropping rows |
| High-cardinality categories | Target or frequency encoding inside folds, native categorical support | One-hot encoding thousands of values |
| Small, noisy data | Regularized linear models, shallow ensembles | Large neural networks |
Exercise
You have a table with a numeric column income (heavily right-skewed), a column zip_code with 4,000 distinct values, and 8% missing values in income. You plan to compare a logistic regression and a gradient-boosted tree model. Name one preprocessing decision for each of the three issues, and say whether the choice differs between the two models.
Show answer
Skewed income: logistic regression benefits from a log transform and scaling, because it is sensitive to magnitude. The gradient-boosted tree does not need either, since it only compares values to thresholds. High-cardinality zip_code: avoid one-hot encoding 4,000 values. Use frequency or target encoding, with target encoding fitted inside each training fold to avoid leakage. Both models can use it. Missing income: impute (for example with the median) and add a missing-indicator column for logistic regression. The gradient-boosted tree can take NaN natively, although imputation with an indicator also works. In all cases, put these steps in a pipeline so they are fitted inside each cross-validation fold.