Skip to main content

Machine Learning I

Colab link

Open In Colab

Predicting beach water quality (balneabilidade) with climate variables

Inspiration: predict the water quality of a specific beach in the state of São Paulo.

Browsing some Kaggle datasets, the beach water quality dataset was quite complete, with many years of data. On top of that, this dataset invites us to work with time series, which are much harder to predict than datasets without a temporal component. Here we go straight to the harder scenarios.

Dataset: Beach water quality in the state of São Paulo

The dataset contains a series of beaches with water quality data for one parameter: Enterococcus. This is a very important water quality parameter because it is a bioindicator of sewage discharge.

However, this dataset has no predictor variables, so we prepared the dataset in the notebook dataset_preparation.ipynb and downloaded ERA5 data directly from Earth Data Hub. We collected 7 variables to use as predictors: - Total precipitation (tp) - Runoff (ro) - Top soil moisture (swl1) - 2 m temperature (t2m) - Downward solar radiation (ssrd) - U10 and v10, the two orthogonal wind components, which are turned into wind speed.

The idea is that, for each variable, we take the 7 days before each sample was collected. So we have 6 climate variables over 7 previous days, totaling 42 predictor variables for our machine learning pipeline.

Before we start, let’s think together: using ONLY climate variables, could we predict whether a specific beach will be unfit for bathing the next day?

We could easily do this for every beach in SP, but to avoid a very large volume of data here, we’ll focus on Perequê beach in Guarujá, SP.

In this class we’ll walk through the standard workflow of a supervised machine learning project:

  1. Define the target (the class we want to predict) and check whether the classes are balanced
  2. Split train and test respecting time
  3. Build pipelines (preprocessing + model) with sklearn
  4. Tune hyperparameters with Grid Search and cross-validation (4 folds)
  5. Retrain the best model on the whole training set
  6. Evaluate on the test set: confusion matrix, precision, recall and F1
  7. Select features and see how fewer variables affect performance
  8. Interpret the best model: which variables influence the prediction, and in which direction

The data comes from the dataset_preparation.ipynb notebook: 445 Enterococcus samples from CETESB (2012–2021) and, for each sample, 7 ERA5-Land variables on each of the 7 previous days.

Code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import TimeSeriesSplit, GridSearchCV, cross_val_score
from sklearn.base import clone
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.metrics import (precision_score, recall_score, f1_score, accuracy_score,
                             confusion_matrix, ConfusionMatrixDisplay, classification_report)
from sklearn.inspection import permutation_importance

# chart colors and style
AZUL, LARANJA, VERDE, CINZA, TINTA = "#2a78d6", "#eb6834", "#1baf7a", "#898781", "#52514e"
plt.rcParams.update({
    "axes.spines.top": False, "axes.spines.right": False,
    "axes.edgecolor": CINZA, "axes.labelcolor": TINTA,
    "xtick.color": TINTA, "ytick.color": TINTA,
    "axes.grid": True, "grid.color": "#e6e5e1", "figure.dpi": 110,
})

SEED = 42

Load the dataset

Code
## if you are on Colab
#!git clone https://github.com/ftl-brazil-2026/ebook.git
Code
## if you are on Colab, read the dataset like this
## dataset = pd.read_parquet("/content/ebook/ml-dl/data/pereque_guaruja_era5_window7.parquet")
Code
dataset = pd.read_parquet("data/pereque_guaruja_era5_window7.parquet")
dataset = dataset.sort_values("Date").reset_index(drop=True)   # temporal order matters
print(dataset.shape)
dataset.head()
(445, 55)
City Beach Date Enterococcus tp_mm_day_7 ro_mm_day_7 swvl1_day_7 t2m_c_day_7 ssrd_mj_day_7 wind_speed_day_7 ... wind_onshore_day_2 tp_mm_day_1 ro_mm_day_1 swvl1_day_1 t2m_c_day_1 ssrd_mj_day_1 wind_speed_day_1 wind_onshore_day_1 tp_mm_sum_3d tp_mm_sum_7d
0 GUARUJÁ PEREQUÊ 2012-01-03 560.0 0.660896 1.351357 0.390381 21.873444 23.740416 1.739490 ... -0.556320 2.584457 1.353264 0.411865 21.748444 21.823488 3.616360 -0.770633 46.667099 51.984787
1 GUARUJÁ PEREQUÊ 2012-01-08 440.0 27.175903 9.468079 0.424561 23.475006 13.230080 1.432132 ... 1.556386 10.330200 1.836777 0.393311 24.029694 24.248320 0.314128 0.310074 17.706394 47.587513
2 GUARUJÁ PEREQUÊ 2012-01-15 228.0 5.432129 1.411438 0.401123 23.092194 20.725760 1.217795 ... 0.183443 0.972748 1.166344 0.373047 26.623444 16.678911 2.901690 -0.016875 5.425096 34.943222
3 GUARUJÁ PEREQUÊ 2012-01-22 320.0 14.640808 3.261566 0.395020 25.310944 16.359425 1.284021 ... 0.958184 16.357422 7.972717 0.420654 25.068756 24.608768 0.821181 0.306810 46.501160 131.713867
4 GUARUJÁ PEREQUÊ 2012-01-29 104.0 1.498222 2.056122 0.414307 24.451569 15.360000 1.273596 ... 1.071924 4.589081 5.233765 0.417480 20.482819 19.234816 1.847250 -0.491982 82.912445 116.492271

5 rows × 55 columns

