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.
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:
Define the target (the class we want to predict) and check whether the classes are balanced
Split train and test respecting time
Build pipelines (preprocessing + model) with sklearn
Tune hyperparameters with Grid Search and cross-validation (4 folds)
Retrain the best model on the whole training set
Evaluate on the test set: confusion matrix, precision, recall and F1
Select features and see how fewer variables affect performance
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.
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.
# 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 inenumerate(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:
That way December (12) ends up “close” to January (1), which wouldn’t happen using the month number directly.
Code
mes = dataset["Date"].dt.monthdataset["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 notin NAO_FEATURES]print(f"{len(FEATURES)} features")FEATURES[:10]
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
from sklearn.model_selection import train_test_splitX_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 objectcv = TimeSeriesSplit(n_splits=4)# it works through the split methodfig, ax = plt.subplots(figsize=(12, 3))for i, (idx_tr, idx_val) inenumerate(cv.split(X_train)): ax.scatter(datas_train.iloc[idx_tr], [i] *len(idx_tr), color=AZUL, marker="|", s=200, label="train"if i ==0elseNone) ax.scatter(datas_train.iloc[idx_val], [i] *len(idx_val), color=LARANJA, marker="|", s=200, label="validation"if i ==0elseNone)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 inrange(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:
StandardScaler: standardization, giving each feature mean 0 and standard deviation 1: \(z = \frac{x - \mu}{\sigma}\)
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.
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.
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.
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.
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 combinationres_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 inenumerate(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 testmelhor = 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)
plot_df = metricas[["Precisão (macro)", "Recall (macro)", "F1 (macro)"]].iloc[::-1]y = np.arange(len(plot_df))altura =0.26fig, ax = plt.subplots(figsize=(10, 6))for i, (metrica, cor) inenumerate(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 inzip(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-validationprint(f"Chosen model: {melhor}\n")print(classification_report(y_test, previsoes[melhor], target_names=["Fit", "Unfit"], digits=3))
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 daysgrupo = [f"{v}_day_{d}"for v in ["tp_mm", "ro_mm", "swvl1"] for d inrange(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.
# same Grid Search + retraining, now with only the 15 featuresbuscas_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 testcomp = 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
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.
Which features most influence the predictions?
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
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 setperm = 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().indexfig, 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) inenumerate(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 >1else''})", 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
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?
Change METRICA to "balanced_accuracy" or "recall". What happens to the confusion matrix?
Use only the day_1 and day_2 features (where the correlation was highest). Does performance drop?
Add a new algorithm (for example HistGradientBoostingClassifier or MLPClassifier) by adding just one more entry to the modelos dictionary.