Arctic sea ice forecast

Current events on this problem

- Polytechnique MAP542 2016/17,
number of participants =
**23**, number of submissions =**53**, combined score =**0.272**, click here for score vs time plot - single-day RAMP at Climate Informatics Workshop 2016,
number of participants =
**50**, number of submissions =**91**, combined score =**0.307**, click here for score vs time plot - Polytechnique MAP583 2016/17,
number of participants =
**124**, number of submissions =**257**, combined score =**0.259**, click here for score vs time plot

Keywords

*Balázs Kégl (CNRS), Camille Marini (CNRS), Andy Rhines (UW), Jennifer Dy (NEU), Arindam Banerjee (UMN)*

Arctic sea ice cover is one of the most variable features of Earth's climate. Its annual cycle peaks at around 15 million square kilometers in early spring, melting back to a minimum of about 6 million square kilometers in September. These seasonal swings are important for Earth's energy balance, as ice reflects the majority of sunlight while open water absorbs it. Changes in ice cover are also important for marine life and navigation for shipping.

In recent years, Arctic sea ice cover has declined rapidly, particularly during the September minimum. These changes have outpaced the predictions of climate models, and forecasting extent remains a formidable challenge. Typically, skillful predictions are limited to ~2-5 months in advance Stroeve, et al. "Improving Predictions of Arctic Sea Ice Extent", while idealized experiments suggest that predictions up to two years in advance should be possible Guemas et al., 2014.

Better tools to predict ice cover are critical for seasonal and regional climate prediction, and would thus address grand challenges in the study of climate change (World Climate Research Programme: Grand Challenges, 2013).

As a surrogate for observational data, we will use output from a 1300 year simulation using the NCAR CCSM4.0 climate model. The model was run in fully-coupled mode with interactive ocean, atmosphere, and sea ice. The simulation was also performed in an idealized "Pre-Industrial" mode, where greenhouse gas concentrations and other external forcings are held fixed to 1850 levels. This allows us to access a stationary climate over a 1000+ year period, which makes the evaluation of the predictor more robust than if we used real measurements that are both non-stationary and limited to several decades.

The data is a time series of "images" $z_t$, consisting of different physical variables on a regular grid on the Earth, indexed by lon(gitude) and lat(itude) coordinates. The variables we have made available are:

`ice_area`

: the Northern Hemisphere sea ice area, in millions of squared kilometers.`ts`

: surface temperature, most important over the oceans which have a very high heat capacity.`taux`

: zonal (x-direction) surface wind stress. This is the frictional effect of winds on the sea surface and sea ice.`tauy`

: meridional (y-direction) surface wind stress.`ps`

: surface pressure.`psl`

: equivalent sea-level surface pressure. This corrects ps for the effects of topography, though the two should be very similar.`shflx`

: Surface sensible heat flux, the amount of heat transferred from the surface to the atmosphere.`cldtot`

: Total cloud cover (fractional), which has strong effects on radiative energy balance at the surface.

The fields are recorded every month for 1300 years, giving 15,600 time points. The goal is to predict the Northern Hemisphere sea ice area 4 months ahead.

The pipeline will consists of a time series feature extractor and a predictor. Since the task is regression, the predictor will be a regressor, and the score (to minimize) will be the root mean square error. The feature extractor will have access to the whole data. It will construct a "classical" feature matrix where each row corresponds to a time point. You should collect all information into these features that you find relevant to the regressor. The feature extractor can take anything from the past, that is, it will implement a function $x_t = g(z_1, \ldots, z_t)$. Since you will have access to the full data, in theory you can cheat (even inadvertently) by using information from the future. We have implemented a randomized test to find such "bugs", but please do your best to avoid this since it would make the results irrelevant.

You are of course free to explore any regression technique to improve the prediction. Since the input dimension is relatively large (2000+ dimensions per time point even after subsampling) sparse regression techniques (eg. LASSO) may be the best way to go, but this is just an a priori suggestion. The following list provides you other hints to start with, based on domain knowledge.

- Some of the predictors will be very non-Gaussian.
- Teleconnections such as those associated with El Nino can be very important, so do not restrict your attention to variables in the Arctic.

Packages to install:

conda install xarray dask netCDF4 basemap

In [16]:

```
%matplotlib inline
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
```

`Dataset`