Code
dataset.columns
Index(['City', 'Beach', 'Date', 'Enterococcus', 'tp_mm_day_7', 'ro_mm_day_7',
       'swvl1_day_7', 't2m_c_day_7', 'ssrd_mj_day_7', 'wind_speed_day_7',
       'wind_onshore_day_7', 'tp_mm_day_6', 'ro_mm_day_6', 'swvl1_day_6',
       't2m_c_day_6', 'ssrd_mj_day_6', 'wind_speed_day_6',
       'wind_onshore_day_6', 'tp_mm_day_5', 'ro_mm_day_5', 'swvl1_day_5',
       't2m_c_day_5', 'ssrd_mj_day_5', 'wind_speed_day_5',
       'wind_onshore_day_5', 'tp_mm_day_4', 'ro_mm_day_4', 'swvl1_day_4',
       't2m_c_day_4', 'ssrd_mj_day_4', 'wind_speed_day_4',
       'wind_onshore_day_4', 'tp_mm_day_3', 'ro_mm_day_3', 'swvl1_day_3',
       't2m_c_day_3', 'ssrd_mj_day_3', 'wind_speed_day_3',
       'wind_onshore_day_3', 'tp_mm_day_2', 'ro_mm_day_2', 'swvl1_day_2',
       't2m_c_day_2', 'ssrd_mj_day_2', 'wind_speed_day_2',
       'wind_onshore_day_2', 'tp_mm_day_1', 'ro_mm_day_1', 'swvl1_day_1',
       't2m_c_day_1', 'ssrd_mj_day_1', 'wind_speed_day_1',
       'wind_onshore_day_1', 'tp_mm_sum_3d', 'tp_mm_sum_7d'],
      dtype='str')

Define the target variable for binary classification

CONAMA Resolution 274/2000 uses Enterococcus to classify beach water quality. Here we adopt the following rule:

Enterococcus (CFU/100 mL) Class Label
≤ 200 Fit (good water, “própria”) 0
> 200 Unfit (bad water, “imprópria”) 1

Class 1 (unfit) is the positive class: it’s the event we want to detect.

Code
LIMIAR = 400
dataset["impropria"] = (dataset["Enterococcus"] > LIMIAR).astype(int)
NOMES_CLASSES = ["Própria (0)", "Imprópria (1)"]

dataset["impropria"].value_counts().rename(index=dict(enumerate(NOMES_CLASSES)))
impropria
Própria (0)      249
Imprópria (1)    196
Name: count, dtype: int64

Is the dataset balanced?

A dataset is imbalanced when one class appears much more often than the other. This matters because a model that always guesses the majority class already gets a lot right, and looks good without having learned anything.

Code
contagem = dataset["impropria"].value_counts().sort_index()
por_ano = dataset.groupby(dataset["Date"].dt.year)["Enterococcus"].mean()

fig, axes = plt.subplots(1, 2, figsize=(12, 4), width_ratios=[1, 2])

axes[0].bar(NOMES_CLASSES, contagem.values, color=[AZUL, LARANJA], width=0.6)
for x, n in enumerate(contagem.values):
    axes[0].text(x, n + 5, f"{n}\n({n / contagem.sum():.0%})", ha="center", color=TINTA)
axes[0].set(ylabel="Number of samples", title="Class balance", ylim=(0, contagem.max() * 1.2))
axes[0].grid(axis="x", visible=False)

axes[1].bar(por_ano.index, por_ano.values, color=LARANJA, width=0.6)
axes[1].axhline(dataset["impropria"].mean() * 100, color=CINZA, ls="--", lw=1)
axes[1].axvline(2018.5, color=TINTA, lw=1)
axes[1].text(2018.4, 970, "train ", ha="right", color=TINTA)
axes[1].text(2018.6, 970, "test", ha="left", color=TINTA)
axes[1].set(ylabel="% of unfit samples", title="Fraction of unfit samples per year",
            ylim=(0, 1000), xticks=por_ano.index)
axes[1].grid(axis="x", visible=False)
plt.tight_layout()
plt.show()

Code
# effect of seasonality 
contagem = dataset["impropria"].value_counts().sort_index()
por_mes = dataset.groupby(dataset["Date"].dt.month)["Enterococcus"].mean()

fig, axes = plt.subplots(1, 2, figsize=(12, 4), width_ratios=[1, 2])

axes[0].bar(NOMES_CLASSES, contagem.values, color=[AZUL, LARANJA], width=0.6)
for x, n in enumerate(contagem.values):
    axes[0].text(x, n + 5, f"{n}\n({n / contagem.sum():.0%})", ha="center", color=TINTA)
axes[0].set(ylabel="Number of samples", title="Class balance", ylim=(0, contagem.max() * 1.2))
axes[0].grid(axis="x", visible=False)

axes[1].bar(por_mes.index, por_mes.values, color=LARANJA, width=0.6)
axes[1].axhline(dataset["impropria"].mean() * 100, color=CINZA, ls="--", lw=1)
axes[1].set(ylabel="% of unfit samples", title="Fraction of unfit samples per month",
            ylim=(0, 1000), xticks=por_mes.index)
axes[1].grid(axis="x", visible=False)
plt.tight_layout()
plt.show()

Predictor variables (features)

We use the 7 ERA5-Land variables on each of the 7 previous days (day_7 … day_1) and the rainfall accumulations. In the exploratory analysis we saw some seasonality, so we add the month with a cyclical encoding:

\[\text{mes\_sin} = \sin\left(\frac{2\pi \cdot \text{month}}{12}\right), \qquad \text{mes\_cos} = \cos\left(\frac{2\pi \cdot \text{month}}{12}\right)\]

That way December (12) ends up “close” to January (1), which wouldn’t happen using the month number directly.

Code
mes = dataset["Date"].dt.month
dataset["mes_sin"] = np.sin(2 * np.pi * mes / 12)
dataset["mes_cos"] = np.cos(2 * np.pi * mes / 12)

NAO_FEATURES = ["City", "Beach", "Date", "Enterococcus", "impropria"]
FEATURES = [c for c in dataset.columns if c not in NAO_FEATURES]
print(f"{len(FEATURES)} features")
FEATURES[:10]
53 features
['tp_mm_day_7',
 'ro_mm_day_7',
 'swvl1_day_7',
 't2m_c_day_7',
 'ssrd_mj_day_7',
 'wind_speed_day_7',
 'wind_onshore_day_7',
 'tp_mm_day_6',
 'ro_mm_day_6',
 'swvl1_day_6']

Train/test split respecting time

