From d765d9dd3140a2a91b465cde10a46efbb3eac44a Mon Sep 17 00:00:00 2001 From: Andres Rodriguez Date: Mon, 26 Oct 2026 11:48:52 -0700 Subject: [PATCH 1/2] docs: list the individual-tests quickstart notebook Add quickstart_documentation_run_test.ipynb (validmind-library#576) to the developer sidebar and the ValidMind Library quickstart listing, next to the other quickstart variants. Co-Authored-By: Claude Opus 5.5 --- site/developer/_sidebar.yaml | 2 ++ site/developer/validmind-library.qmd | 1 + 2 files changed, 3 insertions(+) diff --git a/site/developer/_sidebar.yaml b/site/developer/_sidebar.yaml index 72307efb8..ffefaf8b5 100644 --- a/site/developer/_sidebar.yaml +++ b/site/developer/_sidebar.yaml @@ -17,6 +17,8 @@ website: - notebooks/quickstart/quickstart_validation.ipynb - text: "Quickstart (OIDC device flow)" file: notebooks/quickstart/quickstart_model_documentation_oidc_device_flow.ipynb + - text: "Quickstart (individual tests)" + file: notebooks/quickstart/quickstart_documentation_run_test.ipynb # USING THE VARIABLE IN THE LINK TEXT MESSES UP THE MOBILE VIEW & BREADCRUMB - section: "Install and initialize ValidMind" contents: diff --git a/site/developer/validmind-library.qmd b/site/developer/validmind-library.qmd index 3ff75d309..3313b82de 100644 --- a/site/developer/validmind-library.qmd +++ b/site/developer/validmind-library.qmd @@ -22,6 +22,7 @@ listing: - ../notebooks/quickstart/quickstart_documentation.ipynb - ../notebooks/quickstart/quickstart_validation.ipynb - ../notebooks/quickstart/quickstart_model_documentation_oidc_device_flow.ipynb + - ../notebooks/quickstart/quickstart_documentation_run_test.ipynb - quickstart/authenticate-with-oidc-device-flow.qmd - id: development type: grid From a682db95950962055306b802866edd2085265a7c Mon Sep 17 00:00:00 2001 From: Andres Rodriguez Date: Wed, 28 Oct 2026 11:57:56 -0700 Subject: [PATCH 2/2] Vendor quickstart_documentation_run_test notebook from validmind-library The sidebar and listing linked a notebook that was not yet copied into site/notebooks, so validate failed on unresolved link targets. Co-Authored-By: Claude Opus 5.5 --- .../quickstart_documentation_run_test.ipynb | 939 ++++++++++++++++++ 1 file changed, 939 insertions(+) create mode 100644 site/notebooks/quickstart/quickstart_documentation_run_test.ipynb diff --git a/site/notebooks/quickstart/quickstart_documentation_run_test.ipynb b/site/notebooks/quickstart/quickstart_documentation_run_test.ipynb new file mode 100644 index 000000000..43eb287d5 --- /dev/null +++ b/site/notebooks/quickstart/quickstart_documentation_run_test.ipynb @@ -0,0 +1,939 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Quickstart for documentation with individual tests\n", + "\n", + "Learn the basics of using ValidMind to document records as part of a development workflow. Set up the ValidMind Library in your environment, then run individual tests and log their results to a document that has no content blocks registered yet.\n", + "\n", + "To document our 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 ValidMind model object for use with testing\n", + "4. Run individual tests with `vm.tests.run_test()` and log each result to the ValidMind Platform with `result.log()`\n" + ], + "id": "9b60f7c9" + }, + { + "cell_type": "markdown", + "id": "167aef58", + "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", + " - [Register sample model](#toc3_2_1__) \n", + " - [Create an empty document](#toc3_2_2__) \n", + " - [Get your code snippet](#toc3_2_3__) \n", + " - [Initialize the Python environment](#toc3_3__) \n", + "- [Getting to know ValidMind](#toc4__) \n", + " - [View documentation in the ValidMind Platform](#toc4_1__) \n", + "- [Working with ValidMind datasets](#toc5__) \n", + " - [Prepare the sample dataset](#toc5_1__) \n", + " - [Import the sample dataset](#toc5_1_1__) \n", + " - [Preprocess the raw dataset](#toc5_1_2__) \n", + " - [Split the dataset](#toc5_1_3__) \n", + " - [Separate features and targets](#toc5_1_4__) \n", + " - [Initialize the ValidMind datasets](#toc5_2__) \n", + "- [Working with ValidMind models](#toc6__) \n", + " - [Train an XGBoost classifier model](#toc6_1__) \n", + " - [Set evaluation metrics](#toc6_1_1__) \n", + " - [Fit the model](#toc6_1_2__) \n", + " - [Initialize the ValidMind model](#toc6_2__) \n", + " - [Assign predictions](#toc6_3__) \n", + "- [Run and log individual tests](#toc7__) \n", + " - [Run and log a set of tests](#toc7_1__) \n", + "- [In summary](#toc8__) \n", + "- [Next steps](#toc9__) \n", + " - [Work with your documentation](#toc9_1__) \n", + " - [Discover more learning resources](#toc9_2__) \n", + "- [Upgrade ValidMind](#toc10__) \n", + "\n", + ":::\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "1cce526f", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Introduction\n", + "\n", + "Development aims to produce a fit-for-purpose *champion* by conducting thorough testing and analysis, supporting the capabilities of the champion with evidence in the form of documentation and test results. Documentation should be clear and comprehensive, ideally following a structure or template covering all aspects of compliance with 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": "f9b5eac2", + "metadata": {}, + "source": [ + "\n", + "\n", + "## About ValidMind\n", + "\n", + "ValidMind is a suite of tools for managing 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 documentation. Together, these products simplify risk management, facilitate compliance with regulations and institutional standards, and enhance collaboration between yourself and validators." + ] + }, + { + "cell_type": "markdown", + "id": "650236de", + "metadata": {}, + "source": [ + "\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": "b9d9d4cf", + "metadata": {}, + "source": [ + "\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 records such as models and running tests, as well as find code samples and our Python Library API reference.\n", + "\n", + "
For access to all features available in this notebook, you'll need access to a ValidMind account.\n", + "

\n", + "Register with ValidMind
" + ] + }, + { + "cell_type": "markdown", + "id": "59b308f7", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Key concepts\n", + "\n", + "**record**: A tool tracked in the ValidMind inventory, such as a model. Records include traditional statistical models, legacy systems, artificial intelligence/machine learning models, large language models (LLMs), agentic AI systems, and other documentable items that benefit from oversight, testing, and lifecycle management.\n", + "\n", + "**model**: [SR 26-2](https://www.federalreserve.gov/supervisionreg/srletters/SR2602.htm) (which supersedes SR 11-7) defines a model as a \"complex quantitative method, system, or approach that applies statistical, economic, or financial theories to process input data into quantitative estimates.\" Simple arithmetic, deterministic rule-based processes, or software without statistical, economic, or financial theories underpinning their design or use are generally outside SR 26-2’s definition of a model. Within ValidMind, a model is a type of record tracked in the inventory.\n", + "\n", + "**documentation, model documentation**: A structured and detailed document pertaining to a record, encompassing key components such as its underlying assumptions, methodologies, data sources, inputs, performance metrics, evaluations, limitations, and intended uses. Within the realm of risk management, this documentation serves to ensure transparency, adherence to regulatory requirements, and a clear understanding of potential risks associated with the record's application.\n", + "\n", + "**document template**: Lays out the structure of documents, segmented into various sections and sub-sections, and functions as a test suite specifying the tests that should be run, and how the results should be displayed. Document templates help automate your development, validation, monitoring, and other risk management processes. Document templates are available for default ValidMind document types as well as custom document types.\n", + "\n", + "**documentation template**: A default ValidMind document type that serves as a standardized framework for developing and documenting records, including sections designated for record details, data descriptions, test results, and performance metrics. By outlining required documentation and recommended analyses, document templates ensure consistency and completeness across documentation and help guide developers through a systematic development process while promoting comparability and traceability of development outcomes.\n", + "\n", + "**test**: A function contained in the ValidMind Library, designed to run a specific quantitative test on the dataset or record. Test results are logged to the ValidMind Platform, where they are attached to documents. Tests are the building blocks of ValidMind, used to evaluate and document records and datasets, and can be run individually or as part of a suite defined by your templates.\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 record that has been initialized in ValidMind with [`init_model()`](https://docs.validmind.ai/validmind/validmind.html#init_model). Despite the naming convention, model objects can be any type of record you want to test, document, validate, or monitor with ValidMind.\n", + " - **dataset**: A single dataset that has been initialized in ValidMind with [`init_dataset()`](https://docs.validmind.ai/validmind/validmind.html#init_dataset).\n", + " - **models**: A list of ValidMind records - usually this is used when you want to compare multiple records in your custom tests.\n", + " - **datasets**: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom tests. (Learn more: [Run tests with multiple datasets](https://docs.validmind.ai/notebooks/how_to/tests/run_tests/configure_tests/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 test, customize its behavior, or provide additional context.\n", + "\n", + "**outputs**: Custom tests 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." + ] + }, + { + "cell_type": "markdown", + "id": "61b5cbeb", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Setting up" + ] + }, + { + "cell_type": "markdown", + "id": "0f08166e", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Install the ValidMind Library\n", + "\n", + "
Recommended Python versions\n", + "

\n", + "Python 3.8 <= x <= 3.14
\n", + "\n", + "To install the library, with the `xgboost` extra for our model and the `explainability` extra for the SHAP test we run later:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d1f6dbed", + "metadata": {}, + "outputs": [], + "source": [ + "%pip install -q \"validmind[xgboost,explainability]\"" + ] + }, + { + "cell_type": "markdown", + "id": "1bf4e4cb", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Initialize the ValidMind Library" + ] + }, + { + "cell_type": "markdown", + "id": "cb6e369b", + "metadata": {}, + "source": [ + "\n", + "\n", + "#### Register sample model\n", + "\n", + "Let's first register a sample record (model) for use with this notebook:\n", + "\n", + "1. In a browser, [log in to ValidMind](https://docs.validmind.ai/guide/access/log-in-to-validmind.html).\n", + "\n", + "2. In the left sidebar, select **Inventory**.\n", + "\n", + "3. Select `Model` by clicking on **{Record} Inventory**, where `{Record}` is the currently active type of record. (Learn more: [Register records in the inventory](https://docs.validmind.ai/guide/inventory/register-records-in-inventory.html))\n", + "4. Click **+ Register Model**.\n", + "\n", + "5. Enter the model details and click **Next >** to continue to assignment of inventory record stakeholders.\n", + "\n", + "6. Select your own name under the **Record Owner** drop-down.\n", + "\n", + "7. Click **Register Model** to add the model to your inventory." + ] + }, + { + "cell_type": "markdown", + "id": "8337dbdf", + "metadata": {}, + "source": [ + "\n", + "\n", + "#### Create an empty document\n", + "\n", + "Once you've registered your model, let's create a document to hold your test results.\n", + "\n", + "1. In the left sidebar that appears for your model, click **Documents** and select **Development**.\n", + "\n", + " If you cannot locate your Development document, make sure Development type documents are enabled for model records and create a new document. (**Learn more:** [Manage documents](https://docs.validmind.ai/guide/templates/manage-documents.html#add-record-documents))\n", + "\n", + "2. Leave the document empty — **do not apply a template**.\n", + "\n", + "Unlike [the standard quickstart](https://docs.validmind.ai/notebooks/quickstart/quickstart_documentation.html), which relies on a template to define which tests run and where their results land, here we log each test result directly. Results logged this way are attached to the document even though no content blocks are registered for them, and you can insert them into the document later from the platform.\n" + ] + }, + { + "cell_type": "markdown", + "id": "43037f46", + "metadata": {}, + "source": [ + "\n", + "\n", + "#### Get your code snippet\n", + "\n", + "Initialize the ValidMind Library with the *code snippet* unique to each record per document, ensuring your test results are uploaded to the correct record and automatically populated in the right document in the ValidMind Platform when you run the library.\n", + "\n", + "1. On the left sidebar that appears for your model, select **Getting Started** and select `Development` from the **Document** drop-down menu.\n", + "\n", + "2. Click **Copy snippet to clipboard**.\n", + "\n", + "3. Next, [load your model identifier credentials from an `.env` file](https://docs.validmind.ai/developer/quickstart/store-credentials-in-env-file.html) or replace the placeholder with your own code snippet:\n", + "\n", + "If your organization authenticates with OAuth 2.0 / OIDC instead of API keys, see [Authenticate with OIDC device flow](https://docs.validmind.ai/developer/quickstart/authenticate-with-oidc-device-flow.html) or try the [OIDC device-flow quickstart notebook](https://docs.validmind.ai/notebooks/quickstart/quickstart_model_documentation_oidc_device_flow.html).\n" + ] + }, + { + "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", + " document=\"documentation\",\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "1a6933d3", + "metadata": {}, + "source": [ + "\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": "fafe8fc2", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Getting to know ValidMind" + ] + }, + { + "cell_type": "markdown", + "id": "fa0e43cb", + "metadata": {}, + "source": [ + "\n", + "\n", + "### View documentation in the ValidMind Platform\n", + "\n", + "Next, let's head to the ValidMind Platform to look at the document you created:\n", + "\n", + "1. In a browser, [log in to ValidMind](https://docs.validmind.ai/guide/access/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 **Development** under Documents for your model. The document is still empty, since no content blocks are registered. The test results you log later in this notebook are attached to it." + ] + }, + { + "cell_type": "markdown", + "id": "9d0d1005", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Working with ValidMind datasets" + ] + }, + { + "cell_type": "markdown", + "id": "1b94e39f", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Prepare the sample dataset" + ] + }, + { + "cell_type": "markdown", + "id": "6fc79fc1", + "metadata": {}, + "source": [ + "\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.\n", + "- To keep the notebook quick to run, we only use the first 500 rows. Remove `.head(500)` to work with the full dataset, as the [standard quickstart](https://docs.validmind.ai/notebooks/quickstart/quickstart_documentation.html) does." + ] + }, + { + "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().head(500)\n", + "raw_df.head()" + ] + }, + { + "cell_type": "markdown", + "id": "4fe0f216", + "metadata": {}, + "source": [ + "\n", + "\n", + "#### Preprocess 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": "9f690a04", + "metadata": {}, + "source": [ + "\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": "a9ad2104", + "metadata": {}, + "source": [ + "\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", + "id": "73d767d7", + "metadata": {}, + "source": [ + "\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", + "id": "0b33afca", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Working with ValidMind models" + ] + }, + { + "cell_type": "markdown", + "id": "5962362c", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Train 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": "33cafbcf", + "metadata": {}, + "source": [ + "\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", + "id": "47d84a80", + "metadata": {}, + "source": [ + "\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", + "id": "23bccb27", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Initialize the ValidMind model\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", + "- Despite the naming convention, ValidMind model objects can be any type of record you want to test, document, validate, or monitor with the ValidMind Library.\n", + "- From classical statistical and machine learning models, to generative and agentic AI systems and more, the ValidMind model object provides a consistent wrapper around your record so it can be passed as a unified input to any ValidMind test or test suite, with results sent directly to the ValidMind Platform.\n", + "\n", + "Initialize your 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", + "id": "20c008bf", + "metadata": {}, + "source": [ + "\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", + "id": "afc4f08f", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Run and log individual tests\n", + "\n", + "This is where it all comes together — you are now ready to **run tests one at a time and log their results**.\n", + "\n", + "- [`vm.tests.run_test()`](https://docs.validmind.ai/validmind/validmind/tests.html#run_test) runs a single test and returns a `TestResult` object. Nothing is sent to the ValidMind Platform at this point, so you can inspect the result and re-run the test with different inputs or parameters until you're happy with it.\n", + "- [`result.log()`](https://docs.validmind.ai/validmind/validmind/vm_models.html#log) then uploads that result to the document you initialized above.\n", + "\n", + "Since this document has no test-driven blocks telling the library which tests to run, you choose the tests yourself and name each one explicitly.\n", + "\n", + "To explore what's available, use [`vm.tests.list_tests()`](https://docs.validmind.ai/validmind/validmind/tests.html#list_tests). For example, the following lists tests whose ID, task or tags mention classification. A filter only narrows the list, so it won't necessarily include every test you run below. To learn how to search, filter and inspect tests in more detail, see [Explore tests](https://docs.validmind.ai/notebooks/how_to/tests/explore_tests/explore_tests.html).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2691caec", + "metadata": {}, + "outputs": [], + "source": [ + "vm.tests.list_tests(filter=\"classification\", pretty=True)" + ] + }, + { + "cell_type": "markdown", + "id": "e90af076", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Run and log a set of tests\n", + "\n", + "Since each test is just a function call, you can run and log several tests with a plain Python loop. The tests below cover data quality, descriptive statistics and correlations, model training, model evaluation, explainability and model diagnosis for our churn model. Each test gets the inputs that suit it:\n", + "\n", + "- Tests that only need a dataset use the raw dataset.\n", + "- Tests that need a model and a dataset use the test dataset.\n", + "- Tests that compare datasets use the training and test datasets.\n", + "- `ClassifierPerformance` runs twice, once on the training dataset and once on the test dataset. The `:in_sample` and `:out_of_sample` suffixes on the test ID keep the two results separate.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84bc39f1", + "metadata": {}, + "outputs": [], + "source": [ + "both = [vm_train_ds, vm_test_ds]\n", + "tests = {\n", + " # Data description\n", + " \"validmind.data_validation.DatasetDescription\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.ClassImbalance\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.Duplicates\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.HighCardinality\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.MissingValues\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.Skewness\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.UniqueRows\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.TooManyZeroValues\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.IQROutliersTable\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.IQROutliersBarPlot\": {\"dataset\": vm_raw_dataset},\n", + " # Descriptive statistics / correlations\n", + " \"validmind.data_validation.DescriptiveStatistics\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.PearsonCorrelationMatrix\": {\"dataset\": vm_raw_dataset},\n", + " \"validmind.data_validation.HighPearsonCorrelation\": {\"dataset\": vm_raw_dataset},\n", + " # Model training\n", + " \"validmind.model_validation.ModelMetadata\": {\"model\": vm_model},\n", + " \"validmind.data_validation.DatasetSplit\": {\"datasets\": both},\n", + " \"validmind.model_validation.sklearn.PopulationStabilityIndex\": {\"model\": vm_model, \"datasets\": both},\n", + " # Model evaluation\n", + " \"validmind.model_validation.sklearn.ConfusionMatrix\": {\"model\": vm_model, \"dataset\": vm_test_ds},\n", + " \"validmind.model_validation.sklearn.ClassifierPerformance:in_sample\": {\"model\": vm_model, \"dataset\": vm_train_ds},\n", + " \"validmind.model_validation.sklearn.ClassifierPerformance:out_of_sample\": {\"model\": vm_model, \"dataset\": vm_test_ds},\n", + " \"validmind.model_validation.sklearn.PrecisionRecallCurve\": {\"model\": vm_model, \"dataset\": vm_test_ds},\n", + " \"validmind.model_validation.sklearn.ROCCurve\": {\"model\": vm_model, \"dataset\": vm_test_ds},\n", + " \"validmind.model_validation.sklearn.TrainingTestDegradation\": {\"model\": vm_model, \"datasets\": both},\n", + " \"validmind.model_validation.sklearn.MinimumAccuracy\": {\"model\": vm_model, \"dataset\": vm_test_ds},\n", + " \"validmind.model_validation.sklearn.MinimumF1Score\": {\"model\": vm_model, \"dataset\": vm_test_ds},\n", + " \"validmind.model_validation.sklearn.MinimumROCAUCScore\": {\"model\": vm_model, \"dataset\": vm_test_ds},\n", + " # Explainability\n", + " \"validmind.model_validation.sklearn.PermutationFeatureImportance\": {\"model\": vm_model, \"dataset\": vm_test_ds},\n", + " \"validmind.model_validation.sklearn.SHAPGlobalImportance\": {\"model\": vm_model, \"dataset\": vm_test_ds},\n", + " # Model diagnosis\n", + " \"validmind.model_validation.sklearn.WeakspotsDiagnosis\": {\"model\": vm_model, \"datasets\": both},\n", + " \"validmind.model_validation.sklearn.OverfitDiagnosis\": {\"model\": vm_model, \"datasets\": both},\n", + " \"validmind.model_validation.sklearn.RobustnessDiagnosis\": {\"model\": vm_model, \"datasets\": both},\n", + "}\n", + "\n", + "for test_id, inputs in tests.items():\n", + " vm.tests.run_test(test_id, inputs=inputs).log()" + ] + }, + { + "cell_type": "markdown", + "id": "9a4cde04", + "metadata": {}, + "source": [ + "\n", + "\n", + "## In summary\n", + "\n", + "In this notebook, you learned how to:\n", + "\n", + "- [x] Register a record (model) within the ValidMind Platform\n", + "- [x] Install and initialize the ValidMind Library\n", + "- [x] Create an empty document with no content blocks registered\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 individual tests with `run_test()` and log each result with `result.log()`\n" + ] + }, + { + "cell_type": "markdown", + "id": "68803cd9", + "metadata": {}, + "source": [ + "\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 documentation." + ] + }, + { + "cell_type": "markdown", + "id": "ba38b729", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Work with your documentation\n", + "\n", + "1. From the **Inventory** in the ValidMind Platform, go to the model you registered earlier. (Learn more: [Working with the inventory](https://docs.validmind.ai/guide/inventory/working-with-the-inventory.html))\n", + "\n", + "2. In the left sidebar that appears for your model, click **Development** under Documents.\n", + "\n", + "What you see is the full draft of your documentation in a more easily consumable version. From here, you can make qualitative edits to documentation, view guidelines, collaborate with validators, and submit your documentation for approval when it's ready. (**Learn more:** [Working with documentation](https://docs.validmind.ai/guide/documentation/working-with-documentation.html))" + ] + }, + { + "cell_type": "markdown", + "id": "ae046dc4", + "metadata": {}, + "source": [ + "\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 development](https://docs.validmind.ai/developer/validmind-library.html#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 use the ValidMind Library to streamline your work:\n", + "\n", + "- [Run tests & test suites](https://docs.validmind.ai/developer/how-to/testing-overview.html)\n", + "- [Use ValidMind Library features](https://docs.validmind.ai/developer/how-to/feature-overview.html)\n", + "- [Code samples by use case](https://docs.validmind.ai/developer/samples-jupyter-notebooks.html)\n", + "\n", + "Or, visit our [documentation](https://docs.validmind.ai/) to learn more about ValidMind." + ] + }, + { + "cell_type": "markdown", + "id": "4ce38015", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Upgrade ValidMind\n", + "\n", + "
After installing ValidMind, you’ll want to periodically make sure you are on the latest version to access any new features and other enhancements.
\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": "f865e64e", + "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": "65b36aa7", + "metadata": {}, + "source": [ + "You may need to restart your kernel after running the upgrade package for changes to be applied." + ] + }, + { + "cell_type": "markdown", + "id": "copyright-bd87da591b88473997979690dbffcfa5", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n", + "\n", + "***\n", + "\n", + "Copyright © 2023-2026 ValidMind Inc. All rights reserved.
\n", + "Refer to [LICENSE](https://github.com/validmind/validmind-library/blob/main/LICENSE) for details.
\n", + "SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial
" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "ValidMind Library", + "language": "python", + "name": "validmind" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}