and `DataArray`

objects at the xarray site.

In [17]:

```
X_ds = xr.open_dataset('data/train.nc')
y_array = np.load('data/train.npy')
```

`xarray`

uses `datetime64[ns]`

as a time type which means that dates must be between 1678 and 2262. We convert whatever time type we have into `datetime64[ns]`

starting at 1700. This only works if the monthly time series has length less than 562 years, which is the case of all train and test times series, both in the starting kit and in the backend. This is important so that, e.g., grouping by month works correctly.

In [6]:

```
X_ds['time'] = pd.date_range(
'1/1/1700', periods=X_ds['time'].shape[0], freq='M')\
- np.timedelta64(15, 'D')
```

Printing it, you can see that it contains all the data, indices, and other metadata.

In [7]:

```
X_ds
```

Out[7]:

`y_array`

on the disk is already shifted by `n_lookahead = 4`

months. `n_burn_in = 120`

(months) is the length of the prefix for which no prediction is required. If your feature extractor only uses these ten years of the past to extract features from, you don't need to worry about missing data in the beginning of the sequence. Otherwise you should take care of the issue "manually" (handling missing data in the beginning of the sequence).

In [18]:

```
y_array, y_array.shape
```

Out[18]:

In [19]:

```
X_ds['ice_area']
```

Out[19]:

In [9]:

```
def plot_map(map_xr, time_index):
lons, lats = np.meshgrid(map_xr['lon'], map_xr['lat'])
fig = plt.figure()
ax = fig.add_axes([0.05, 0.05, 0.9,0.9])
map = Basemap(llcrnrlon=0, llcrnrlat=-89, urcrnrlon=360, urcrnrlat=89, projection='mill')
# draw coastlines, country boundaries, fill continents.
map.drawcoastlines(linewidth=0.25)
#map.drawcountries(linewidth=0.25)
#map.fillcontinents(color='coral',lake_color='aqua')
# draw the edge of the map projection region (the projection limb)
#map.drawmapboundary(fill_color='aqua')
ax.set_title(map_xr.attrs['long_name'] + ' at month ' + str(time_index))
im = map.pcolormesh(lons, lats, map_xr[time_index],
shading='flat', cmap=plt.cm.jet, latlon=True)
cb = map.colorbar(im,"bottom", size="5%", pad="2%")
#plt.savefig("test_plot.pdf")
plt.show()
```

In [10]:

```
t = 126
plot_map(X_ds['ts'], t)
plot_map(X_ds['taux'], t)
plot_map(X_ds['tauy'], t)
plot_map(X_ds['ps'], t)
plot_map(X_ds['psl'], t)
plot_map(X_ds['shflx'], t)
plot_map(X_ds['cldtot'], t)
```

The size of the Northern hemisphere sea ice area in million square kilometers, shifted by 4 months. Note that this variable is also part of the input (see above), shifted back so it is aligned with the other variables.

In [11]:

```
fig = plt.figure(figsize=(16, 12))
ax = fig.add_subplot(2, 1, 1)
ax.set_xlabel('time [months]')
ax.set_ylabel('ice area [M km^2]')
ax.plot(X_ds['time'], y_array)
ax = fig.add_subplot(2, 1, 2)
ax.set_xlabel('time [months]')
ax.set_ylabel('ice area [M km^2]')
ax.plot(X_ds['time'][:120], y_array[:120])
```

Out[11]:

`pandas`

dataframes or `numpy`

array. The result is always a

In [12]:

```
t = 123
lat = 13
lon = 29
```

In [13]:

```
X_ds['ice_area'][t]
```

Out[13]:

In [14]:

```
X_ds['ts'][t, lat]
```

Out[14]:

You can convert any of these objects into a `numpy`

array.

In [15]:

```
X_ds['taux'].values
```

Out[15]:

You can also use slices, and slice bounds don't even have to be in the index arrays.

In [16]:

```
X_ds['tauy'][12].loc[10:50]
```

Out[16]:

In [17]:

```
X_ds.isel(time=t)
```

Out[17]:

Cross validating time-series predictors is tricky. We can't simply shuffle the observations $z_t =$ `X_ds['tas'][t]`

since we would lose both causality and the correlation structure that follows natural order.