With time series we cannot shuffle the data before splitting. If we mix it up, the model trains on 2020 samples and is tested on 2015: it “sees the future”, and the test score becomes too optimistic (data leakage). In real life, we train on the past and predict the future.

  • Train (and validation): 2012–2018, about 80% of the samples
  • Test: 2019–2021, about 20% of the samples, kept under lock and key until the end
Code
treino = dataset["Date"].dt.year <= 2018

X_train, y_train = dataset.loc[treino, FEATURES], dataset.loc[treino, "impropria"]
X_test, y_test = dataset.loc[~treino, FEATURES], dataset.loc[~treino, "impropria"]
datas_train, datas_test = dataset.loc[treino, "Date"], dataset.loc[~treino, "Date"]

pd.DataFrame({
    "coletas": [len(y_train), len(y_test)],
    "% do total": [len(y_train) / len(dataset) * 100, len(y_test) / len(dataset) * 100],
    "% impróprias": [y_train.mean() * 100, y_test.mean() * 100],
    "período": [f"{datas_train.min():%Y-%m} a {datas_train.max():%Y-%m}", f"{datas_test.min():%Y-%m} a {datas_test.max():%Y-%m}"],
}, index=["treino", "teste"]).round(1)
coletas % do total % impróprias período
treino 356 80.0 43.5 2012-01 a 2018-12
teste 89 20.0 46.1 2019-01 a 2021-07

Take a look at sklearn's train_test_split function!

train_test_split

Code
from sklearn.model_selection import train_test_split

X_train_s = dataset.drop(columns=['Enterococcus','impropria']).sort_values(by=['Date'])
Y_target = dataset['impropria']
X_train_s, X_test_s, y_train_s, y_test_s = train_test_split(X_train_s, Y_target, shuffle=False, test_size=0.2)

## what's the problem here? 
#X_train_s['Date'].max()

Temporal cross-validation (4 folds)

As we saw in the theory class, to choose hyperparameters we need validation data, without touching the test set.

Cross-validation splits the training set into k parts (folds) and evaluates the model k times.

With regular KFold the folds are shuffled, and the model can train on the future and validate on the past. With temporal data we use TimeSeriesSplit, which ensures that in each fold the model trains on everything that came before and validates on the next block. The training set grows with each fold.

Code
# create the TimeSeriesSplit object
cv = TimeSeriesSplit(n_splits=4)

# it works through the split method
fig, ax = plt.subplots(figsize=(12, 3))
for i, (idx_tr, idx_val) in enumerate(cv.split(X_train)):
    ax.scatter(datas_train.iloc[idx_tr], [i] * len(idx_tr), color=AZUL, marker="|", s=200, label="train" if i == 0 else None)
    ax.scatter(datas_train.iloc[idx_val], [i] * len(idx_val), color=LARANJA, marker="|", s=200, label="validation" if i == 0 else None)
ax.scatter(datas_test, [4] * len(datas_test), color=CINZA, marker="|", s=200, label="test (not used in CV)")
ax.set(yticks=range(5), yticklabels=[f"fold {i + 1}" for i in range(4)] + ["test"], title="TimeSeriesSplit com 4 folds")
ax.invert_yaxis()
ax.grid(axis="y", visible=False)
ax.legend(frameon=False, loc="upper center", bbox_to_anchor=(0.5, -0.15), ncols=3)
plt.show()

Preprocessing and model in a single object

We’ll use a very handy class for keeping the code clean and readable: Pipeline, which chains the steps together logically. Here each pipeline has two:

  1. StandardScaler: standardization, giving each feature mean 0 and standard deviation 1: \(z = \frac{x - \mu}{\sigma}\)
  2. the classifier

Why does this matter so much?

  • Avoids leakage: inside cross-validation, StandardScaler computes \(\mu\) and \(\sigma\) using only each fold’s training data. If we standardized the whole dataset first, validation would peek at the future mean (data leak).
  • Organization: switching algorithms means swapping one piece; the rest of the code stays the same.
  • Scale: KNN, SVM and logistic regression depend on distances or weights, so variables on different scales (radiation in MJ/m², rain in mm) would distort the model. Trees don’t need it, but we keep the same format for all of them.
Code
# example: a simple pipeline
exemplo = Pipeline([
    ("scaler", StandardScaler()),
    ("modelo", LogisticRegression(max_iter=5000)),
])
exemplo
Pipeline(steps=[('scaler', StandardScaler()),
                ('modelo', LogisticRegression(max_iter=5000))])
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

Optimization metric: F1

We’ve already seen that accuracy can be misleading. So we’ll go with F1, which combines two questions:

  • Precision: of the times the model said “unfit”, how many really were? \(\frac{TP}{TP + FP}\)
  • Recall (sensitivity): of the samples that really were unfit, how many did the model catch? \(\frac{TP}{TP + FN}\)
  • F1: the harmonic mean of the two, \(F1 = 2 \cdot \frac{\text{precision} \cdot \text{recall}}{\text{precision} + \text{recall}}\)

F1 is computed for one class. We have two options:

scoring What it measures
"f1" F1 of the positive class (unfit) ONLY
"f1_macro" simple average of the F1 of the unfit class and the F1 of the fit class

Baseline: the Dummy model

Before any algorithm, we measure a DummyClassifier that always answers “unfit”. Any real model has to beat this value to be worth it.

Code
baseline = Pipeline([("scaler", StandardScaler()), ("modelo", DummyClassifier(strategy="constant", constant=1))])

for scoring in ["f1", "f1_macro"]:
    s = cross_val_score(baseline, X_train, y_train, cv=cv, scoring=scoring)
    print(f"Baseline, {scoring:<9}: {s.mean():.3f} ± {s.std():.3f}")
Baseline, f1       : 0.599 ± 0.053
Baseline, f1_macro : 0.300 ± 0.026
Code
METRICA = "f1_macro"
f1_baseline_cv = cross_val_score(baseline, 
                                 X_train, 
                                 y_train, 
                                 cv=cv, 
                                 scoring=METRICA)

