Document a time series forecasting model

Use the FRED sample dataset to train a simple time series model and document that model with the ValidMind Developer Framework.

As part of the notebook, you will learn how to train a simple model while exploring how the documentation process works:

Contents

About ValidMind

ValidMind is a platform for managing model risk, including risk associated with AI and statistical models.

You use the ValidMind Developer Framework to automate documentation and validation tests, and then use the ValidMind AI Risk Platform UI to collaborate on model documentation. Together, these products simplify model risk management, facilitate compliance with regulations and institutional standards, and enhance collaboration between yourself and model validators.

Before you begin

This notebook assumes you have basic familiarity with Python, including an understanding of how functions work. If you are new to Python, you can still run the notebook but we recommend further familiarizing yourself with the language.

If you encounter errors due to missing modules in your Python environment, install the modules with pip install, and then re-run the notebook. For more help, refer to Installing Python Modules.

New to ValidMind?

If you haven’t already seen our Get started with the ValidMind Developer Framework, we recommend you explore the available resources for developers at some point. There, you can learn more about documenting models, find code samples, or read our developer reference.

For access to all features available in this notebook, create a free ValidMind account.

Signing up is FREE — Register with ValidMind

Key concepts

Model documentation: A structured and detailed record pertaining to a model, encompassing key components such as its underlying assumptions, methodologies, data sources, inputs, performance metrics, evaluations, limitations, and intended uses. It serves to ensure transparency, adherence to regulatory requirements, and a clear understanding of potential risks associated with the model’s application.

Documentation template: Functions as a test suite and lays out the structure of model documentation, segmented into various sections and sub-sections. Documentation templates define the structure of your model documentation, specifying the tests that should be run, and how the results should be displayed.

Tests: A function contained in the ValidMind Developer Framework, designed to run a specific quantitative test on the dataset or model. Tests are the building blocks of ValidMind, used to evaluate and document models and datasets, and can be run individually or as part of a suite defined by your model documentation template.

Metrics: A subset of tests that do not have thresholds. In the context of this notebook, metrics and tests can be thought of as interchangeable concepts.

Custom metrics: Custom metrics are functions that you define to evaluate your model or dataset. These functions can be registered with ValidMind to be used in the platform.

Inputs: Objects to be evaluated and documented in the ValidMind framework. They can be any of the following:

  • model: A single model that has been initialized in ValidMind with vm.init_model().
  • dataset: Single dataset that has been initialized in ValidMind with vm.init_dataset().
  • models: A list of ValidMind models - usually this is used when you want to compare multiple models in your custom metric.
  • datasets: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom metric. See this example for more information.

Parameters: Additional arguments that can be passed when running a ValidMind test, used to pass additional information to a metric, customize its behavior, or provide additional context.

Outputs: Custom metrics can return elements like tables or plots. Tables may be a list of dictionaries (each representing a row) or a pandas DataFrame. Plots may be matplotlib or plotly figures.

Test suites: Collections of tests designed to run together to automate and generate model documentation end-to-end for specific use-cases.

Example: the classifier_full_suite test suite runs tests from the tabular_dataset and classifier test suites to fully document the data and model sections for binary classification model use-cases.

Install the client library

The client library provides Python support for the ValidMind Developer Framework. To install it:

%pip install -q validmind

Initialize the client library

ValidMind generates a unique code snippet for each registered model to connect with your developer environment. You initialize the client library with this code snippet, which ensures that your documentation and tests are uploaded to the correct model when you run the notebook.

### Get your code snippet

  1. In a browser, log in to ValidMind.

  2. In the left sidebar, navigate to Model Inventory and click + Register new model.

  3. Enter the model details and click Continue. (Need more help?)

    For example, to register a model for use with this notebook, select:

    • Documentation template: Time Series Forecasting with ML
    • Use case: Analytics - Analytics

    You can fill in other options according to your preference.

  4. Go to Getting Started and click Copy snippet to clipboard.

Next, replace this placeholder with your own code snippet:

import validmind as vm

