Fitting Contextualized Models
Contents
Fitting Contextualized Models#
Let’s walk through an example of Contextualized analysis.
Download and Prepare Data#
First, we will load the data into a standard pandas dataframe or a numpy array, and create a train / test split. There’s only 1 step of preprocessing required: deciding the context variables..
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_diabetes
X, Y = load_diabetes(return_X_y=True, as_frame=True)
Y = np.expand_dims(Y.values, axis=-1)
C = X[['age', 'sex', 'bmi']]
X.drop(['age', 'sex', 'bmi'], axis=1, inplace=True)
seed = 1
C_train, C_test, X_train, X_test, Y_train, Y_test = train_test_split(C, X, Y, test_size=0.20, random_state=seed)
Train a Contextualized Model#
Contextualized models follow an sklearn-like interface to make training easy.
%%capture
from contextualized.easy import ContextualizedRegressor
model = ContextualizedRegressor(n_bootstraps=10)
model.fit(C_train.values, X_train.values, Y_train,
encoder_type="mlp", max_epochs=3,
learning_rate=1e-2)
Save the trained model.#
from contextualized.utils import save, load
save_path = './easy_demo_model.pt'
save(model, path=save_path)
The model can be re-loaded with:#
model = load(save_path)