Model Selection

In Evaluating Performance, we saw how to check the performance of an interpolator using cross-validation. We found that the default parameters for verde.Spline are not good for predicting our sample air temperature data. Now, let’s see how we can tune the Spline to improve the cross-validation performance.

Once again, we’ll start by importing the required packages and loading our sample data.

import numpy as np
import matplotlib.pyplot as plt
import as ccrs
import itertools
import pyproj
import verde as vd

data = vd.datasets.fetch_texas_wind()

# Use Mercator projection because Spline is a Cartesian gridder
projection = pyproj.Proj(proj="merc", lat_ts=data.latitude.mean())
proj_coords = projection(data.longitude.values, data.latitude.values)

region = vd.get_region((data.longitude, data.latitude))
# The desired grid spacing in degrees (converted to meters using 1 degree approx. 111km)
spacing = 15 / 60

Before we begin tuning, let’s reiterate what the results were with the default parameters.

spline_default = vd.Spline()
score_default = np.mean(
    vd.cross_val_score(spline_default, proj_coords, data.air_temperature_c)
), data.air_temperature_c)
print("R² with defaults:", score_default)


R² with defaults: 0.7960368854778264


Spline has many parameters that can be set to modify the final result. Mainly the damping regularization parameter and the mindist “fudge factor” which smooths the solution. Would changing the default values give us a better score?

We can answer these questions by changing the values in our spline and re-evaluating the model score repeatedly for different values of these parameters. Let’s test the following combinations:

dampings = [None, 1e-4, 1e-3, 1e-2]
mindists = [5e3, 10e3, 50e3, 100e3]

# Use itertools to create a list with all combinations of parameters to test
parameter_sets = [
    dict(damping=combo[0], mindist=combo[1])
    for combo in itertools.product(dampings, mindists)
print("Number of combinations:", len(parameter_sets))
print("Combinations:", parameter_sets)


Number of combinations: 16
Combinations: [{'damping': None, 'mindist': 5000.0}, {'damping': None, 'mindist': 10000.0}, {'damping': None, 'mindist': 50000.0}, {'damping': None, 'mindist': 100000.0}, {'damping': 0.0001, 'mindist': 5000.0}, {'damping': 0.0001, 'mindist': 10000.0}, {'damping': 0.0001, 'mindist': 50000.0}, {'damping': 0.0001, 'mindist': 100000.0}, {'damping': 0.001, 'mindist': 5000.0}, {'damping': 0.001, 'mindist': 10000.0}, {'damping': 0.001, 'mindist': 50000.0}, {'damping': 0.001, 'mindist': 100000.0}, {'damping': 0.01, 'mindist': 5000.0}, {'damping': 0.01, 'mindist': 10000.0}, {'damping': 0.01, 'mindist': 50000.0}, {'damping': 0.01, 'mindist': 100000.0}]

Now we can loop over the combinations and collect the scores for each parameter set.

spline = vd.Spline()
scores = []
for params in parameter_sets:
    score = np.mean(vd.cross_val_score(spline, proj_coords, data.air_temperature_c))


[-6.672752073616222, 0.48454031727685865, 0.8383522700289255, 0.8371988991061692, 0.8351153077117826, 0.8316607509514652, 0.8492629931148892, 0.8418400888286983, 0.8371795091873141, 0.8412200336704665, 0.852955508247071, 0.852172766758309, 0.8401945161936857, 0.8330182923876113, 0.8441706458566685, 0.8491145591355966]

The largest score will yield the best parameter combination.

best = np.argmax(scores)
print("Best score:", scores[best])
print("Score with defaults:", score_default)
print("Best parameters:", parameter_sets[best])


Best score: 0.852955508247071
Score with defaults: 0.7960368854778264
Best parameters: {'damping': 0.001, 'mindist': 50000.0}

That is a nice improvement over our previous score!

This type of tuning is important and should always be performed when using a new gridder or a new dataset. However, the above implementation requires a lot of coding. Fortunately, Verde provides convenience classes that perform the cross-validation and tuning automatically when fitting a dataset.

Cross-validated gridders

The verde.SplineCV class provides a cross-validated version of verde.Spline. It has almost the same interface but does all of the above automatically when fitting a dataset. The only difference is that you must provide a list of damping and mindist parameters to try instead of only a single value:

Calling fit will run a grid search over all parameter combinations to find the one that maximizes the cross-validation score., data.air_temperature_c)


SplineCV(client=None, cv=None, dampings=[None, 0.0001, 0.001, 0.01],
         delayed=False, engine='auto', force_coords=None,
         mindists=[5000.0, 10000.0, 50000.0, 100000.0])