vm.init(
  api_host = "https://api.prod.validmind.ai/api/v1/tracking",
  api_key = "...",
  api_secret = "...",
  model = "..."
)

Initialize the Python environment

Next, let’s import the necessary libraries and set up your Python environment for data analysis:

from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split

%matplotlib inline

Preview the documentation template

A template predefines sections for your model documentation and provides a general outline to follow, making the documentation process much easier.

You will upload documentation and test results into this template later on. For now, take a look at the structure that the template provides with the vm.preview_template() function from the ValidMind library and note the empty sections:

vm.preview_template()

Load the sample dataset

The sample dataset used here is provided by the ValidMind library. To be able to use it, you need to import the dataset and load it into a pandas DataFrame, a two-dimensional tabular data structure that makes use of rows and columns:

from validmind.datasets.regression import fred_timeseries 

target_column = fred_timeseries.target_column

print(
    f"Loaded demo dataset with: \n\n\t• Target column: '{target_column}'"
)

raw_df = fred_timeseries.load_data()
raw_df.head()

Document the model

As part of documenting the model with the ValidMind Developer Framework, you need to preprocess the raw dataset, initialize some training and test datasets, initialize a model object you can use for testing, and then run the full suite of tests.

Prepocess the raw dataset

Preprocessing performs a number of operations to get ready for the subsequent steps: - Split the dataset: Divide the original dataset into training and test sets for the primary model with an 80/20 split, without shuffling. - Difference the data: Calculate the first difference of the train and test datasets to remove trends and seasonality, then drop any resulting NaN values. - Extract features and target variables: Separate the feature columns (predictors) and the target variable from the differenced train and test datasets.

# Split the raw dataset into training and test sets 
train_df, test_df = train_test_split(raw_df, test_size=0.2, shuffle=False)

# Take the first difference of the training and test sets
train_diff_df = train_df.diff().dropna()
test_diff_df = test_df.diff().dropna()

# Extract the features and target variable from the training set
X_diff_train = train_diff_df.drop(target_column, axis=1)
y_diff_train = train_diff_df[target_column]

# Extract the features and target variable from the test set
X_diff_test = test_diff_df.drop(target_column, axis=1)
y_diff_test = test_diff_df[target_column]

Train random forests and gradient boosting regressor models

This section trains random forest and gradient boosting models on differenced data, transforms predictions back to the original scale, and evaluates model performance using Mean Squared Error (MSE) and R-squared (R²) scores.

The following helper functions are used to post-process predictions and evaluate model performance:

  • transform_to_levels: Reconstructs the original values from differenced predictions by cumulatively summing them, starting from a given initial value.
  • evaluate_model: Calculates the Mean Squared Error (MSE) and R-squared (R²) score to evaluate the accuracy of the predictions against the true values.
def transform_to_levels(y_diff_pred, first_value=0): 
    y_pred = [first_value]
    for pred in y_diff_pred:
        y_pred.append(y_pred[-1] + pred)
    return y_pred

def evaluate_model(y_true, y_pred):
    mse = mean_squared_error(y_true, y_pred)
    r2 = r2_score(y_true, y_pred)
    return mse, r2
# Fit the random forest model
model_rf = RandomForestRegressor(n_estimators=1500, random_state=0)
model_rf.fit(X_diff_train, y_diff_train)

# Make predictions on the training and test sets
y_diff_train_pred = model_rf.predict(X_diff_train)
y_diff_test_pred = model_rf.predict(X_diff_test)

# Transform the predictions back to the original scale
y_train_rf_pred = transform_to_levels(y_diff_train_pred, first_value=train_df[target_column].iloc[0])
y_test_rf_pred = transform_to_levels(y_diff_test_pred, first_value=test_df[target_column].iloc[0])

# Evaluate the model's performance on the training and test sets
mse_train, r2_train = evaluate_model(train_df[target_column], y_train_rf_pred)
mse_test, r2_test = evaluate_model(test_df[target_column], y_test_rf_pred)