To formalize the issue, let us first define formally the predictor that we will produce in the RAMP. Let the time series be $z_1, \ldots, z_T$ and the let target to predict at time $t$ be $y_t$. The target is usually (and in our case) a function of the future $z_{t+1}, \ldots$, but it can be anything else. We want to learn a function that predicts $y$ from the past, that is

\begin{equation} \hat{y}_t = f(z_1, ..., z_t) = f(Z_t) \end{equation}where $Z_t = (z_1, ..., z_t)$ is the past. Now, the sample $(Z_t, y_t)$ is a regular (although none iid) sample from the point of view of shuffling, so we can train on $\{Z_t, y_t\}_{t \in \cal{I}_{\text{train}}}$ and test on $(Z_t, y_t)_{t \in \cal{I}_{\text{test}}}$, where $\cal{I}_{\text{train}}$ and $\cal{I}_{\text{test}}$ are arbitrary but disjunct train and test index sets, respectively (typically produced by sklearn's `ShuffleSplit`

). Using shuffling would nevertheless allow a second order leakage from training points to test points that preceed them, by, e.g., aggregating the training set and adding the aggregate back as a feature. To avoid this, we use block-CV: on each fold, all $t \in \cal{I}_{\text{test}}$ are larger than all $t \in \cal{I}_{\text{train}}$. We also make sure that all training and test sets contain consecutive observations, so recurrent nets and similar predictors, which rely on this, may be trained.