Hyperparameters

Algorithm Idea Hyperparameters tested
Logistic Regression linear boundary; gives the class probability C (inverse of regularization), l1_ratio (0 = L2/Ridge, 1 = L1/Lasso)
KNN votes with the k most similar neighbors n_neighbors, neighbor weighting
SVM (RBF) non-linear boundary with maximum margin C, gamma
Decision Tree a sequence of “yes/no” questions about the features depth, minimum samples per leaf
Random Forest average of many trees trained on different samples depth, leaves, number of features per split
Gradient Boosting trees in sequence, each correcting the previous one’s error number of trees, learning rate, depth

class_weight="balanced" gives more weight to the minority class (fit) during training, a simple way to deal with imbalance. We let Grid Search decide whether to use it.

In pipelines, the step name + __ + parameter name says which piece the hyperparameter belongs to: modelo__C is the C of the "modelo" step.

Code
def pipeline(modelo):
    return Pipeline([("scaler", StandardScaler()), ("modelo", modelo)])

modelos = {
    "Regressão Logística": (
        pipeline(LogisticRegression(solver="liblinear", max_iter=5000)),
        {"modelo__C": [0.001, 0.01, 0.1, 1, 10],
         "modelo__l1_ratio": [0, 1],
         "modelo__class_weight": [None, "balanced"]},
    ),
    "KNN": (
        pipeline(KNeighborsClassifier()),
        {"modelo__n_neighbors": [3, 5, 11, 21, 31],
         "modelo__weights": ["uniform", "distance"]},
    ),
    "SVM": (
        pipeline(SVC(kernel="rbf", random_state=SEED)),
        {"modelo__C": [0.1, 1, 10],
         "modelo__gamma": ["scale", 0.01, 0.001],
         "modelo__class_weight": [None, "balanced"]},
    ),
    "Árvore de Decisão": (
        pipeline(DecisionTreeClassifier(random_state=SEED)),
        {"modelo__max_depth": [2, 3, 5, 8, None],
         "modelo__min_samples_leaf": [1, 5, 10, 20],
         "modelo__class_weight": [None, "balanced"]},
    ),
    "Random Forest": (
        pipeline(RandomForestClassifier(n_estimators=300, random_state=SEED, n_jobs=-1)),
        {"modelo__max_depth": [3, 5, 10, None],
         "modelo__min_samples_leaf": [1, 5, 10],
         "modelo__max_features": ["sqrt", 0.3],
         "modelo__class_weight": [None, "balanced"]},
    ),
    "Gradient Boosting": (
        pipeline(GradientBoostingClassifier(random_state=SEED)),
        {"modelo__n_estimators": [100, 300],
         "modelo__learning_rate": [0.01, 0.05, 0.1],
         "modelo__max_depth": [2, 3]},
    ),
}

for nome, (_, grade) in modelos.items():
    n = np.prod([len(v) for v in grade.values()])
    print(f"{nome:<20} {n:>3} combinations × 4 folds = {n * 4:>3} fits")
Regressão Logística   20 combinações × 4 folds =  80 treinos
KNN                   10 combinações × 4 folds =  40 treinos
SVM                   18 combinações × 4 folds =  72 treinos
Árvore de Decisão     40 combinações × 4 folds = 160 treinos
Random Forest         48 combinações × 4 folds = 192 treinos
Gradient Boosting     12 combinações × 4 folds =  48 treinos

Grid Search with cross-validation

For each algorithm, GridSearchCV tests every combination in the grid. Each combination is trained and validated on the 4 temporal folds, and the best is the one with the highest mean macro F1 on validation.

Code
buscas = {}
for nome, (pipe, grade) in modelos.items():
    busca = GridSearchCV(pipe, grade, cv=cv, scoring=METRICA, refit=False, n_jobs=-1)
    busca.fit(X_train, y_train)
    buscas[nome] = busca
    print(f"{nome:<20} validation macro F1 = {busca.best_score_:.3f}   {busca.best_params_}")
Regressão Logística  F1 macro validação = 0.570   {'modelo__C': 0.01, 'modelo__class_weight': None, 'modelo__l1_ratio': 0}
KNN                  F1 macro validação = 0.496   {'modelo__n_neighbors': 5, 'modelo__weights': 'uniform'}
SVM                  F1 macro validação = 0.576   {'modelo__C': 10, 'modelo__class_weight': 'balanced', 'modelo__gamma': 0.01}
Árvore de Decisão    F1 macro validação = 0.559   {'modelo__class_weight': 'balanced', 'modelo__max_depth': 2, 'modelo__min_samples_leaf': 1}
Random Forest        F1 macro validação = 0.534   {'modelo__class_weight': 'balanced', 'modelo__max_depth': 5, 'modelo__max_features': 'sqrt', 'modelo__min_samples_leaf': 1}
Gradient Boosting    F1 macro validação = 0.505   {'modelo__learning_rate': 0.1, 'modelo__max_depth': 3, 'modelo__n_estimators': 100}
Code
# cross-validation results, mean and std over the 4 folds, for each model's best combination
res_cv = pd.DataFrame({
    nome: {"F1 macro (validação)": b.best_score_,
           "desvio": b.cv_results_["std_test_score"][b.best_index_]}
    for nome, b in buscas.items()
}).T.sort_values("F1 macro (validação)")

fig, ax = plt.subplots(figsize=(9, 4))
ax.barh(res_cv.index, res_cv["F1 macro (validação)"], xerr=res_cv["desvio"], color=AZUL, height=0.6,
        error_kw={"ecolor": TINTA, "lw": 1, "capsize": 3})
ax.axvline(f1_baseline_cv.mean(), color=LARANJA, ls="--", lw=1.5, label="baseline - Dummy")
ax.legend(frameon=False, loc="lower right")
for y, v in enumerate(res_cv["F1 macro (validação)"]):
    ax.text(0.02, y, f"{v:.3f}", va="center", color="white", fontweight="bold")