print(f"Train Mean Squared Error: {mse_train}")
print(f"Train R-Squared: {r2_train}")
print(f"Test Mean Squared Error: {mse_test}")
print(f"Test R-Squared: {r2_test}")
# Fit the gradient boost model
model_gb = GradientBoostingRegressor(n_estimators=1500, random_state=0)
model_gb.fit(X_diff_train, y_diff_train)

# Make predictions on the training and test sets
y_diff_train_pred = model_gb.predict(X_diff_train)
y_diff_test_pred = model_gb.predict(X_diff_test)

# Transform the predictions back to the original scale
y_train_gb_pred = transform_to_levels(y_diff_train_pred, first_value=train_df[target_column].iloc[0])
y_test_gb_pred = transform_to_levels(y_diff_test_pred, first_value=test_df[target_column].iloc[0])

# Evaluate the model's performance on the training and test sets
mse_train, r2_train = evaluate_model(train_df[target_column], y_train_gb_pred)
mse_test, r2_test = evaluate_model(test_df[target_column], y_test_gb_pred)

print(f"Train Mean Squared Error: {mse_train}")
print(f"Train R-Squared: {r2_train}")
print(f"Test Mean Squared Error: {mse_test}")
print(f"Test R-Squared: {r2_test}")

Initialize the ValidMind datasets

Before you can run tests, you must first initialize a ValidMind dataset object using the init_dataset function from the ValidMind (vm) module.

This function takes a number of arguments:

  • dataset — the raw dataset that you want to provide as input to tests
  • input_id - a unique identifier that allows tracking what inputs are used when running each individual test
  • target_column — a required argument if tests require access to true values. This is the name of the target column in the dataset

With all dataframes ready, you can now initialize the ValidMind datasets objects using vm.init_dataset():

  • vm_raw_ds: contains the raw, unprocessed data with the specified target column.
  • vm_train_diff_ds: contains the training data with the differenced target column, excluding the first row to remove NaN values caused by differencing.
  • vm_test_diff_ds: contains the test data with the differenced target column, excluding the first row to remove NaN values caused by differencing.
  • vm_train_ds: contains the training data, excluding the first row to align with the differenced data.
  • vm_test_ds: includes the test data split from the raw dataset.
vm_raw_ds = vm.init_dataset(
    input_id="raw_ds",
    dataset=raw_df,
    target_column=target_column,
)

vm_train_diff_ds = vm.init_dataset(
    input_id="train_diff_ds",
    dataset=train_diff_df,
    target_column=target_column,
)

vm_test_diff_ds = vm.init_dataset(
    input_id="test_diff_ds",
    dataset=test_diff_df,
    target_column=target_column,
)

vm_train_ds = vm.init_dataset(
    input_id="train_ds",
    dataset=train_df,
    target_column=target_column,
)

vm_test_ds = vm.init_dataset(
    input_id="test_ds",
    dataset=test_df,
    target_column=target_column,
)

Initialize the model objects

Additionally, you need to initialize a ValidMind model object (vm_model) for each model, that can be passed to other functions for analysis and tests on the data. You simply intialize this model object with vm.init_model():

vm_model_rf = vm.init_model(
    model_rf,
    input_id="random_forests_model",
)

vm_model_gb = vm.init_model(
    model_gb,
    input_id="gradient_boosting_model",
)

Assign predictions to the datasets

We can now use the assign_predictions() method from the Dataset object to link existing predictions to any model. If no prediction values are passed, the method will compute predictions automatically:

vm_train_ds.assign_predictions(
    model=vm_model_rf,
    prediction_values=y_train_rf_pred,
)

vm_test_ds.assign_predictions(
    model=vm_model_rf,
    prediction_values=y_test_rf_pred,
)

vm_train_ds.assign_predictions(
    model=vm_model_gb,
    prediction_values=y_train_gb_pred,
)

vm_test_ds.assign_predictions(
    model=vm_model_gb,
    prediction_values=y_test_gb_pred,
)
from validmind.utils import preview_test_config