The estimated best damping and mindist, as well as the cross-validation scores, are stored in class attributes:

print("Highest score:", spline.scores_.max())
print("Best damping:", spline.damping_)
print("Best mindist:", spline.mindist_)


Highest score: 0.852955508247071
Best damping: 0.001
Best mindist: 50000.0

The cross-validated gridder can be used like any other gridder (including in verde.Chain and verde.Vector):

grid = spline.grid(
    dims=["latitude", "longitude"],


Dimensions:      (latitude: 43, longitude: 51)
  * longitude    (longitude) float64 -106.4 -106.1 -105.9 ... -94.06 -93.8
  * latitude     (latitude) float64 25.91 26.16 26.41 ... 35.91 36.16 36.41
Data variables:
    temperature  (latitude, longitude) float64 19.42 19.42 19.43 ... 7.536 7.765
    metadata:  Generated by SplineCV(client=None, cv=None, dampings=[None, 0....

Like verde.cross_val_score, SplineCV can also run the grid search in parallel using Dask by specifying the delayed attribute:

Unlike verde.cross_val_score, calling fit does not result in dask.delayed objects. The full grid search is executed and the optimal parameters are found immediately., data.air_temperature_c)

print("Best damping:", spline.damping_)
print("Best mindist:", spline.mindist_)


Best damping: 0.001
Best mindist: 50000.0

The one caveat is the that the scores_ attribute will be a list of dask.delayed objects instead because the scores are only computed as intermediate values in the scheduled computations.

print("Delayed scores:", spline.scores_)


Delayed scores: [Delayed('mean-072c79f8-dc2d-4e99-9b0c-ee7fc9b4e2f2'), Delayed('mean-f1350a62-1e57-4217-a11b-8ecc22bd1d84'), Delayed('mean-3d066587-57c8-497c-978e-d4a7efc19a29'), Delayed('mean-9cbce76b-74d2-4d8e-8405-2e0d25a77faf'), Delayed('mean-19760129-b8ac-4921-b344-c27bc9714d86'), Delayed('mean-8e287edf-c952-4d86-b624-676b6a76c4c3'), Delayed('mean-cefbae33-f2d9-4d3f-8426-10ea34a32bb9'), Delayed('mean-0b981dc0-4301-42af-bc58-74972faf2672'), Delayed('mean-22b6c56d-efa5-44f7-8f0a-03a8bfacfbe0'), Delayed('mean-32b0b249-23e6-45dd-acf7-4b11b5d486f7'), Delayed('mean-c99a781a-f2c7-45b5-a21a-761defaf194d'), Delayed('mean-be272ef0-5a00-4f99-b95c-4c23a78a60bd'), Delayed('mean-93176f46-167c-4323-9db6-e18bc438018b'), Delayed('mean-271758c8-67b1-45c8-854e-420379680c9e'), Delayed('mean-8abd6df9-576f-4ab0-a741-923c6bb3b8f3'), Delayed('mean-48e621d3-5816-4462-9dba-bed6c00ecbb6')]

Calling dask.compute on the scores will calculate their values but will unfortunately run the entire grid search again. So using delayed=True is not recommended if you need the scores of each parameter combination.

The importance of tuning

To see the difference that tuning has on the results, we can make a grid with the best configuration and see how it compares to the default result.

grid_default = spline_default.grid(
    dims=["latitude", "longitude"],

Let’s plot our grids side-by-side:

mask = vd.distance_mask(
    (data.longitude, data.latitude),
    maxdist=3 * spacing * 111e3,
    coordinates=vd.grid_coordinates(region, spacing=spacing),

grid = grid.where(mask)
grid_default = grid_default.where(mask)

plt.figure(figsize=(14, 8))
for i, title, grd in zip(range(2), ["Defaults", "Tuned"], [grid_default, grid]):
    ax = plt.subplot(1, 2, i + 1, projection=ccrs.Mercator())
    pc = grd.temperature.plot.pcolormesh(
    plt.colorbar(pc, orientation="horizontal", aspect=50, pad=0.05).set_label("C")
        data.longitude, data.latitude, ".k", markersize=1, transform=ccrs.PlateCarree()


/home/leo/src/verde/tutorials/ UserWarning: Tight layout not applied. The left and right margins cannot be made large enough to accommodate all axes decorations.
/home/leo/src/verde/tutorials/ UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.

Notice that, for sparse data like these, smoother models tend to be better predictors. This is a sign that you should probably not trust many of the short wavelength features that we get from the defaults.

Total running time of the script: ( 0 minutes 2.100 seconds)

Gallery generated by Sphinx-Gallery