EDA for ML
Exploratory data analysis is the first step before building any model. You need to understand the shape of your data before choosing algorithms and preprocessing. Skipping it leads to poor models and wasted time. This page uses a synthetic classification dataset; the same patterns apply to any tabular data.
Every code block runs in a container in the companion repository, so the numbers and figure are real.
Load the data
Section titled “Load the data”from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom sklearn.datasets import make_classification
out = Path("outputs")out.mkdir(exist_ok=True)
features, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=2, weights=[0.85, 0.15], random_state=42)feature_names = [f"feature_{i}" for i in range(10)]df = pd.DataFrame(features, columns=feature_names)df["target"] = yprint(df.shape)(1000, 11)Target distribution
Section titled “Target distribution”The first thing to check is the target. For classification, this reveals class imbalance.
print(df["target"].value_counts(normalize=True).to_string())target0 0.8461 0.154This 85/15 split matters: a model that always predicts class 0 scores 85% accuracy without learning anything, accuracy becomes misleading, and the minority class is usually the one you care about (disease positive). For regression, plot the target histogram and check for skew; a heavily skewed target may benefit from a log transform.
Missing values
Section titled “Missing values”missing = df.isnull().sum()missing_pct = (missing / len(df) * 100).round(1)print(f"Columns with missing values: {(missing > 0).sum()}")if (missing > 0).any(): print(missing_pct[missing > 0].to_string())Columns with missing values: 0The synthetic data has no missing values, so the filter prints nothing more. Rules of thumb: under 5% missing, simple imputation is fine; 5 to 30%, consider whether missingness is informative; over 30%, consider dropping the column or adding a “was-missing” indicator.
Descriptive statistics
Section titled “Descriptive statistics”print(df.describe().round(2).T.to_string()) count mean std min 25% 50% 75% maxfeature_0 1000.0 0.12 1.62 -4.66 -1.04 0.23 1.26 4.72feature_1 1000.0 -0.01 1.53 -4.47 -1.18 -0.15 1.05 4.84feature_2 1000.0 -0.07 1.02 -3.03 -0.78 -0.04 0.64 3.28feature_3 1000.0 -0.89 1.18 -4.42 -1.65 -0.97 -0.25 5.44feature_4 1000.0 0.82 1.20 -3.72 0.16 0.84 1.53 5.94feature_5 1000.0 0.81 1.70 -4.34 -0.30 0.77 1.89 7.09feature_6 1000.0 0.51 2.19 -7.30 -0.89 0.52 2.01 7.46feature_7 1000.0 0.02 1.03 -3.25 -0.68 0.03 0.68 3.09feature_8 1000.0 -0.06 1.05 -3.58 -0.74 -0.08 0.66 2.99feature_9 1000.0 0.77 2.12 -8.10 -0.25 1.03 2.04 7.93target 1000.0 0.15 0.36 0.00 0.00 0.00 0.00 1.00Look for scale differences (which demand scaling), unusual min/max values (possible
outliers or errors), and near-zero standard deviations (features that carry no
information). Here the standard deviations run from 1.02 for feature_2 to 2.19 for
feature_6, and none is near zero.
Correlations
Section titled “Correlations”Highly correlated features are redundant. Tree models handle them fine; linear models can produce unstable coefficients.
corr = df[feature_names].corr()high_pairs = [(first, second, round(corr.loc[first, second], 3)) for i, first in enumerate(feature_names) for second in feature_names[i + 1:] if abs(corr.loc[first, second]) > 0.8]print("Highly correlated pairs (|r| > 0.8):", high_pairs or "none")Highly correlated pairs (|r| > 0.8): noneNo pairs cross 0.8 here. Real biological data often has correlated features (genes in a pathway co-express). When two features are highly correlated, drop one, combine them, or leave them if you use tree-based models.
Which features separate the classes?
Section titled “Which features separate the classes?”class_means = df.groupby("target").mean().round(2)# Show the first five features.print(class_means.iloc[:, :5].reset_index().to_string(index=False)) target feature_0 feature_1 feature_2 feature_3 feature_4 0 -0.05 -0.04 -0.08 -1.03 0.94 1 1.07 0.14 -0.01 -0.09 0.16Features whose means differ between classes carry signal. feature_0 goes from -0.05
to 1.07 across the classes; feature_3 from -1.03 to -0.09. A per-feature histogram
colored by class makes this visual.
fig, axes = plt.subplots(2, 5, figsize=(15, 6))for ax, col in zip(axes.ravel(), feature_names): ax.hist(df.loc[df["target"] == 0, col], bins=30, alpha=0.5, label="0") ax.hist(df.loc[df["target"] == 1, col], bins=30, alpha=0.5, label="1") ax.set_title(col, fontsize=9) ax.legend(fontsize=6)fig.tight_layout()fig.savefig(out / "feature-distributions.png", dpi=150)plt.close(fig)
Features whose two histograms overlap heavily are less useful than those where the classes separate.
Outliers
Section titled “Outliers”from scipy import stats
z = pd.DataFrame(np.abs(stats.zscore(df[feature_names])), columns=feature_names)outliers = (z > 3).sum().sort_values(ascending=False)print(outliers[outliers > 0].to_string())feature_3 16feature_9 10feature_4 6feature_6 4feature_8 4feature_1 3feature_7 3feature_5 3feature_2 2A handful of outliers per feature is normal for 1000 samples. feature_3 has 16, worth
a look. Options: cap at a percentile, remove if they are errors, transform to reduce
skew, or do nothing (tree models are robust).
Duplicates
Section titled “Duplicates”print(f"Duplicate rows: {df.duplicated().sum()}")Duplicate rows: 0A duplicate that lands in both train and test causes leakage. Deduplicate before splitting.
Checklist
Section titled “Checklist”| Question | Check |
|---|---|
| How large is the dataset? | df.shape |
| Is the target balanced? | value_counts(normalize=True) |
| Missing values? | df.isnull().sum() |
| Feature scales similar? | df.describe() |
| Highly correlated features? | correlation matrix, threshold 0.8 |
| Which features separate classes? | group by target, compare means |
| Outliers? | z-scores or IQR |
| Duplicates? | df.duplicated().sum() |
Next steps
Section titled “Next steps”Now that you understand the data, the next page covers Preprocessing & Data Leakage, where you prepare it for modeling without leaking information.
Further reading
Section titled “Further reading”-
scikit-learn feature selection
The guide distinguishes variance filters, univariate tests, and estimator-based selection. Those distinctions help assess what a target-conditioned plot can establish about a feature.
-
The feature-selection example demonstrates leakage from evaluation data. Keep exploratory choices that use the target inside development data before evaluating the final model.