test_config = fred_timeseries.get_demo_test_config()
preview_test_config(test_config)

Run data validation tests

test = vm.tests.run_test(
    "validmind.data_validation.TimeSeriesDescription",
    input_grid={
        "dataset": ["raw_ds", "train_diff_ds", "test_diff_ds", "train_ds", "test_ds"],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TimeSeriesLinePlot",
    input_grid={
        "dataset": ["raw_ds"],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TimeSeriesMissingValues",
    input_grid={
        "dataset": ["raw_ds", "train_diff_ds", "test_diff_ds", "train_ds", "test_ds"],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.SeasonalDecompose",
    input_grid={
        "dataset": ["raw_ds"],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TimeSeriesDescriptiveStatistics",
    input_grid={
        "dataset": ["train_diff_ds", "test_diff_ds"],
    },
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TimeSeriesOutliers",
    input_grid={
        "dataset": ["train_diff_ds", "test_diff_ds"],
    },
    params={
        "zscore_threshold": 4
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.TimeSeriesHistogram",
    input_grid={
        "dataset": [ "train_diff_ds", "test_diff_ds"],
    },
    params={
        "nbins": 100
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.data_validation.DatasetSplit",
    inputs={
        "datasets": ["train_diff_ds", "test_diff_ds"],
    }
)
test.log()

Run model validation tests

test = vm.tests.run_test(
    "validmind.model_validation.ModelMetadata",
    input_grid={
        "model": ["random_forests_model", "gradient_boosting_model"],
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.RegressionErrors",
    input_grid={
        "dataset": ["train_ds", "test_ds"],
        "model": ["random_forests_model", "gradient_boosting_model"],
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.RegressionR2Square",
    input_grid={
        "dataset": ["train_ds", "test_ds"],
        "model": ["random_forests_model", "gradient_boosting_model"],
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.TimeSeriesR2SquareBySegments:train_data",
    input_grid={
        "dataset": ["train_ds"],
        "model": ["random_forests_model", "gradient_boosting_model"],
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.TimeSeriesR2SquareBySegments:test_data",
    input_grid={
        "dataset": ["test_ds"],
        "model": ["random_forests_model", "gradient_boosting_model"],
    },
    params={
        "segments":{
            "start_date": ["2012-11-01","2018-02-01"],
            "end_date": ["2018-01-01","2023-03-01"]
        }
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.TimeSeriesPredictionsPlot",
    input_grid={
        "dataset": ["train_ds", "test_ds"],
        "model": ["random_forests_model", "gradient_boosting_model"],
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.TimeSeriesPredictionWithCI",
    input_grid={
        "dataset": ["train_ds", "test_ds"],
        "model": ["random_forests_model", "gradient_boosting_model"],
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.ModelPredictionResiduals",
    input_grid={
        "dataset": ["train_ds", "test_ds"],
        "model": ["random_forests_model", "gradient_boosting_model"],
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.FeatureImportance",
    input_grid={
        "dataset": ["train_ds", "test_ds"],
        "model": ["random_forests_model", "gradient_boosting_model"],
    }
)
test.log()
test = vm.tests.run_test(
    "validmind.model_validation.sklearn.PermutationFeatureImportance",
    input_grid={
        "dataset": ["train_ds", "test_ds"],
        "model": ["random_forests_model", "gradient_boosting_model"],
    }
)
test.log()

Next steps

You can look at the results of this test suite right in the notebook where you ran the code, as you would expect. But there is a better way — use the ValidMind platform to work with your model documentation.

Work with your model documentation

  1. From the Model Inventory in the ValidMind Platform UI, go to the model you registered earlier. (Need more help?)

  2. Click and expand the Model Development section.

What you see is the full draft of your model documentation in a more easily consumable version. From here, you can make qualitative edits to model documentation, view guidelines, collaborate with validators, and submit your model documentation for approval when it’s ready. Learn more …

Discover more learning resources

We offer many interactive notebooks to help you document models:

Or, visit our documentation to learn more about ValidMind.