ax.set(xlabel="Macro F1 (mean ± std over 4 folds)", xlim=(0, 1), title="Cross-Validation Results")
ax.grid(axis="y", visible=False)
plt.show()

# the chosen model is the best on VALIDATION, never on test
melhor = res_cv["F1 macro (validação)"].idxmax()
print(f"Model chosen by cross-validation: {melhor}")

Modelo escolhido pela validação cruzada: SVM

Retrain on the whole training set

During CV, each model only saw part of the training set. Now that we know the best hyperparameters, we retrain each pipeline on the whole 2012–2018 period. clone creates a “fresh” copy of the pipeline, and set_params applies the winning hyperparameters.

Note: GridSearchCV does this by itself with refit=True (the default). Here we make it explicit so it’s clear what happens.

Code
finais = {"Baseline": clone(baseline).fit(X_train, y_train)}
for nome, (pipe, _) in modelos.items():
    finais[nome] = clone(pipe).set_params(**buscas[nome].best_params_).fit(X_train, y_train)
list(finais)
['Baseline',
 'Regressão Logística',
 'KNN',
 'SVM',
 'Árvore de Decisão',
 'Random Forest',
 'Gradient Boosting']

11. Evaluation on the test set (2019–2021)

Only now do we use the test set, exactly once. It simulates real use: predicting years the model has never seen.

Confusion matrix

Predicted: fit Predicted: unfit
Actual: fit True Negative (TN) False Positive (FP): false alarm, beach closed for nothing
Actual: unfit False Negative (FN): health risk, swimmers go into contaminated water True Positive (TP)
Code
previsoes = {nome: m.predict(X_test) for nome, m in finais.items()}

fig, axes = plt.subplots(2, 4, figsize=(16, 8))
for ax, (nome, y_pred) in zip(axes.flat, previsoes.items()):
    ConfusionMatrixDisplay(confusion_matrix(y_test, y_pred), display_labels=["Fit", "Unfit"]).plot(
        ax=ax, cmap="Blues", colorbar=False, values_format="d")
    ax.set_title(f"{nome}\nF1 macro = {f1_score(y_test, y_pred, average='macro'):.3f}", fontsize=10)
    ax.set(xlabel="Predicted", ylabel="Actual")
    ax.grid(False)
axes.flat[-1].axis("off")
plt.tight_layout()
plt.show()

Precision, recall and F1

We compute each metric for both classes and the macro average (the same one used for optimization).

Code
def metricas_teste(y_true, y_pred):
    return {
        "Precisão (macro)": precision_score(y_true, y_pred, average="macro", zero_division=0),
        "Recall (macro)": recall_score(y_true, y_pred, average="macro"),
        "F1 (macro)": f1_score(y_true, y_pred, average="macro"),
        "F1 imprópria": f1_score(y_true, y_pred, pos_label=1),
        "F1 própria": f1_score(y_true, y_pred, pos_label=0),
        "Recall imprópria": recall_score(y_true, y_pred, pos_label=1),
        "Recall própria": recall_score(y_true, y_pred, pos_label=0),
        "Acurácia": accuracy_score(y_true, y_pred),
    }

metricas = pd.DataFrame({nome: metricas_teste(y_test, y_pred) for nome, y_pred in previsoes.items()}).T
metricas = metricas.sort_values("F1 (macro)", ascending=False)
metricas.round(3)
Precisão (macro) Recall (macro) F1 (macro) F1 imprópria F1 própria Recall imprópria Recall própria Acurácia
Regressão Logística 0.642 0.629 0.627 0.556 0.698 0.488 0.771 0.640
Árvore de Decisão 0.626 0.624 0.624 0.582 0.667 0.561 0.688 0.629
Random Forest 0.586 0.586 0.584 0.575 0.593 0.610 0.562 0.584
Gradient Boosting 0.591 0.586 0.584 0.514 0.654 0.463 0.708 0.596
KNN 0.542 0.535 0.524 0.412 0.636 0.341 0.729 0.551
SVM 0.522 0.522 0.521 0.462 0.580 0.439 0.604 0.528
Baseline 0.230 0.500 0.315 0.631 0.000 1.000 0.000 0.461
Code
plot_df = metricas[["Precisão (macro)", "Recall (macro)", "F1 (macro)"]].iloc[::-1]
y = np.arange(len(plot_df))
altura = 0.26

fig, ax = plt.subplots(figsize=(10, 6))
for i, (metrica, cor) in enumerate(zip(plot_df.columns, [AZUL, LARANJA, VERDE])):
    pos = y + (1 - i) * altura
    ax.barh(pos, plot_df[metrica], height=altura - 0.03, color=cor, label=metrica)
    for p, v in zip(pos, plot_df[metrica]):
        ax.text(v + 0.005, p, f"{v:.2f}", va="center", fontsize=8, color=TINTA)
ax.set(yticks=y, yticklabels=plot_df.index, xlim=(0, 1.08), xlabel="Test score (macro average of both classes)",
       title="Metrics on the test set (2019–2021)")
ax.grid(axis="y", visible=False)
ax.legend(frameon=False, loc="upper center", bbox_to_anchor=(0.5, -0.1), ncols=3)
plt.tight_layout()
plt.show()

Code
melhor
'SVM'
Code
# full report for the model chosen by cross-validation
print(f"Chosen model: {melhor}\n")
print(classification_report(y_test, previsoes[melhor], target_names=["Fit", "Unfit"], digits=3))
Modelo escolhido: SVM

              precision    recall  f1-score   support

     Própria      0.558     0.604     0.580        48
   Imprópria      0.486     0.439     0.462        41

    accuracy                          0.528        89
   macro avg      0.522     0.522     0.521        89
weighted avg      0.525     0.528     0.525        89

Which variables does the chosen model use?

Permutation importance shuffles one feature at a time and measures how much the macro F1 drops. If F1 drops a lot, the model depends on that variable.

We compute the importance on the training data. In the next section we’ll use this ranking to select features, and any choice made by looking at the test set would contaminate the final evaluation (data leakage).