The training algorithm thus maps $(Z_t, y_t)_{t \in \cal{I}_{\text{train}}}$ to $f$. The point $Z_t$ contains the target for all training points $Z_{t'}$ for $t' \le t - 4$, so it is technically possible to cheat: when you receive a test set $z_1, ..., z_T$, you could look up the target of $z_t$ in $z_{t+4}$. To detect this (often inadvertant) cheating, we will check that you feature extractor is invariant to the future.

To allow a reasonably long past before making the first prediction, we strip the first $b = 120$ months (burn-in). You can of course use a longer window in your feature extractor, but in this case you will have to handle the missing time points in the beginning of the sequence.

We have factorized the pipeline into two steps. The first feature extractor $g$ transforms the past into a classical feature vector $x_t = g(Z_t)$, and the classical regressor $h$ predicts the target from the feature vector $\hat{y}_t = h(x_t)$. To summarize, the full predictor is a composition $f(Z_t) = h(g(Z_t))$. If you have a complex solution where this factorization does not make sense (e.g., RNNs), you can do all the work in the (optional) fit function of the feature extractor, send the prediction as a single feature $x_t$ to the regressor, and simply use an identity function in the regressor $\hat{y}_t = x_t$.

The feature extractor implements a single `transform`

function. As we explained above, it receives the full `X_ds`

including the burn-in period $b$ as an attribute. It should produce a feature matrix of length $T - b$, of type numpy array, representing the past vector $(Z_{t+b}, \ldots, Z_{T})$. For constructing/computing $x_t$, it can only use the past $Z_t = (z_1, \ldots, z_t) = $ `X_ds['tas'][:t]`

.

Note that the following code cells are *not* executed in the notebook. The notebook saves their contents in the file specified in the first line of the cell, so you can edit your submission before running the local test below and submitting it at the RAMP site.

In [3]:

```
%%file submissions/starting_kit/ts_feature_extractor.py
import numpy as np
class FeatureExtractor(object):
def __init__(self):
pass
def transform(self, X_ds):
"""Compute the vector of input variables at time t.
Spatial variables will
be averaged along lat and lon coordinates.
"""
# This is the range for which features should be provided. Strip
# the burn-in from the beginning and the prediction look-ahead from
# the end.
valid_range = np.arange(X_ds.n_burn_in, len(X_ds['time']))
# We convert the Dataset into a 4D DataArray
X_xr = X_ds.to_array()
# We compute the mean over the lat and lon axes
mean_xr = np.mean(X_xr, axis=(2, 3))
# We convert it into numpy array, transpose, and slice the valid range
X_array = mean_xr.values.T[valid_range]
return X_array
```

The regressor should implement a scikit-klearn-like regressor with fit and predict functions. The starting kit uses a linear model.

In [108]:

```
%%file submissions/starting_kit/regressor.py
from sklearn.base import BaseEstimator
from sklearn import linear_model
class Regressor(BaseEstimator):
def __init__(self):
self.reg = linear_model.LinearRegression()
def fit(self, X, y):
self.reg.fit(X, y)
def predict(self, X):
return self.reg.predict(X)
```

It is **important that you test your submission files before submitting them**. For this we provide a unit test. Note that the test runs on your files in `submissions/starting_kit`

.

First `pip install ramp-workflow`

or install it from the github repo. Make sure that the python files `ts_feature_extractor.py`

and `regressor.py`

are in the `submissions/starting_kit`

folder, and the data `train.nc`

and `test.nc`

are in `data`

. Then run

`ramp_test_submission`

If it runs and print training and test errors on each fold, then you can submit the code.

In [109]:

```
!ramp_test_submission
```

`rampwf.utils.testing.py`

, and call `assert_submission`

. This may be useful if you would like to understand how we instantiate the workflow, the scores, the data connectors, and the cross validation scheme defined in `problem.py`

, and how we insert and train/test your submission.

In [ ]:

```
# %load https://raw.githubusercontent.com/paris-saclay-cds/ramp-workflow/master/rampwf/utils/testing.py
"""The :mod:`rampwf.utils.testing` submodule provide utils to test ramp-kits"""
from __future__ import print_function
import imp
from os.path import join, abspath
from os import system
import numpy as np
def assert_read_problem(ramp_kit_dir='.'):
problem = imp.load_source('', join(ramp_kit_dir, 'problem.py'))
return problem
def assert_title(ramp_kit_dir='.'):
problem = assert_read_problem(ramp_kit_dir)
print('Testing {}'.format(problem.problem_title))
def assert_data(ramp_kit_dir='.', ramp_data_dir='.'):
problem = assert_read_problem(ramp_kit_dir)
print('Reading train and test files from {}/data ...'.format(
ramp_data_dir))
X_train, y_train = problem.get_train_data(path=ramp_data_dir)
X_test, y_test = problem.get_test_data(path=ramp_data_dir)
return X_train, y_train, X_test, y_test
def assert_cv(ramp_kit_dir='.', ramp_data_dir='.'):
problem = assert_read_problem(ramp_kit_dir)
X_train, y_train = problem.get_train_data(path=ramp_data_dir)
print('Reading cv ...')
cv = list(problem.get_cv(X_train, y_train))
return cv
def assert_score_types(ramp_kit_dir='.'):
problem = assert_read_problem(ramp_kit_dir)
score_types = problem.score_types
return score_types
def assert_submission(ramp_kit_dir='.', ramp_data_dir='.',
submission='starting_kit'):
"""Helper to test a submission from a ramp-kit.
Parameters
----------
ramp_kit_dir : str, (default='.')
The directory of the ramp-kit to be tested for submission.
ramp_data_dir : str, (default='.')
The directory of the data
submission_name : str, (default='starting_kit')
The name of the submission to be tested.
Returns
-------
None
"""
problem = assert_read_problem(ramp_kit_dir)
assert_title(ramp_kit_dir)
X_train, y_train, X_test, y_test = assert_data(ramp_kit_dir, ramp_data_dir)
cv = assert_cv(ramp_kit_dir, ramp_data_dir)
score_types = assert_score_types(ramp_kit_dir)
print('Training {}/submissions/{} ...'.format(
ramp_kit_dir, submission))
module_path = join(ramp_kit_dir, 'submissions', submission)
train_train_scoress = np.empty((len(cv), len(score_types)))
train_valid_scoress = np.empty((len(cv), len(score_types)))
test_scoress = np.empty((len(cv), len(score_types)))
for fold_i, (train_is, valid_is) in enumerate(cv):
trained_workflow = problem.workflow.train_submission(
module_path, X_train, y_train, train_is=train_is)
y_pred_train = problem.workflow.test_submission(
trained_workflow, X_train)
predictions_train_train = problem.Predictions(
y_pred=y_pred_train[train_is])
ground_truth_train_train = problem.Predictions(
y_true=y_train[train_is])
predictions_train_valid = problem.Predictions(
y_pred=y_pred_train[valid_is])
ground_truth_train_valid = problem.Predictions(
y_true=y_train[valid_is])
y_pred_test = problem.workflow.test_submission(
trained_workflow, X_test)
predictions_test = problem.Predictions(y_pred=y_pred_test)
ground_truth_test = problem.Predictions(y_true=y_test)
print('CV fold {}'.format(fold_i))
for score_type_i, score_type in enumerate(score_types):
score = score_type.score_function(
ground_truth_train_train, predictions_train_train)
train_train_scoress[fold_i, score_type_i] = score
print('\ttrain {} = {}'.format(
score_type.name, round(score, score_type.precision)))
score = score_type.score_function(
ground_truth_train_valid, predictions_train_valid)
train_valid_scoress[fold_i, score_type_i] = score
print('\tvalid {} = {}'.format(
score_type.name, round(score, score_type.precision)))
score = score_type.score_function(
ground_truth_test, predictions_test)
test_scoress[fold_i, score_type_i] = score
print('\ttest {} = {}'.format(
score_type.name, round(score, score_type.precision)))
print('----------------------------')
means = train_train_scoress.mean(axis=0)
stds = train_train_scoress.std(axis=0)
for mean, std, score_type in zip(means, stds, score_types):
print('train {} = {} ± {}'.format(
score_type.name, round(mean, score_type.precision),
round(std, score_type.precision + 1)))
means = train_valid_scoress.mean(axis=0)
stds = train_valid_scoress.std(axis=0)
for mean, std, score_type in zip(means, stds, score_types):
print('valid {} = {} ± {}'.format(
score_type.name, round(mean, score_type.precision),
round(std, score_type.precision + 1)))
means = test_scoress.mean(axis=0)
stds = test_scoress.std(axis=0)
for mean, std, score_type in zip(means, stds, score_types):
print('test {} = {} ± {}'.format(
score_type.name, round(mean, score_type.precision),
round(std, score_type.precision + 1)))
print('----------------------------')
problem_name = abspath(ramp_kit_dir).split('/')[-1]
print('Testing if the notebook can be converted to html')
system('jupyter nbconvert --to html {}/{}_starting_kit.ipynb'.format(
ramp_kit_dir, problem_name))
```

In [30]:

```
# assert_submission()
```

Once you found a good model, you can submit it to ramp.studio. First, if it is your first time using RAMP, sign up, otherwise log in. Then find an open event on the particular problem, for example, the event sea ice colorado for this RAMP. Sign up for the event. Both signups are controled by RAMP administrators, so there **can be a delay between asking for signup and being able to submit**.

Once your signup request is accepted, you can go to your sandbox and copy-paste (or upload) `ts_feature_extractor.py`

and `regressor.py`

from `submissions/starting_kit`

. Save it, rename it, then submit it. The submission is trained and tested on our backend in the same way as `ramp_test_submission`

does it locally. While your submission is waiting in the queue and being trained, you can find it in the "New submissions (pending training)" table in my submissions. Once it is trained, you get a mail, and your submission shows up on the public leaderboard.
If there is an error (despite having tested your submission locally with `ramp_test_submission`

), it will show up in the "Failed submissions" table in my submissions. You can click on the error to see part of the trace.

After submission, do not forget to give credits to the previous submissions you reused or integrated into your submission.

The data set we use at the backend is usually different from what you find in the starting kit, so the score may be different.

The usual way to work with RAMP is to explore solutions, add feature transformations, select models, perhaps do some AutoML/hyperopt, etc., *locally*, and checking them with `ramp_test_submission`

. The script prints mean cross-validation scores

```
----------------------------
train rmse = 0.896 ± 0.0093
valid rmse = 0.799 ± 0.0675
test rmse = 0.97 ± 0.0115
```

The official score in this RAMP (the first score column after "historical contributivity" on the leaderboard) is root mean squared error ("rmse"), so the line that is relevant in the output of `ramp_test_submission`

is `valid rmse = 0.799 ± 0.0675`

. When the score is good enough, you can submit it at the RAMP.

To get you started, we made several other example submissions.

This one uses the whole set of fields at time $t$ as the feature vector. We also modify the regressor because of the large dimensional input.

In [102]:

```
%%file submissions/whole_fields/ts_feature_extractor.py
import numpy as np
class FeatureExtractor(object):
def __init__(self):
pass
def transform(self, X_ds):
"""Compute the vector of input variables at time t.
Spatial variables will be concatenated.
"""
# This is the range for which features should be provided. Strip
# the burn-in from the beginning and the prediction look-ahead from
# the end.
valid_range = np.arange(X_ds.n_burn_in, len(X_ds['time']))
# We convert the Dataset into a 4D DataArray
X_xr = X_ds.to_array()
# We convert it into np array, put the t axis first
X_array_t_first = np.swapaxes(X_xr.values, 0, 1)
shape = X_array_t_first.shape
# We reshape it to create one vector per time step, and slice the
# valid range
X_array = X_array_t_first.reshape(
shape[0], shape[1] * shape[2] * shape[3])[valid_range]
return X_array
```

In [110]:

```
%%file submissions/whole_fields/regressor.py
from sklearn.base import BaseEstimator
from sklearn import linear_model
class Regressor(BaseEstimator):
def __init__(self):
self.reg = linear_model.Lasso()
def fit(self, X, y):
self.reg.fit(X, y)
def predict(self, X):
return self.reg.predict(X)
```

You can test this by

In [111]:

```
!ramp_test_submission --submission whole_fields
```

`[t, t-1, ... t-window_size+1]`

then concatenate. Spatial variables are averaged along lat and lon coordinates. We use this with a random forest regressor.

In [113]:

```
%%file submissions/mean_ten/ts_feature_extractor.py
import numpy as np
class FeatureExtractor(object):
def __init__(self):
self.window_size = 10
def transform(self, X_ds):
"""Compute the vector of input variables in window of a given size.
Compute the vector of input variables at times
[t, t-1, ... t-window_size+1] then concatenate. Spatial variables
will be averaged along lat and lon coordinates.
"""
# This is the range for which features should be provided. Strip
# the burn-in from the beginning and the prediction look-ahead from
# the end.
valid_range = np.arange(X_ds.attrs['n_burn_in'], len(X_ds['time']))
# We convert the Dataset into a 4D DataArray
X_xr = X_ds.to_array()
# We compute the mean over the lat and lon axes
mean_xr = np.mean(X_xr, axis=(2, 3))
mean_array_transposed = mean_xr.values.T
# We concatenate the past window_size means
mean_array_c = np.concatenate(
[np.roll(mean_array_transposed, i)
for i in range(self.window_size)], axis=1)
# We slice the valid range
X_array = mean_array_c[valid_range]
return X_array
```

In [122]:

```
%%file submissions/mean_ten/regressor.py
from sklearn.base import BaseEstimator
from sklearn.ensemble import RandomForestRegressor
class Regressor(BaseEstimator):
def __init__(self):
self.reg = RandomForestRegressor(n_estimators=10, max_leaf_nodes=500)
def fit(self, X, y):
self.reg.fit(X, y)
def predict(self, X):
return self.reg.predict(X)
```

In [123]:

```
!ramp_test_submission --submission mean_ten
```

In [131]:

```
%%file submissions/monthly_means/ts_feature_extractor.py
import numpy as np
class FeatureExtractor(object):
def __init__(self):
pass
def transform(self, X_ds):
"""Compute the monthly averages of the ice_area.
Corresponding to the month to predict.
The code could be simplified but in this way it is general, can be
used for the other variables as well.
"""
# This is the range for which features should be provided. Strip
# the burn-in from the beginning and the prediction look-ahead from
# the end.
valid_range = np.arange(X_ds.attrs['n_burn_in'], len(X_ds['time']))
# We convert the Dataset into a 4D DataArray
X_xr = X_ds.to_array()
# We compute the mean over the lat and lon axes
mean_array = np.mean(X_xr, axis=(2, 3)).values
# We group the 8 monthly series into 8 x 12 monthly groups of series
monthly_groups = mean_array.reshape(
(mean_array.shape[0], 12, -1), order='F')
# We compute cumulative means in each group
monthly_means = np.cumsum(monthly_groups, axis=2)\
/ (1. + np.arange(monthly_groups.shape[2]))
# We repeat each mean 12 times
monthly_means_per_month = np.repeat(monthly_means, 12, axis=2)
# We pad m 0s to the series corresponding to month m, no single-line
# operation for this
for j in range(monthly_means_per_month.shape[0]):
for m in range(12):
monthly_means_per_month[j, m] = np.roll(
monthly_means_per_month[j, m], m)
monthly_means_per_month[j, m, :m] = 0
# We reshape and transpose it into one vector per month
monthly_ice_area_mean = monthly_means_per_month[0]
# At each month t we use the running mean correponting to month t - 8
X_array = np.array(
[monthly_ice_area_mean[(t + X_ds.n_lookahead - 12) % 12][t]
for t in range(monthly_ice_area_mean.shape[1])])
# We slice the valid range
X_array = X_array[valid_range].reshape(-1, 1)
return X_array
```

In [132]:

```
!ramp_test_submission --submission monthly_means
```

In [4]:

```
%%file submissions/illegal_lookahead/ts_feature_extractor.py
import numpy as np
class FeatureExtractor(object):
def __init__(self):
pass
def transform(self, X_ds):
"""Compute the vector of input variables at time t. Spatial variables will
be averaged along lat and lon coordinates."""
# This is the range for which features should be provided. Strip
# the burn-in from the beginning and the prediction look-ahead from
# the end.
valid_range = np.arange(X_ds.attrs['n_burn_in'], len(X_ds['time']))
# We convert the Dataset into a 4D DataArray
X_xr = X_ds.to_array()
# We compute the mean over the lat and lon axes
mean_xr = np.mean(X_xr, axis=(2, 3))
# We convert it into numpy array, transpose, and slice the valid range
# We roll it backwards to see what happens when the feature extractor
# attempts to look into the future.
X_array = mean_xr.values.T[np.roll(valid_range, -2)]
return X_array
```

In [134]:

```
!ramp_test_submission --submission illegal_lookahead
```

When you are developing and debugging your submission, you may want to stay in the notebook and execute the workflow step by step. You can import `problem.py`

and call the ingredients directly, or even deconstruct the code from ramp-workflow.

In [1]:

```
import imp
problem = imp.load_source('', 'problem.py')
```

Get the training data.

In [2]:

```
X_train, y_train = problem.get_train_data()
```

Get the first cv fold, creating training and validation indices.

In [3]:

```
train_is, test_is = list(problem.get_cv(X_train, y_train))[0]
```

Train your starting kit.

In [4]:

```
ts_fe, reg = problem.workflow.train_submission(
'submissions/starting_kit', X_train, y_train, train_is)
```

Get the full prediction (train and validation).

In [5]:

```
y_pred = problem.workflow.test_submission((ts_fe, reg), X_train)
```

Print the training and validation scores.

In [7]:

```
score_function = problem.score_types[0]
```

In [8]:

```
score_train = score_function(y_train[train_is], y_pred[train_is])
print(score_train)
```

In [9]:

```
score_valid = score_function(y_train[test_is], y_pred[test_is])
print(score_valid)
```

Get the independent test data.

In [10]:

```
X_test, y_test = problem.get_test_data()
```

Test the submission on it.

In [11]:

```
y_test_pred = problem.workflow.test_submission((ts_fe, reg), X_test)
```

Print the test score.

In [12]:

```
score_test = score_function(y_test, y_test_pred)
print(score_test)
```

`el_nino`

, `ts_feature_extractor`

, and `regressor`

workflows and deconstruct them.

In [24]:

```
ts_feature_extractor = imp.load_source(
'', 'submissions/starting_kit/ts_feature_extractor.py')
ts_fe = ts_feature_extractor.FeatureExtractor()
regressor = imp.load_source(
'', 'submissions/starting_kit/regressor.py')
reg = regressor.Regressor()
```

In [19]:

```
n_burn_in = X_ds.n_burn_in
# X_ds contains burn-in so it needs to be extended by n_burn_in
# timesteps. This assumes that train_is is a block of consecutive
# time points.
burn_in_range = np.arange(train_is[-1], train_is[-1] + n_burn_in)
extended_train_is = np.concatenate((train_is, burn_in_range))
X_train_ds = X_ds.isel(time=extended_train_is)
X_train_array = ts_fe.transform(X_train_ds)
print(X_train_array)
reg.fit(X_train_array[train_is], y_train[train_is])
```

In [20]:

```
X_train_array = ts_fe.transform(X_train)
y_pred = reg.predict(X_train_array)
```

In [21]:

```
X_test_array = ts_fe.transform(X_test)
y_test_pred = reg.predict(X_test_array)
```

You can find more information in the README of the ramp-workflow library.

Don't hesitate to contact us.