Menu
CoddyTech

Validation Sets

Part of the Supervised Learning section of Coddy's Machine Learning journey. Lesson 35 of 58.

In Choosing k and Tree Depth, you kept the k or depth with the best test score. That score flatters: you kept it because it came out high.

So keep a third set for choosing, the validation set:

A bar split into three parts: training rows 60%, used to fit every candidate; validation 20%, used to choose; test 20%, used to report once

Two splits make it. 0.25 of the remaining 80% is 20%:

X_rest, X_test, y_rest, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
X_train, X_val, y_train, y_val = train_test_split(X_rest, y_rest, test_size=0.25, random_state=0)
print(len(X_train), len(X_val), len(X_test))

For 500 rows it prints:

300 100 100

Choose on validation. Touch the test set once, at the very end.

challenge icon

Challenge

Medium

A vineyard predicts grape yield per row with Ridge. The starter picks alpha by the test score and reports that same score. Fix it.

  1. Split X_rest and y_rest into training and validation rows (test_size=0.25, random_state=0).
  2. Choose alpha by validation R squared, and print it with that score.
  3. Fit the chosen alpha on the training rows and print its test R squared.

For another vineyard:

Chosen alpha: 1 (validation R squared 0.787)
Test R squared: 0.726

The honest score is often lower than the starter's. It is the true one.

Try it yourself

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge


# Fits a scaled Ridge(alpha) on the first set of rows, returns its R squared on the second
def ridge_r2(alpha, X_fit, y_fit, X_check, y_check):
    scaler = StandardScaler()
    model = Ridge(alpha=alpha)
    model.fit(scaler.fit_transform(X_fit), y_fit)
    return model.score(scaler.transform(X_check), y_check)


# 90 vineyard rows: 10 measurements each and the grape yield in kg
rows = pd.read_csv("vineyard.csv")
features = ["sun_hours", "rain_mm", "soil_ph", "slope_deg", "vine_age",
            "row_length_m", "buds_per_vine", "frost_days", "wind_kmh", "clay_pct"]
X = rows[features]
y = rows["yield_kg"]
alphas = [0.1, 1, 10, 100]
X_rest, X_test, y_rest, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

# This picks alpha by the test score, then reports that same score: fix it
best_alpha = 0
best_r2 = -1
for alpha in alphas:
    r2 = ridge_r2(alpha, X_rest, y_rest, X_test, y_test)
    if r2 > best_r2:
        best_alpha = alpha
        best_r2 = r2
print(f"Chosen alpha: {best_alpha}")
print(f"Test R squared: {best_r2:.3f}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Supervised Learning

Practice on your own: Online Python compiler