Code
melhor ="Random Forest"
Code
imp = permutation_importance(finais[melhor], X_train, 
                             y_train, 
                             scoring=METRICA, 
                             n_repeats=50, 
                             random_state=15, 
                             n_jobs=-1
                             )
importancia = pd.Series(imp.importances_mean, index=FEATURES).sort_values(ascending=False)
top = importancia.head(15).sort_values()

fig, ax = plt.subplots(figsize=(9, 5))
ax.barh(top.index, top.values, color=AZUL, height=0.6)
ax.axvline(0, color=CINZA, lw=1)
ax.set(xlabel="Mean macro F1 drop when shuffling the feature (train)", title=f"Top 15 features: {melhor}")
ax.grid(axis="y", visible=False)
plt.show()

Less is more? Retraining with only the 15 most important features

So far we’ve used 53 features for only 356 training samples. Many of these features end up representing almost the same thing:

  • today’s soil moisture is very similar to yesterday’s (variables autocorrelated in time);
  • rain, runoff and soil moisture on the same day move together (multicollinearity).

Redundant features bring no new information, but they do bring noise and more parameters to fit. With little data, this increases the risk of overfitting, and distance-based models (KNN, SVM) suffer from the curse of dimensionality: with many dimensions, all points end up “far” from each other.

First, let’s see how correlated the features are with each other.

Code
# correlation between rain, runoff and soil moisture features over the 7 days
grupo = [f"{v}_day_{d}" for v in ["tp_mm", "ro_mm", "swvl1"] for d in range(1, 8)]
corr_grupo = X_train[grupo].corr()

fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(corr_grupo, cmap="RdBu_r", vmin=-1, vmax=1, square=True, linewidths=0.5, linecolor="white",
            cbar_kws={"label": "Pearson correlation", "shrink": 0.7}, ax=ax)
ax.set_title("Correlation between features: rain, runoff and soil moisture (day_1 to day_7)")
plt.show()

# how many feature pairs (out of all 53) are strongly correlated?
corr_abs = X_train[FEATURES].corr().abs().to_numpy()
pares = corr_abs[np.triu_indices_from(corr_abs, k=1)]
print(f"{len(pares)} feature pairs")
print(f"{(pares > 0.7).sum()} pairs with |r| > 0.7 ({(pares > 0.7).mean():.0%})")
print(f"{(pares > 0.9).sum()} pairs with |r| > 0.9 ({(pares > 0.9).mean():.0%})")

1378 pares de features
37 pares com |r| > 0.7 (3%)
4 pares com |r| > 0.9 (0%)

Reading the plot: soil moisture forms an almost entirely red block: one day’s value practically repeats the previous day’s. Rain and runoff on the same day also move together.

Now we select the 15 most important features from the ranking in section 12 and repeat exactly the same process: same pipelines, same hyperparameter grid, same cross-validation and same test set. Only the list of columns changes.

Code
TOP_FEATURES = list(importancia.head(10).index)
X_train_top, X_test_top = X_train[TOP_FEATURES], X_test[TOP_FEATURES]
print(f"{len(FEATURES)} > {len(TOP_FEATURES)} features:")
TOP_FEATURES
53 > 10 features:
['ssrd_mj_day_1',
 'ssrd_mj_day_2',
 'wind_onshore_day_2',
 'wind_speed_day_5',
 'tp_mm_day_1',
 't2m_c_day_1',
 'ssrd_mj_day_7',
 'wind_onshore_day_1',
 'wind_onshore_day_3',
 'ssrd_mj_day_3']
Code
# same Grid Search + retraining, now with only the 15 features
buscas_top, finais_top = {}, {}
for nome, (pipe, grade) in modelos.items():
    busca = GridSearchCV(pipe, grade, cv=cv, scoring=METRICA, refit=False, n_jobs=-1).fit(X_train_top, y_train)
    buscas_top[nome] = busca
    finais_top[nome] = clone(pipe).set_params(**busca.best_params_).fit(X_train_top, y_train)
    print(f"{nome:<20} validation macro F1 = {busca.best_score_:.3f}   {busca.best_params_}")

previsoes_top = {nome: m.predict(X_test_top) for nome, m in finais_top.items()}
metricas_top = pd.DataFrame({nome: metricas_teste(y_test, y_pred) for nome, y_pred in previsoes_top.items()}).T
Regressão Logística  F1 macro validação = 0.574   {'modelo__C': 0.01, 'modelo__class_weight': 'balanced', 'modelo__l1_ratio': 0}
KNN                  F1 macro validação = 0.523   {'modelo__n_neighbors': 11, 'modelo__weights': 'uniform'}
SVM                  F1 macro validação = 0.553   {'modelo__C': 1, 'modelo__class_weight': None, 'modelo__gamma': 'scale'}
Árvore de Decisão    F1 macro validação = 0.601   {'modelo__class_weight': 'balanced', 'modelo__max_depth': 2, 'modelo__min_samples_leaf': 1}
Random Forest        F1 macro validação = 0.566   {'modelo__class_weight': None, 'modelo__max_depth': None, 'modelo__max_features': 'sqrt', 'modelo__min_samples_leaf': 1}
Gradient Boosting    F1 macro validação = 0.553   {'modelo__learning_rate': 0.01, 'modelo__max_depth': 2, 'modelo__n_estimators': 100}
Code
# comparison 53 features x top 15, on cross-validation and test
comp = pd.DataFrame({
    "CV, 53 features": {n: buscas[n].best_score_ for n in modelos},
    "CV, top 15": {n: buscas_top[n].best_score_ for n in modelos},
    "Teste, 53 features": metricas.loc[list(modelos), "F1 (macro)"],
    "Teste, top 15": metricas_top.loc[list(modelos), "F1 (macro)"],
})
comp["Δ teste"] = comp["Teste, top 15"] - comp["Teste, 53 features"]
comp.sort_values("Teste, top 15", ascending=False).round(3)
CV, 53 features CV, top 15 Teste, 53 features Teste, top 15 Δ teste
Regressão Logística 0.570 0.574 0.627 0.643 0.016
Árvore de Decisão 0.559 0.601 0.624 0.624 0.000
SVM 0.576 0.553 0.521 0.595 0.074
Gradient Boosting 0.505 0.553 0.584 0.575 -0.009
KNN 0.496 0.523 0.524 0.557 0.033
Random Forest 0.534 0.566 0.584 0.534 -0.051
Code
base
Regressão Logística    0.626834
Árvore de Decisão      0.624473
Random Forest          0.584060
Gradient Boosting      0.583680
KNN                    0.524064
SVM                    0.520769
Baseline               0.315385
Name: F1 (macro), dtype: float64
Code
ordem = comp.sort_values("Teste, top 15").index
y = np.arange(len(ordem))
altura = 0.38
f1_baseline_teste = metricas["F1 (macro)"]

