{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f2c17b2d",
   "metadata": {},
   "source": [
    "# Quickstart for model documentation\n",
    "\n",
    "Learn the basics of using ValidMind to document models as part of a model development workflow. Set up the ValidMind Library in your environment, and generate a draft of documentation using ValidMind tests for a binary classification model.\n",
    "\n",
    "To document a model with the ValidMind Library, we'll:\n",
    "\n",
    "1. Import a sample dataset and preprocess it\n",
    "2. Split the datasets and initialize them for use with ValidMind\n",
    "3. Initialize a model object for use with testing\n",
    "4. Run a full suite of tests as defined by our documentation template, which will send the results of those tests to the ValidMind Platform"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05dce32a",
   "metadata": {},
   "source": [
    "::: {.content-hidden when-format=\"html\"}\n",
    "## Contents    \n",
    "- [Introduction](#toc1_)    \n",
    "- [About ValidMind](#toc2_)    \n",
    "  - [Before you begin](#toc2_1_)    \n",
    "  - [New to ValidMind?](#toc2_2_)    \n",
    "  - [Key concepts](#toc2_3_)    \n",
    "- [Setting up](#toc3_)    \n",
    "  - [Install the ValidMind Library](#toc3_1_)    \n",
    "  - [Initialize the ValidMind Library](#toc3_2_)    \n",
    "    - [Get your code snippet](#toc3_2_1_)    \n",
    "  - [Initialize the Python environment](#toc3_3_)    \n",
    "- [Getting to know ValidMind](#toc4_)    \n",
    "  - [Preview the documentation template](#toc4_1_)    \n",
    "  - [View model documentation in the ValidMind Platform](#toc4_2_)    \n",
    "- [Import the sample dataset](#toc5_)    \n",
    "- [Preprocessing the raw dataset](#toc6_)    \n",
    "  - [Split the dataset](#toc6_1_)    \n",
    "  - [Separate features and targets](#toc6_2_)    \n",
    "- [Training an XGBoost classifier model](#toc7_)    \n",
    "  - [Set evaluation metrics](#toc7_1_)    \n",
    "  - [Fit the model](#toc7_2_)    \n",
    "- [Initialize the ValidMind datasets](#toc8_)    \n",
    "- [Initialize a model object](#toc9_)    \n",
    "  - [Assign predictions](#toc9_1_)    \n",
    "- [Run the full suite of tests](#toc10_)    \n",
    "- [In summary](#toc11_)    \n",
    "- [Next steps](#toc12_)    \n",
    "  - [Work with your model documentation](#toc12_1_)    \n",
    "  - [Discover more learning resources](#toc12_2_)    \n",
    "- [Upgrade ValidMind](#toc13_)    \n",
    "\n",
    ":::\n",
    "<!-- jn-toc-notebook-config\n",
    "\tnumbering=false\n",
    "\tanchor=true\n",
    "\tflat=false\n",
    "\tminLevel=2\n",
    "\tmaxLevel=4\n",
    "\t/jn-toc-notebook-config -->\n",
    "<!-- THIS CELL WILL BE REPLACED ON TOC UPDATE. DO NOT WRITE YOUR TEXT IN THIS CELL -->"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1919918",
   "metadata": {},
   "source": [
    "<a id='toc1_'></a>\n",
    "\n",
    "## Introduction\n",
    "\n",
    "Model development aims to produce a fit-for-purpose *champion model* by conducting thorough testing and analysis, supporting the capabilities of the model with evidence in the form of documentation and test results. Model documentation should be clear and comprehensive, ideally following a structure or template covering all aspects of compliance with model risk regulation.\n",
    "\n",
    "A *binary classification model* is a type of predictive model used in churn analysis to identify customers who are likely to leave a service or subscription by analyzing various behavioral, transactional, and demographic factors.\n",
    "\n",
    "- This model helps businesses take proactive measures to retain at-risk customers by offering personalized incentives, improving customer service, or adjusting pricing strategies.\n",
    "- Effective validation of a churn prediction model ensures that businesses can accurately identify potential churners, optimize retention efforts, and enhance overall customer satisfaction while minimizing revenue loss."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8f85783",
   "metadata": {},
   "source": [
    "<a id='toc2_'></a>\n",
    "\n",
    "## About ValidMind\n",
    "\n",
    "ValidMind is a suite of tools for managing model risk, including risk associated with AI and statistical models. \n",
    "\n",
    "You use the ValidMind Library to automate documentation and validation tests, and then use the ValidMind Platform 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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87fbc9d8",
   "metadata": {},
   "source": [
    "<a id='toc2_1_'></a>\n",
    "\n",
    "### Before you begin\n",
    "\n",
    "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. \n",
    "\n",
    "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](https://docs.python.org/3/installing/index.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f368277",
   "metadata": {},
   "source": [
    "<a id='toc2_2_'></a>\n",
    "\n",
    "### New to ValidMind?\n",
    "\n",
    "If you haven't already seen our documentation on the [ValidMind Library](https://docs.validmind.ai/developer/validmind-library.html), we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models and running tests, as well as find code samples and our Python Library API reference.\n",
    "\n",
    "<div class=\"alert alert-block alert-info\" style=\"background-color: #B5B5B510; color: black; border: 1px solid #083E44; border-left-width: 5px; box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);border-radius: 5px;\"><span style=\"color: #083E44;\"><b>For access to all features available in this notebook, create a free ValidMind account.</b></span>\n",
    "<br></br>\n",
    "Signing up is FREE — <a href=\"https://docs.validmind.ai/guide/configuration/register-with-validmind.html\" style=\"color: #DE257E;\"><b>Register with ValidMind</b></a></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec08fd19",
   "metadata": {},
   "source": [
    "<a id='toc2_3_'></a>\n",
    "\n",
    "### Key concepts\n",
    "\n",
    "**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.\n",
    "\n",
    "**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.\n",
    "\n",
    "**Tests**: A function contained in the ValidMind Library, 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.\n",
    "\n",
    "**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.\n",
    "\n",
    "**Custom metrics**: Custom metrics are functions that you define to evaluate your model or dataset. These functions can be registered with the ValidMind Library to be used in the ValidMind Platform.\n",
    "\n",
    "**Inputs**: Objects to be evaluated and documented in the ValidMind Library. They can be any of the following:\n",
    "\n",
    "  - **model**: A single model that has been initialized in ValidMind with [`vm.init_model()`](https://docs.validmind.ai/validmind/validmind.html#init_model).\n",
    "  - **dataset**: Single dataset that has been initialized in ValidMind with [`vm.init_dataset()`](https://docs.validmind.ai/validmind/validmind.html#init_dataset).\n",
    "  - **models**: A list of ValidMind models - usually this is used when you want to compare multiple models in your custom metric.\n",
    "  - **datasets**: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom metric. (Learn more: [Run tests with multiple datasets](https://docs.validmind.ai/notebooks/how_to/run_tests_that_require_multiple_datasets.html))\n",
    "\n",
    "**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.\n",
    "\n",
    "**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.\n",
    "\n",
    "**Test suites**: Collections of tests designed to run together to automate and generate model documentation end-to-end for specific use-cases.\n",
    "\n",
    "Example: the [`classifier_full_suite`](https://docs.validmind.ai/validmind/validmind/test_suites/classifier.html#ClassifierFullSuite) test suite runs tests from the [`tabular_dataset`](https://docs.validmind.ai/validmind/validmind/test_suites/tabular_datasets.html) and [`classifier`](https://docs.validmind.ai/validmind/validmind/test_suites/classifier.html) test suites to fully document the data and model sections for binary classification model use-cases."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8883927",
   "metadata": {},
   "source": [
    "<a id='toc3_'></a>\n",
    "\n",
    "## Setting up"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc3_1_'></a>\n",
    "\n",
    "### Install the ValidMind Library\n",
    "\n",
    "<div class=\"alert alert-block alert-info\" style=\"background-color: #B5B5B510; color: black; border: 1px solid #083E44; border-left-width: 5px; box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);border-radius: 5px;\"><span style=\"color: #083E44;\"><b>Recommended Python versions</b></span>\n",
    "<br></br>\n",
    "Python 3.8 <= x <= 3.11</div>\n",
    "\n",
    "To install the library:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1f6dbed",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q validmind"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "797eb7f0",
   "metadata": {},
   "source": [
    "<a id='toc3_2_'></a>\n",
    "\n",
    "### Initialize the ValidMind Library\n",
    "\n",
    "ValidMind generates a unique _code snippet_ for each registered model to connect with your developer environment. You initialize the ValidMind Library with this code snippet, which ensures that your documentation and tests are uploaded to the correct model when you run the notebook."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc3_2_1_'></a>\n",
    "\n",
    "#### Get your code snippet\n",
    "\n",
    "1. In a browser, [log in to ValidMind](https://docs.validmind.ai/guide/configuration/log-in-to-validmind.html).\n",
    "\n",
    "2. In the left sidebar, navigate to **Inventory** and click **+ Register Model**.\n",
    "\n",
    "3. Enter the model details and click **Continue**. ([Need more help?](https://docs.validmind.ai/guide/model-inventory/register-models-in-inventory.html))\n",
    "\n",
    "   For example, to register a model for use with this notebook, select:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74d329e8",
   "metadata": {},
   "source": [
    "   - Documentation template: `Binary classification`\n",
    "   - Use case: `Marketing/Sales - Attrition/Churn Management`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "install-credentials-4c404843-3474-4618-8898-f3bcce33fadd",
   "metadata": {},
   "source": [
    "   You can fill in other options according to your preference.\n",
    "   \n",
    "4. Go to **Getting Started** and click **Copy snippet to clipboard**.\n",
    "\n",
    "Next, [load your model identifier credentials from an `.env` file](https://docs.validmind.ai/developer/model-documentation/store-credentials-in-env-file.html) or replace the placeholder with your own code snippet:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e2c1dd22",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load your model identifier credentials from an `.env` file\n",
    "\n",
    "%load_ext dotenv\n",
    "%dotenv .env\n",
    "\n",
    "# Or replace with your code snippet\n",
    "\n",
    "import validmind as vm\n",
    "\n",
    "vm.init(\n",
    "    # api_host=\"...\",\n",
    "    # api_key=\"...\",\n",
    "    # api_secret=\"...\",\n",
    "    # model=\"...\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44bf926b",
   "metadata": {},
   "source": [
    "<a id='toc3_3_'></a>\n",
    "\n",
    "### Initialize the Python environment\n",
    "\n",
    "Then, let's import the necessary libraries and set up your Python environment for data analysis:\n",
    "\n",
    "- Import **Extreme Gradient Boosting** (XGBoost) with an alias so that we can reference its functions in later calls. XGBoost is a powerful machine learning library designed for speed and performance, especially in handling structured or tabular data.\n",
    "- Enable **`matplotlib`**, a plotting library used for visualizing data. Ensures that any plots you generate will render inline in our notebook output rather than opening in a separate window."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62d7c2c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import xgboost as xgb\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41474c53",
   "metadata": {},
   "source": [
    "<a id='toc4_'></a>\n",
    "\n",
    "## Getting to know ValidMind"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d87ae6f",
   "metadata": {},
   "source": [
    "<a id='toc4_1_'></a>\n",
    "\n",
    "### Preview the documentation template\n",
    "\n",
    "Let's verify that you have connected the ValidMind Library to the ValidMind Platform and that the appropriate *template* is selected for your model. A template predefines sections for your model documentation and provides a general outline to follow, making the documentation process much easier.\n",
    "\n",
    "You will upload documentation and test results unique to your model based on this template later on. For now, **take a look at the default structure that the template provides with [the `vm.preview_template()` function](https://docs.validmind.ai/validmind/validmind.html#preview_template)** from the ValidMind library and note the empty sections:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2bce375",
   "metadata": {},
   "outputs": [],
   "source": [
    "vm.preview_template()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa3b815d",
   "metadata": {},
   "source": [
    "<a id='toc4_2_'></a>\n",
    "\n",
    "### View model documentation in the ValidMind Platform\n",
    "\n",
    "Next, let's head to the ValidMind Platform to see the template in action:\n",
    "\n",
    "1. In a browser, [log in to ValidMind](https://docs.validmind.ai/guide/configuration/log-in-to-validmind.html).\n",
    "\n",
    "2. In the left sidebar, navigate to **Inventory** and select the model you registered for this notebook.\n",
    "\n",
    "3. Click on the **Documentation** for your model and note how the structure of the documentation matches our preview above."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bde500ce",
   "metadata": {},
   "source": [
    "<a id='toc5_'></a>\n",
    "\n",
    "## Import the sample dataset\n",
    "\n",
    "First, let's import the public [Bank Customer Churn Prediction](https://www.kaggle.com/datasets/shantanudhakadd/bank-customer-churn-prediction) dataset from Kaggle so that we have something to work with.\n",
    "\n",
    "In our below example, note that: \n",
    "\n",
    "- The target column, `Exited` has a value of `1` when a customer has churned and `0` otherwise.\n",
    "- The ValidMind Library provides a wrapper to automatically load the dataset as a [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html) object. A Pandas Dataframe is a two-dimensional tabular data structure that makes use of rows and columns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58d1c94b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from validmind.datasets.classification import customer_churn\n",
    "\n",
    "print(\n",
    "    f\"Loaded demo dataset with: \\n\\n\\t• Target column: '{customer_churn.target_column}' \\n\\t• Class labels: {customer_churn.class_labels}\"\n",
    ")\n",
    "\n",
    "raw_df = customer_churn.load_data()\n",
    "raw_df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52d0aaa8",
   "metadata": {},
   "source": [
    "<a id='toc6_'></a>\n",
    "\n",
    "## Preprocessing the raw dataset\n",
    "\n",
    "Before running tests with Validmind, we'll need to preprocess our imported dataset. This involves splitting the data and separating the features (inputs) from the targets (outputs)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83545763",
   "metadata": {},
   "source": [
    "<a id='toc6_1_'></a>\n",
    "\n",
    "### Split the dataset\n",
    "\n",
    "Splitting our dataset helps assess how well the model generalizes to unseen data.\n",
    "\n",
    "Use [`preprocess()`](https://docs.validmind.ai/validmind/validmind/datasets/classification/customer_churn.html#preprocess) to split our dataset into three subsets:\n",
    "\n",
    "1. **train_df** — Used to train the model.\n",
    "2. **validation_df** — Used to evaluate the model's performance during training.\n",
    "3. **test_df** — Used later on to asses the model's performance on new, unseen data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "418cb5aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "train_df, validation_df, test_df = customer_churn.preprocess(raw_df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0ae3dc5",
   "metadata": {},
   "source": [
    "<a id='toc6_2_'></a>\n",
    "\n",
    "### Separate features and targets\n",
    "\n",
    "To train the model, we need to provide it with:\n",
    "\n",
    "1. **Inputs** — Features such as customer age, usage, etc.\n",
    "2. **Outputs (Expected answers/labels)** — in our case, we would like to know whether the customer churned or not.\n",
    "\n",
    "Here, we'll use `x_train` and `x_val` to hold the input data (features), and `y_train` and `y_val` to hold the answers (the target we want to predict):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6fd365fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_train = train_df.drop(customer_churn.target_column, axis=1)\n",
    "y_train = train_df[customer_churn.target_column]\n",
    "x_val = validation_df.drop(customer_churn.target_column, axis=1)\n",
    "y_val = validation_df[customer_churn.target_column]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_'></a>\n",
    "\n",
    "## Training an XGBoost classifier model\n",
    "\n",
    "Next, let's create an XGBoost classifier model that will automatically stop training if it doesn’t improve after 10 tries.\n",
    "\n",
    "Setting a threshold avoids wasting time and helps prevent overfitting by stopping training when further improvement isn’t happening."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3296cac6",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = xgb.XGBClassifier(early_stopping_rounds=10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "826d8adf",
   "metadata": {},
   "source": [
    "<a id='toc7_1_'></a>\n",
    "\n",
    "### Set evaluation metrics\n",
    "\n",
    "Then, we'll set the evaluation metrics, which tells the model to use three different ways to measure its performance:\n",
    "\n",
    "1. **error** — Measures how often the model makes incorrect predictions.\n",
    "2. **logloss** — Indicates how confident the predictions are.\n",
    "3. **auc** — Evaluates how well the model distinguishes between churn and not churn.\n",
    "\n",
    "Using multiple metrics gives a more complete picture of how good (or bad) the model is."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "32d3c3f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "model.set_params(\n",
    "    eval_metric=[\"error\", \"logloss\", \"auc\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc7_2_'></a>\n",
    "\n",
    "### Fit the model\n",
    "\n",
    "Finally, our actual training step — where the model learns patterns from the data, so it can make predictions later:\n",
    "\n",
    "- The model is trained on `x_train` and `y_train`, and evaluates its performance using `x_val` and `y_val` to check if it’s learning well.\n",
    "- To turn off printed output while training, we'll set `verbose` to `False`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fb95ce4",
   "metadata": {},
   "outputs": [],
   "source": [
    "model.fit(\n",
    "    x_train,\n",
    "    y_train,\n",
    "    eval_set=[(x_val, y_val)],\n",
    "    verbose=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc8_'></a>\n",
    "\n",
    "## Initialize the ValidMind datasets\n",
    "\n",
    "Before you can run tests with your preprocessed datasets, you must first initialize a ValidMind `Dataset` object using the [`init_dataset`](https://docs.validmind.ai/validmind/validmind.html#init_dataset) function from the ValidMind (`vm`) module. **This step is always necessary every time you want to connect a dataset to documentation and produce test results through ValidMind,** but you only need to do it once per dataset.\n",
    "\n",
    "For this example, we'll pass in the following arguments:\n",
    "\n",
    "- **`dataset`** — The raw dataset that you want to provide as input to tests.\n",
    "- **`input_id`** — A unique identifier that allows tracking what inputs are used when running each individual test.\n",
    "- **`target_column`** — A required argument if tests require access to true values. This is the name of the target column in the dataset.\n",
    "- **`class_labels`** — An optional value to map predicted classes to class labels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb6ad06a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize the raw dataset\n",
    "vm_raw_dataset = vm.init_dataset(\n",
    "    dataset=raw_df,\n",
    "    input_id=\"raw_dataset\",\n",
    "    target_column=customer_churn.target_column,\n",
    "    class_labels=customer_churn.class_labels,\n",
    ")\n",
    "\n",
    "# Initialize the training dataset\n",
    "vm_train_ds = vm.init_dataset(\n",
    "    dataset=train_df,\n",
    "    input_id=\"train_dataset\",\n",
    "    target_column=customer_churn.target_column,\n",
    ")\n",
    "\n",
    "# Initialize the testing dataset\n",
    "vm_test_ds = vm.init_dataset(\n",
    "    dataset=test_df,\n",
    "    input_id=\"test_dataset\",\n",
    "    target_column=customer_churn.target_column\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc9_'></a>\n",
    "\n",
    "## Initialize a model object\n",
    "\n",
    "You'll also need to initialize a ValidMind model object (`vm_model`) that can be passed to other functions for analysis and tests on the data for our model.\n",
    "\n",
    "You simply initialize this model object with [`vm.init_model()`](https://docs.validmind.ai/validmind/validmind.html#init_model):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e44eebd",
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_model = vm.init_model(\n",
    "    model,\n",
    "    input_id=\"model\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc9_1_'></a>\n",
    "\n",
    "### Assign predictions\n",
    "\n",
    "Once the model has been registered, you can assign model predictions to the training and testing datasets.\n",
    "\n",
    "- The [`assign_predictions()` method](https://docs.validmind.ai/validmind/validmind/vm_models.html#assign_predictions) from the `Dataset` object can link existing predictions to any number of models.\n",
    "- This method links the model's class prediction values and probabilities to our `vm_train_ds` and `vm_test_ds` datasets.\n",
    "\n",
    "If no prediction values are passed, the method will compute predictions automatically:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62bd94fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "vm_train_ds.assign_predictions(\n",
    "    model=vm_model,\n",
    ")\n",
    "\n",
    "vm_test_ds.assign_predictions(\n",
    "    model=vm_model,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc10_'></a>\n",
    "\n",
    "## Run the full suite of tests\n",
    "\n",
    "This is where it all comes together — you are now ready to **run the documentation tests for the model as defined by the documentation template** you looked at earlier.\n",
    "\n",
    "The [`vm.run_documentation_tests`](https://docs.validmind.ai/validmind/validmind.html#run_documentation_tests) function finds and runs every test specified in the template and then uploads all the documentation and test artifacts that get generated to the ValidMind Platform:\n",
    "\n",
    "- The function requires information about the inputs to use on every test. These inputs can be passed as an `inputs` argument if we want to use the same inputs for all tests. \n",
    "- It's also possible to pass a `config` argument that has information about the `params` and `inputs` that each test requires. The `config` parameter is a dictionary with the following structure:\n",
    "\n",
    "    ```python\n",
    "    config = {\n",
    "        \"<test-id>\": {\n",
    "            \"params\": {\n",
    "                \"param1\": \"value1\",\n",
    "                \"param2\": \"value2\",\n",
    "                ...\n",
    "            },\n",
    "            \"inputs\": {\n",
    "                \"input1\": \"value1\",\n",
    "                \"input2\": \"value2\",\n",
    "                ...\n",
    "            }\n",
    "        },\n",
    "        ...\n",
    "    }\n",
    "    ```\n",
    "\n",
    "    Each `<test-id>` above corresponds to the test driven block identifiers shown by `vm.preview_template()`. For this model, we will use the default parameters for all tests, but we'll need to specify the input configuration for each one. The method `get_demo_test_config()` below constructs the default input configuration for our demo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3d6741b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from validmind.utils import preview_test_config\n",
    "\n",
    "test_config = customer_churn.get_demo_test_config()\n",
    "preview_test_config(test_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70830a61",
   "metadata": {},
   "source": [
    "Now we can pass the input configuration to `vm.run_documentation_tests()` and run the full suite of tests.\n",
    "\n",
    "The variable `full_suite` then holds the result of these tests:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae3accf7",
   "metadata": {},
   "outputs": [],
   "source": [
    "full_suite = vm.run_documentation_tests(config=test_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79f1b475",
   "metadata": {},
   "source": [
    "<a id='toc11_'></a>\n",
    "\n",
    "## In summary\n",
    "\n",
    "In this notebook, you learned how to:\n",
    "\n",
    "- [x] Register a model within the ValidMind Platform\n",
    "- [x] Install and initialize the ValidMind Library\n",
    "- [x] Preview the documentation template for your model\n",
    "- [x] Import a sample dataset\n",
    "- [x] Initialize ValidMind datasets and model objects\n",
    "- [x] Assign model predictions to your ValidMind model objects\n",
    "- [x] Run a full suite of documentation tests\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adcc9956",
   "metadata": {},
   "source": [
    "<a id='toc12_'></a>\n",
    "\n",
    "## Next steps\n",
    "\n",
    "You can look at the output produced by the ValidMind Library 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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b8e72f6",
   "metadata": {},
   "source": [
    "<a id='toc12_1_'></a>\n",
    "\n",
    "### Work with your model documentation\n",
    "\n",
    "1. From the **Inventory** in the ValidMind Platform, go to the model you registered earlier. ([Need more help?](https://docs.validmind.ai/guide/model-inventory/working-with-model-inventory.html))\n",
    "\n",
    "2. In the left sidebar that appears for your model, click **Documentation**.\n",
    "\n",
    "    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 ...](https://docs.validmind.ai/guide/working-with-model-documentation.html)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "585b79fd",
   "metadata": {},
   "source": [
    "<a id='toc12_2_'></a>\n",
    "\n",
    "### Discover more learning resources\n",
    "\n",
    "For a more in-depth introduction to using the ValidMind Library for development, check out our introductory development series and the accompanying interactive training:\n",
    "\n",
    "- **[ValidMind for model development](https://docs.validmind.ai/developer/validmind-library.html#for-model-development)**\n",
    "- **[Developer Fundamentals](https://docs.validmind.ai/training/developer-fundamentals/developer-fundamentals-register.html)**\n",
    "\n",
    "We also offer many interactive notebooks to help you document models:\n",
    "\n",
    "- [Run tests & test suites](https://docs.validmind.ai/guide/testing-overview.html)\n",
    "- [Code samples](https://docs.validmind.ai/guide/samples-jupyter-notebooks.html)\n",
    "\n",
    "Or, visit our [documentation](https://docs.validmind.ai/) to learn more about ValidMind."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc13_'></a>\n",
    "\n",
    "## Upgrade ValidMind\n",
    "\n",
    "<div class=\"alert alert-block alert-info\" style=\"background-color: #B5B5B510; color: black; border: 1px solid #083E44; border-left-width: 5px; box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);border-radius: 5px;\">After installing ValidMind, you’ll want to periodically make sure you are on the latest version to access any new features and other enhancements.</div>\n",
    "\n",
    "Retrieve the information for the currently installed version of ValidMind:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35955b6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip show validmind"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "upgrade-version-ab5a531d-4334-4c5b-b6aa-754e336f127f",
   "metadata": {},
   "source": [
    "If the version returned is lower than the version indicated in our [production open-source code](https://github.com/validmind/validmind-library/blob/prod/validmind/__version__.py), restart your notebook and run:\n",
    "\n",
    "```bash\n",
    "%pip install --upgrade validmind\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "upgrade-restart-faf9c324-3332-4eaf-aef5-2c0ca650d5ca",
   "metadata": {},
   "source": [
    "You may need to restart your kernel after running the upgrade package for changes to be applied."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ValidMind Library",
   "language": "python",
   "name": "validmind"
  },
  "language_info": {
   "name": "python",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