fig, axes = plt.subplots(1, 2, figsize=(13, 4.5), sharey=True)
for ax, etapa, base in zip(axes, ["CV", "Teste"], [f1_baseline_cv.mean(), f1_baseline_teste]):
    for i, (conjunto, cor) in enumerate([("53 features", AZUL), ("top 15", LARANJA)]):
        valores = comp.loc[ordem, f"{etapa}, {conjunto}"]
        pos = y + (0.5 - i) * altura
        ax.barh(pos, valores, height=altura - 0.04, color=cor, label=conjunto)
        for p, v in zip(pos, valores):
            ax.text(v + 0.005, p, f"{v:.2f}", va="center", fontsize=8, color=TINTA)
    #ax.axvline(base, color=CINZA, ls="--", lw=1.5, label="baseline")
    ax.set(xlim=(0, 0.85), xlabel="F1 macro",
           title="Cross-validation (2012–2018)" if etapa == "CV" else "Test (2019–2021)")
    ax.grid(axis="y", visible=False)
axes[0].set(yticks=y, yticklabels=ordem)
axes[1].legend(frameon=False, loc="lower right")
plt.suptitle("All 53 features × the 15 most important", y=1.02)
plt.tight_layout()
plt.show()

Code
# confusion matrices with the 15 features
fig, axes = plt.subplots(2, 3, figsize=(12, 8))
for ax, (nome, y_pred) in zip(axes.flat, previsoes_top.items()):
    ConfusionMatrixDisplay(confusion_matrix(y_test, y_pred), display_labels=["Fit", "Unfit"]).plot(
        ax=ax, cmap="Blues", colorbar=False, values_format="d")
    ax.set_title(f"{nome} (top 15)\nF1 macro = {f1_score(y_test, y_pred, average='macro'):.3f}", fontsize=10)
    ax.set(xlabel="Predicted", ylabel="Actual")
    ax.grid(False)
plt.tight_layout()
plt.show()

14. What did the Random Forest learn?

With Random Forest we can use the feature_importances_ attribute, which is similar to the idea of permutation importance but computed internally by the RF algorithm.

  1. Which features most influence the predictions?
  2. In which direction do they influence them (more rain → higher chance of unfit?)

We’ll use these tools:

Tool How it works Caveat
Impurity importance (feature_importances_) sums how much each feature reduces impurity (Gini) in the splits of all trees computed on training data; favors continuous features with many possible values
Partial Dependence varies one feature while holding the others and observes the predicted probability shows the direction of the effect, on average
Code
pd.Series(finais["Random Forest"].named_steps["modelo"].feature_importances_, index=X_train.columns).sort_values(ascending=False)
tp_mm_day_1           0.059203
ssrd_mj_day_1         0.055660
swvl1_day_1           0.043933
tp_mm_sum_3d          0.034593
ssrd_mj_day_2         0.026952
wind_onshore_day_2    0.024993
t2m_c_day_4           0.024800
t2m_c_day_5           0.023316
ro_mm_day_1           0.022918
tp_mm_day_2           0.022050
tp_mm_sum_7d          0.021160
wind_speed_day_1      0.020664
t2m_c_day_1           0.020432
wind_onshore_day_1    0.020170
t2m_c_day_6           0.020061
ro_mm_day_2           0.019877
wind_onshore_day_3    0.019846
t2m_c_day_3           0.019645
wind_speed_day_6      0.019492
wind_speed_day_2      0.019405
ssrd_mj_day_7         0.019202
tp_mm_day_6           0.019162
t2m_c_day_2           0.018440
ro_mm_day_7           0.017060
ssrd_mj_day_6         0.016800
ssrd_mj_day_4         0.016448
tp_mm_day_3           0.016442
ssrd_mj_day_3         0.016254
swvl1_day_4           0.016156
wind_speed_day_5      0.016052
swvl1_day_7           0.015843
wind_onshore_day_6    0.015795
swvl1_day_6           0.014917
tp_mm_day_7           0.014891
swvl1_day_3           0.014738
wind_onshore_day_5    0.014716
swvl1_day_2           0.014515
wind_speed_day_4      0.014492
ro_mm_day_3           0.014209
swvl1_day_5           0.013840
wind_onshore_day_4    0.013700
t2m_c_day_7           0.013564
ro_mm_day_5           0.013197
wind_onshore_day_7    0.012911
wind_speed_day_7      0.011923
tp_mm_day_4           0.011794
wind_speed_day_3      0.011574
tp_mm_day_5           0.010911
ro_mm_day_4           0.010287
ssrd_mj_day_5         0.010105
ro_mm_day_6           0.008431
mes_cos               0.006771
mes_sin               0.005688
dtype: float64
Code
rf = finais_top["Random Forest"]

print(rf.named_steps["modelo"])   # hyperparameters chosen by Grid Search

# 1) impurity importance
imp_impureza = pd.Series(finais["Random Forest"].named_steps["modelo"].feature_importances_, index=X_train.columns).sort_values(ascending=True)


ordem = imp_impureza.index[:15]
fig, axes = plt.subplots(1, 1, figsize=(13, 5.5), sharey=True)

axes.barh(ordem[:15], imp_impureza[ordem], color=AZUL, height=0.6)
axes.set(xlabel="Mean impurity decrease (Gini)", title="Impurity importance (train)")

plt.suptitle("Random Forest (top 15): which features matter most?", y=1.01)
plt.tight_layout()
plt.show()
RandomForestClassifier(n_estimators=300, n_jobs=-1, random_state=42)

Code
pd.Series(rf.named_steps["modelo"].feature_importances_)
0    0.117647
1    0.100715
2    0.094454
3    0.099800
4    0.139573
5    0.090960
6    0.091781
7    0.094452
8    0.086867
9    0.083751
dtype: float64
Code
rf = finais_top["Random Forest"]

print(rf.named_steps["modelo"])   # hyperparameters chosen by Grid Search

# 1) impurity importance (comes with the trained model)
imp_impureza = pd.Series(rf.named_steps["modelo"].feature_importances_, index=TOP_FEATURES)

# 2) permutation importance on the test set
perm = permutation_importance(rf, X_test_top, y_test, scoring=METRICA, n_repeats=50, random_state=SEED, n_jobs=-1)
imp_perm = pd.Series(perm.importances_mean, index=TOP_FEATURES)
imp_perm_std = pd.Series(perm.importances_std, index=TOP_FEATURES)

ordem = imp_perm.sort_values().index
fig, axes = plt.subplots(1, 2, figsize=(13, 5.5), sharey=True)

axes[0].barh(ordem, imp_impureza[ordem], color=AZUL, height=0.6)
axes[0].set(xlabel="Mean impurity decrease (Gini)", title="Impurity importance (train)")

axes[1].barh(ordem, imp_perm[ordem], xerr=imp_perm_std[ordem], color=LARANJA, height=0.6,
             error_kw={"ecolor": TINTA, "lw": 1, "capsize": 2})
axes[1].axvline(0, color=CINZA, lw=1)
axes[1].set(xlabel="Macro F1 drop when shuffled (mean ± std)", title="Permutation importance (test)")

for ax in axes:
    ax.grid(axis="y", visible=False)
plt.suptitle("Random Forest (top 15): which features matter most?", y=1.01)
plt.tight_layout()
plt.show()

Importance by variable type

Each variable appears on several days of the window. Summing the importance across all days of the same variable shows which phenomenon matters most: rain, sun, wind, temperature or seasonality.

Code
def tipo_variavel(feature):
    if feature.startswith("mes_"):
        return "sazonalidade (mês)"
    nomes = {"tp_mm": "chuva", "ro_mm": "escoamento", "swvl1": "umidade do solo", "t2m_c": "temperatura",
             "ssrd_mj": "radiação solar", "wind_speed": "velocidade do vento", "wind_onshore": "vento em direção à praia"}
    return nomes[feature.rsplit("_day_", 1)[0].split("_sum_")[0]]

por_tipo = pd.DataFrame({
    "impureza (treino)": imp_impureza.groupby(tipo_variavel).sum(),
    "permutação (teste)": imp_perm.groupby(tipo_variavel).sum(),
    "nº de features": imp_perm.groupby(tipo_variavel).size(),
}).sort_values("permutação (teste)")

fig, ax = plt.subplots(figsize=(9, 4))
ax.barh(por_tipo.index, por_tipo["permutação (teste)"], color=LARANJA, height=0.6)
for y, (v, n) in enumerate(zip(por_tipo["permutação (teste)"], por_tipo["nº de features"])):
    ax.text(max(v, 0) + 0.002, y, f"{v:.3f}  ({n} feature{'s' if n > 1 else ''})", va="center", fontsize=9, color=TINTA)
ax.axvline(0, color=CINZA, lw=1)
ax.set(xlabel="Sum of permutation importance (test)", title="Which phenomenon influences the prediction most?")
ax.grid(axis="y", visible=False)
plt.show()

por_tipo.round(3)

impureza (treino) permutação (teste) nº de features
radiação solar 0.161 -0.086 4.0
vento em direção à praia 0.122 -0.068 3.0
temperatura 0.140 -0.043 1.0
velocidade do vento 0.114 -0.030 1.0
chuva 0.210 0.002 1.0
escoamento 0.106 NaN NaN
sazonalidade (mês) 0.012 NaN NaN
umidade do solo 0.134 NaN NaN

16. Discussion

  • Always compare with a baseline. A model’s real gain is its distance from that yardstick, not the absolute value.
  • Choose the metric with the problem in mind. With imbalanced classes, prefer metrics that look at both classes (f1_macro, balanced_accuracy) or decide which error is more costly (FN = health risk; FP = beach closed for nothing).
  • Choose the model on validation, evaluate on test. If we chose the “best on test”, the test would no longer be an honest estimate. Note that the model chosen by validation isn’t necessarily the one with the highest test F1: with few samples (89 in the test set, 18 of them fit), the differences between models are small and noisy. They all beat the baseline, and that’s what we can state with confidence.
  • More features isn’t always better. Redundant (correlated) features add noise and overfitting risk without adding information. Select features using only the training data.
  • Importance is not causality. The importance and partial dependence plots show what the model uses, not what causes the contamination. Use them to raise hypotheses and investigate.
  • Time shifts the distribution. The test period (2019–2021) has more unfit samples than the training period (distribution shift), which is common in environmental data.
  • Weather only explains part of the problem. Sewage, tides, currents and tourist density are not in the features, so don’t expect perfect accuracy from meteorology alone.

Exercises

  1. Change LIMIAR (threshold) to 400 (CONAMA 274’s single-sample limit). Does the dataset become more balanced? Do the models improve relative to the baseline?
  2. Change METRICA to "balanced_accuracy" or "recall". What happens to the confusion matrix?
  3. Use only the day_1 and day_2 features (where the correlation was highest). Does performance drop?
  4. Add a new algorithm (for example HistGradientBoostingClassifier or MLPClassifier) by adding just one more entry to the modelos dictionary.