From 4a143f2eb9d32c4d9631efeb2e6f4051eb1e6c5e Mon Sep 17 00:00:00 2001 From: Juan Date: Thu, 2 Jan 2025 14:57:27 +0100 Subject: [PATCH 01/10] Add application scorecard with ml notebooks and new tests --- .../application_scorecard_full_suite.ipynb | 771 +++++++ .../application_scorecard_with_ml.ipynb | 1842 +++++++++++++++++ .../data_validation/test_UniqueRows.py | 9 +- .../datasets/credit_risk/lending_club.py | 458 +++- .../data_validation/MutualInformation.py | 129 ++ .../data_validation/ScoreBandDefaultRates.py | 135 ++ .../data_validation/TooManyZeroValues.py | 4 +- validmind/tests/data_validation/UniqueRows.py | 4 +- .../sklearn/CalibrationCurve.py | 116 ++ .../ClassifierThresholdOptimization.py | 257 +++ .../sklearn/HyperParametersTuning.py | 172 +- .../sklearn/ModelParameters.py | 74 + .../sklearn/ScoreProbabilityAlignment.py | 126 ++ validmind/utils.py | 30 +- 14 files changed, 4044 insertions(+), 83 deletions(-) create mode 100644 notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb create mode 100644 notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb create mode 100644 validmind/tests/data_validation/MutualInformation.py create mode 100644 validmind/tests/data_validation/ScoreBandDefaultRates.py create mode 100644 validmind/tests/model_validation/sklearn/CalibrationCurve.py create mode 100644 validmind/tests/model_validation/sklearn/ClassifierThresholdOptimization.py create mode 100644 validmind/tests/model_validation/sklearn/ModelParameters.py create mode 100644 validmind/tests/model_validation/sklearn/ScoreProbabilityAlignment.py diff --git a/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb b/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb new file mode 100644 index 000000000..ccfc69d86 --- /dev/null +++ b/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb @@ -0,0 +1,771 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Document an application scorecard model\n", + "\n", + "Build and document an *application scorecard model* with the ValidMind Library by using Kaggle's [Lending Club](https://www.kaggle.com/datasets/devanshi23/loan-data-2007-2014/data) sample dataset to build a simple application scorecard.\n", + "\n", + "An application scorecard model is a type of statistical model used in credit scoring to evaluate the creditworthiness of potential borrowers by generating a score based on various characteristics of an applicant — such as credit history, income, employment status, and other relevant financial data. \n", + "\n", + "- This score helps lenders make decisions about whether to approve or reject loan applications, as well as determine the terms of the loan, including interest rates and credit limits. \n", + "- Application scorecard models enable lenders to manage risk efficiently while making the loan application process faster and more transparent for applicants.\n", + "\n", + "This interactive notebook provides a step-by-step guide for loading a demo dataset, preprocessing the raw data, training a model for testing, setting up test inputs, initializing the required ValidMind objects, running the test, and then logging the results to ValidMind." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Contents \n", + "- [About ValidMind](#toc1_) \n", + " - [Before you begin](#toc1_1_) \n", + " - [New to ValidMind?](#toc1_2_) \n", + " - [Key concepts](#toc1_3_) \n", + "- [Install the ValidMind Library](#toc2_) \n", + "- [Initialize the ValidMind Library](#toc3_) \n", + " - [Get your code snippet](#toc3_1_) \n", + "- [Initialize the Python environment](#toc4_) \n", + " - [Preview the documentation template](#toc4_1_) \n", + "- [Load the sample dataset](#toc5_) \n", + " - [Prepocess the dataset](#toc5_1_) \n", + " - [Feature engineering](#toc5_2_) \n", + "- [Train the model](#toc6_) \n", + " - [Compute probabilities](#toc6_1_) \n", + " - [Compute binary predictions](#toc6_2_) \n", + " - [Compute scores](#toc6_3_) \n", + "- [Document the model](#toc7_) \n", + " - [Initialize the ValidMind datasets](#toc7_1_) \n", + " - [Initialize a model object](#toc7_2_) \n", + " - [Assign prediction values and probabilities to the datasets](#toc7_3_) \n", + " - [Assign scores to the datasets](#toc7_4_) \n", + " - [Data validation](#toc7_5_) \n", + " - [Run tests for raw data tests](#toc7_5_1_) \n", + " - [Run tests for preprocessed data](#toc7_5_2_) \n", + " - [Run tests for WoE analysis](#toc7_5_3_) \n", + " - [Model validation](#toc7_6_) \n", + " - [Run tests for model training](#toc7_6_1_) \n", + " - [Run tests for model evaluation](#toc7_6_2_) \n", + " - [Run tests for model explainability](#toc7_6_3_) \n", + "- [Next steps](#toc8_) \n", + " - [Work with your model documentation](#toc8_1_) \n", + " - [Discover more learning resources](#toc8_2_)\n", + "- [Upgrade ValidMind](#toc9_) \n", + "\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## About ValidMind\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.\n", + "\n", + "\n", + "\n", + "### Before you begin\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).\n", + "\n", + "\n", + "\n", + "### New to ValidMind?\n", + "If you haven't already seen our [Get started with the ValidMind Library](https://docs.validmind.ai/developer/get-started-validmind-library.html), we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models, find code samples, or read our developer reference.\n", + "\n", + "
For access to all features available in this notebook, create a free ValidMind account.\n", + "

\n", + "Signing up is FREE — Register with ValidMind
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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", + "**Custom tests**: Custom tests are functions that you define to evaluate your model or dataset. These functions can be registered via the ValidMind Library to be used with 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 test.\n", + "- **datasets**: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom test. See this [example](https://docs.validmind.ai/notebooks/how_to/run_tests_that_require_multiple_datasets.html) for more information.\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.\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", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Install the ValidMind Library\n", + "\n", + "To install the library:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%pip install -q -e ../../../../developer-framework" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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.\n", + "\n", + "\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 **Model 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:\n", + "\n", + " - Documentation template: `Credit Risk Scorecard`\n", + " - Use case: `Credit Risk - CECL`\n", + "\n", + " 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, + "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 = \"https://api.prod.validmind.ai/api/v1/tracking\",\n", + " api_key = \"...\",\n", + " api_secret = \"...\",\n", + " model = \"...\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Initialize the Python environment\n", + "\n", + "Next, let's import the necessary libraries and set up your Python environment for data analysis:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import xgboost as xgb\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "from validmind.datasets.credit_risk import lending_club\n", + "\n", + "%matplotlib inline" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Preview the documentation template\n", + "\n", + "A template predefines sections for your model documentation and provides a general outline to follow, making the documentation process much easier.\n", + "\n", + "You'll 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:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "vm.preview_template()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Load the sample dataset\n", + "\n", + "The sample dataset used here is provided by the ValidMind library. To be able to use it, you'll need to import the dataset and load it into a pandas [DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html), a two-dimensional tabular data structure that makes use of rows and columns:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "df = lending_club.load_data(source=\"offline\")\n", + "\n", + "df.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Prepocess the dataset\n", + "\n", + "In the preprocessing step we perform a number of operations to get ready for building our application scorecard. \n", + "\n", + "We use the `lending_club.preprocess` to simplify preprocessing. This function performs the following operations: \n", + "- Filters the dataset to include only loans for debt consolidation or credit card purposes\n", + "- Removes loans classified under the riskier grades \"F\" and \"G\"\n", + "- Excludes uncommon home ownership types and standardizes employment length and loan terms into numerical formats\n", + "- Discards unnecessary fields and any entries with missing information to maintain a clean and robust dataset for modeling" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "preprocess_df = lending_club.preprocess(df)\n", + "preprocess_df.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Feature engineering\n", + "\n", + "In the feature engineering phase, we apply specific transformations to optimize the dataset for predictive modeling in our application scorecard. \n", + "\n", + "Using the `ending_club.feature_engineering()` function, we conduct the following operations:\n", + "- **WoE encoding**: Converts both numerical and categorical features into Weight of Evidence (WoE) values. WoE is a statistical measure used in scorecard modeling that quantifies the relationship between a predictor variable and the binary target variable. It calculates the ratio of the distribution of good outcomes to the distribution of bad outcomes for each category or bin of a feature. This transformation helps to ensure that the features are predictive and consistent in their contribution to the model.\n", + "- **Integration of WoE bins**: Ensures that the WoE transformed values are integrated throughout the dataset, replacing the original feature values while excluding the target variable from this transformation. This transformation is used to maintain a consistent scale and impact of each variable within the model, which helps make the predictions more stable and accurate." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "fe_df = lending_club.feature_engineering(preprocess_df)\n", + "fe_df.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Train the model\n", + "\n", + "In this section, we focus on constructing and refining our predictive model. \n", + "- We begin by dividing our data, which is based on Weight of Evidence (WoE) features, into training and testing sets (`train_df`, `test_df`). \n", + "- With `lending_club.split`, we employ a simple random split, randomly allocating data points to each set to ensure a mix of examples in both." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Split the data\n", + "train_df, test_df = lending_club.split(fe_df, test_size=0.2)\n", + "\n", + "x_train = train_df.drop(lending_club.target_column, axis=1)\n", + "y_train = train_df[lending_club.target_column]\n", + "\n", + "x_test = test_df.drop(lending_club.target_column, axis=1)\n", + "y_test = test_df[lending_club.target_column]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Define the XGBoost model\n", + "xgb_model = xgb.XGBClassifier(\n", + " n_estimators=50, \n", + " random_state=42, \n", + " early_stopping_rounds=10\n", + ")\n", + "xgb_model.set_params(\n", + " eval_metric=[\"error\", \"logloss\", \"auc\"],\n", + ")\n", + "\n", + "# Fit the model\n", + "xgb_model.fit(\n", + " x_train, \n", + " y_train,\n", + " eval_set=[(x_test, y_test)],\n", + " verbose=False\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Define the Random Forest model\n", + "rf_model = RandomForestClassifier(\n", + " n_estimators=50, \n", + " random_state=42,\n", + ")\n", + "\n", + "# Fit the model\n", + "rf_model.fit(x_train, y_train)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Compute probabilities" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "train_xgb_prob = xgb_model.predict_proba(x_train)[:, 1]\n", + "test_xgb_prob = xgb_model.predict_proba(x_test)[:, 1]\n", + "\n", + "train_rf_prob = rf_model.predict_proba(x_train)[:, 1]\n", + "test_rf_prob = rf_model.predict_proba(x_test)[:, 1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Compute binary predictions" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "cut_off_threshold = 0.3\n", + "\n", + "train_xgb_binary_predictions = (train_xgb_prob > cut_off_threshold).astype(int)\n", + "test_xgb_binary_predictions = (test_xgb_prob > cut_off_threshold).astype(int)\n", + "\n", + "train_rf_binary_predictions = (train_rf_prob > cut_off_threshold).astype(int)\n", + "test_rf_binary_predictions = (test_rf_prob > cut_off_threshold).astype(int)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Document the model\n", + "\n", + "To document the model with the ValidMind Library, you'll need to:\n", + "1. Preprocess the raw dataset\n", + "2. Initialize some training and test datasets\n", + "3. Initialize a model object you can use for testing\n", + "4. Run the full suite of tests" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Initialize the ValidMind datasets\n", + "\n", + "Before you can run tests, 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.\n", + "\n", + "This function takes a number of arguments:\n", + "\n", + "- `dataset`: The 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", + "\n", + "With all datasets ready, you can now initialize the raw, processed, training and test datasets (`raw_df`, `preprocessed_df`, `fe_df`, `train_df` and `test_df`) created earlier into their own dataset objects using [`vm.init_dataset()`](https://docs.validmind.ai/validmind/validmind.html#init_dataset):" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "vm_raw_dataset = vm.init_dataset(\n", + " dataset=df,\n", + " input_id=\"raw_dataset\",\n", + " target_column=lending_club.target_column,\n", + ")\n", + "\n", + "vm_preprocess_dataset = vm.init_dataset(\n", + " dataset=preprocess_df,\n", + " input_id=\"preprocess_dataset\",\n", + " target_column=lending_club.target_column,\n", + ")\n", + "\n", + "vm_fe_dataset = vm.init_dataset(\n", + " dataset=fe_df,\n", + " input_id=\"fe_dataset\",\n", + " target_column=lending_club.target_column,\n", + ")\n", + "\n", + "vm_train_ds = vm.init_dataset(\n", + " dataset=train_df,\n", + " input_id=\"train_dataset\",\n", + " target_column=lending_club.target_column,\n", + ")\n", + "\n", + "vm_test_ds = vm.init_dataset(\n", + " dataset=test_df,\n", + " input_id=\"test_dataset\",\n", + " target_column=lending_club.target_column,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Initialize a model object\n", + "\n", + "You will also need to initialize a ValidMind model object (`vm_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()`](https://docs.validmind.ai/validmind/validmind.html#init_model):" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "vm_xgb_model = vm.init_model(\n", + " xgb_model,\n", + " input_id=\"xgb_model\",\n", + ")\n", + "\n", + "vm_rf_model = vm.init_model(\n", + " rf_model,\n", + " input_id=\"rf_model\",\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Assign prediction values and probabilities to the datasets\n", + "\n", + "With our model now trained, we'll move on to assigning both the predictive probabilities coming directly from the model's predictions, and the binary prediction after applying the cutoff threshold described in the previous steps. \n", + "- These tasks are achieved through the use of the `assign_predictions()` method associated with the VM `dataset` object.\n", + "- This method links the model's class prediction values and probabilities to our VM train and test datasets." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "# XGBoost\n", + "vm_train_ds.assign_predictions(\n", + " model=vm_xgb_model,\n", + " prediction_values=train_xgb_binary_predictions,\n", + " prediction_probabilities=train_xgb_prob,\n", + ")\n", + "\n", + "vm_test_ds.assign_predictions(\n", + " model=vm_xgb_model,\n", + " prediction_values=test_xgb_binary_predictions,\n", + " prediction_probabilities=test_xgb_prob,\n", + ")\n", + "\n", + "# Random Forest\n", + "vm_train_ds.assign_predictions(\n", + " model=vm_rf_model,\n", + " prediction_values=train_rf_binary_predictions,\n", + " prediction_probabilities=train_rf_prob,\n", + ")\n", + "\n", + "vm_test_ds.assign_predictions(\n", + " model=vm_rf_model,\n", + " prediction_values=test_rf_binary_predictions,\n", + " prediction_probabilities=test_rf_prob,\n", + ")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Compute credit risk scores\n", + "\n", + "In this phase, we translate model predictions into actionable scores using probability estimates generated by our trained model." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "train_xgb_scores = lending_club.compute_scores(train_xgb_prob)\n", + "test_xgb_scores = lending_club.compute_scores(test_xgb_prob)\n", + "\n", + "# Assign scores to the datasets\n", + "vm_train_ds.add_extra_column(\"xgb_scores\", train_xgb_scores)\n", + "vm_test_ds.add_extra_column(\"xgb_scores\", test_xgb_scores)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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. 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", + " \"\": {\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 `` 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, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " from validmind.utils import preview_test_config\n", + "\n", + " test_config = lending_club.get_demo_test_config(x_test, y_test)\n", + " preview_test_config(test_config)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we can pass the input configuration to `vm.run_documentation_tests()` and run the full suite of tests. The variable `full_suite` then holds the result of these tests." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "full_suite = vm.run_documentation_tests(config=test_config)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Next steps\n", + "\n", + "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.\n", + "\n", + "\n", + "\n", + "### Work with your model documentation\n", + "\n", + "1. In the ValidMind Platform, go to the **Documentation** page for the model you registered earlier. ([Need more help?](https://docs.validmind.ai/guide/model-documentation/working-with-model-documentation.html))\n", + "\n", + "2. Expand the following sections and take a look around:\n", + "\n", + " - **2. Data Preparation**\n", + " - **3. Model Development**\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 (hint: some of the tests in **2.3. Feature Selection and Engineering** look like they need some attention), view guidelines, collaborate with validators, and submit your model documentation for approval when it's ready.\n", + "\n", + "\n", + "\n", + "### Discover more learning resources\n", + "\n", + "We offer many interactive notebooks to help you document models:\n", + "\n", + "- [Run tests & test suites](https://docs.validmind.ai/developer/model-testing/testing-overview.html)\n", + "- [Code samples](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", + "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, + "metadata": {}, + "outputs": [], + "source": [ + "%pip show validmind" + ] + }, + { + "cell_type": "markdown", + "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", + "metadata": {}, + "source": [ + "You may need to restart your kernel after running the upgrade package for changes to be applied." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "validmind-eEL8LtKG-py3.10", + "language": "python", + "name": "python3" + }, + "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.10.13" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb b/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb new file mode 100644 index 000000000..6dbfee911 --- /dev/null +++ b/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb @@ -0,0 +1,1842 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Document an application scorecard model\n", + "\n", + "Build and document an *application scorecard model* with the ValidMind Library by using Kaggle's [Lending Club](https://www.kaggle.com/datasets/devanshi23/loan-data-2007-2014/data) sample dataset to build a simple application scorecard.\n", + "\n", + "An application scorecard model is a type of statistical model used in credit scoring to evaluate the creditworthiness of potential borrowers by generating a score based on various characteristics of an applicant — such as credit history, income, employment status, and other relevant financial data. \n", + "\n", + "- This score helps lenders make decisions about whether to approve or reject loan applications, as well as determine the terms of the loan, including interest rates and credit limits. \n", + "- Application scorecard models enable lenders to manage risk efficiently while making the loan application process faster and more transparent for applicants.\n", + "\n", + "This interactive notebook provides a step-by-step guide for loading a demo dataset, preprocessing the raw data, training a model for testing, setting up test inputs, initializing the required ValidMind objects, running the test, and then logging the results to ValidMind." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Contents \n", + "- [About ValidMind](#toc1_) \n", + " - [Before you begin](#toc1_1_) \n", + " - [New to ValidMind?](#toc1_2_) \n", + " - [Key concepts](#toc1_3_) \n", + "- [Install the ValidMind Library](#toc2_) \n", + "- [Initialize the ValidMind Library](#toc3_) \n", + " - [Get your code snippet](#toc3_1_) \n", + "- [Initialize the Python environment](#toc4_) \n", + " - [Preview the documentation template](#toc4_1_) \n", + "- [Load the sample dataset](#toc5_) \n", + " - [Prepocess the dataset](#toc5_1_) \n", + " - [Feature engineering](#toc5_2_) \n", + "- [Train the model](#toc6_) \n", + " - [Compute probabilities](#toc6_1_) \n", + " - [Compute binary predictions](#toc6_2_) \n", + " - [Compute scores](#toc6_3_) \n", + "- [Document the model](#toc7_) \n", + " - [Initialize the ValidMind datasets](#toc7_1_) \n", + " - [Initialize a model object](#toc7_2_) \n", + " - [Assign prediction values and probabilities to the datasets](#toc7_3_) \n", + " - [Assign scores to the datasets](#toc7_4_) \n", + " - [Data validation](#toc7_5_) \n", + " - [Run tests for raw data tests](#toc7_5_1_) \n", + " - [Run tests for preprocessed data](#toc7_5_2_) \n", + " - [Run tests for WoE analysis](#toc7_5_3_) \n", + " - [Model validation](#toc7_6_) \n", + " - [Run tests for model training](#toc7_6_1_) \n", + " - [Run tests for model evaluation](#toc7_6_2_) \n", + " - [Run tests for model explainability](#toc7_6_3_) \n", + "- [Next steps](#toc8_) \n", + " - [Work with your model documentation](#toc8_1_) \n", + " - [Discover more learning resources](#toc8_2_)\n", + "- [Upgrade ValidMind](#toc9_) \n", + "\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## About ValidMind\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.\n", + "\n", + "\n", + "\n", + "### Before you begin\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).\n", + "\n", + "\n", + "\n", + "### New to ValidMind?\n", + "If you haven't already seen our [Get started with the ValidMind Library](https://docs.validmind.ai/developer/get-started-validmind-library.html), we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models, find code samples, or read our developer reference.\n", + "\n", + "
For access to all features available in this notebook, create a free ValidMind account.\n", + "

\n", + "Signing up is FREE — Register with ValidMind
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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", + "**Custom tests**: Custom tests are functions that you define to evaluate your model or dataset. These functions can be registered via the ValidMind Library to be used with 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 test.\n", + "- **datasets**: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom test. See this [example](https://docs.validmind.ai/notebooks/how_to/run_tests_that_require_multiple_datasets.html) for more information.\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.\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", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Install the ValidMind Library\n", + "\n", + "To install the library:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%pip install -q -e ../../../../developer-framework" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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.\n", + "\n", + "\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 **Model 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:\n", + "\n", + " - Documentation template: `Credit Risk Scorecard`\n", + " - Use case: `Credit Risk - CECL`\n", + "\n", + " 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, + "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 = \"https://api.prod.validmind.ai/api/v1/tracking\",\n", + " api_key = \"...\",\n", + " api_secret = \"...\",\n", + " model = \"...\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Initialize the Python environment\n", + "\n", + "Next, let's import the necessary libraries and set up your Python environment for data analysis:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import xgboost as xgb\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "from validmind.tests import run_test\n", + "from validmind.datasets.credit_risk import lending_club\n", + "\n", + "%matplotlib inline" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Preview the documentation template\n", + "\n", + "A template predefines sections for your model documentation and provides a general outline to follow, making the documentation process much easier.\n", + "\n", + "You'll 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:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "vm.preview_template()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Load the sample dataset\n", + "\n", + "The sample dataset used here is provided by the ValidMind library. To be able to use it, you'll need to import the dataset and load it into a pandas [DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html), a two-dimensional tabular data structure that makes use of rows and columns:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "df = lending_club.load_data(source=\"offline\")\n", + "\n", + "df.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Prepocess the dataset\n", + "\n", + "In the preprocessing step we perform a number of operations to get ready for building our application scorecard. \n", + "\n", + "We use the `lending_club.preprocess` to simplify preprocessing. This function performs the following operations: \n", + "- Filters the dataset to include only loans for debt consolidation or credit card purposes\n", + "- Removes loans classified under the riskier grades \"F\" and \"G\"\n", + "- Excludes uncommon home ownership types and standardizes employment length and loan terms into numerical formats\n", + "- Discards unnecessary fields and any entries with missing information to maintain a clean and robust dataset for modeling" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "preprocess_df = lending_club.preprocess(df)\n", + "preprocess_df.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Feature engineering\n", + "\n", + "In the feature engineering phase, we apply specific transformations to optimize the dataset for predictive modeling in our application scorecard. \n", + "\n", + "Using the `ending_club.feature_engineering()` function, we conduct the following operations:\n", + "- **WoE encoding**: Converts both numerical and categorical features into Weight of Evidence (WoE) values. WoE is a statistical measure used in scorecard modeling that quantifies the relationship between a predictor variable and the binary target variable. It calculates the ratio of the distribution of good outcomes to the distribution of bad outcomes for each category or bin of a feature. This transformation helps to ensure that the features are predictive and consistent in their contribution to the model.\n", + "- **Integration of WoE bins**: Ensures that the WoE transformed values are integrated throughout the dataset, replacing the original feature values while excluding the target variable from this transformation. This transformation is used to maintain a consistent scale and impact of each variable within the model, which helps make the predictions more stable and accurate." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "fe_df = lending_club.feature_engineering(preprocess_df)\n", + "fe_df.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Train the model\n", + "\n", + "In this section, we focus on constructing and refining our predictive model. \n", + "- We begin by dividing our data, which is based on Weight of Evidence (WoE) features, into training and testing sets (`train_df`, `test_df`). \n", + "- With `lending_club.split`, we employ a simple random split, randomly allocating data points to each set to ensure a mix of examples in both." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Split the data\n", + "train_df, test_df = lending_club.split(fe_df, test_size=0.2)\n", + "\n", + "x_train = train_df.drop(lending_club.target_column, axis=1)\n", + "y_train = train_df[lending_club.target_column]\n", + "\n", + "x_test = test_df.drop(lending_club.target_column, axis=1)\n", + "y_test = test_df[lending_club.target_column]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Define the XGBoost model\n", + "xgb_model = xgb.XGBClassifier(\n", + " n_estimators=50, \n", + " random_state=42, \n", + " early_stopping_rounds=10\n", + ")\n", + "xgb_model.set_params(\n", + " eval_metric=[\"error\", \"logloss\", \"auc\"],\n", + ")\n", + "\n", + "# Fit the model\n", + "xgb_model.fit(\n", + " x_train, \n", + " y_train,\n", + " eval_set=[(x_test, y_test)],\n", + " verbose=False\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Define the Random Forest model\n", + "rf_model = RandomForestClassifier(\n", + " n_estimators=50, \n", + " random_state=42,\n", + ")\n", + "\n", + "# Fit the model\n", + "rf_model.fit(x_train, y_train)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Compute probabilities" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "train_xgb_prob = xgb_model.predict_proba(x_train)[:, 1]\n", + "test_xgb_prob = xgb_model.predict_proba(x_test)[:, 1]\n", + "\n", + "train_rf_prob = rf_model.predict_proba(x_train)[:, 1]\n", + "test_rf_prob = rf_model.predict_proba(x_test)[:, 1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Compute binary predictions" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "cut_off_threshold = 0.3\n", + "\n", + "train_xgb_binary_predictions = (train_xgb_prob > cut_off_threshold).astype(int)\n", + "test_xgb_binary_predictions = (test_xgb_prob > cut_off_threshold).astype(int)\n", + "\n", + "train_rf_binary_predictions = (train_rf_prob > cut_off_threshold).astype(int)\n", + "test_rf_binary_predictions = (test_rf_prob > cut_off_threshold).astype(int)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Document the model\n", + "\n", + "To document the model with the ValidMind Library, you'll need to:\n", + "1. Preprocess the raw dataset\n", + "2. Initialize some training and test datasets\n", + "3. Initialize a model object you can use for testing\n", + "4. Run the full suite of tests" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Initialize the ValidMind datasets\n", + "\n", + "Before you can run tests, 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.\n", + "\n", + "This function takes a number of arguments:\n", + "\n", + "- `dataset`: The 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", + "\n", + "With all datasets ready, you can now initialize the raw, processed, training and test datasets (`raw_df`, `preprocessed_df`, `fe_df`, `train_df` and `test_df`) created earlier into their own dataset objects using [`vm.init_dataset()`](https://docs.validmind.ai/validmind/validmind.html#init_dataset):" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "vm_raw_dataset = vm.init_dataset(\n", + " dataset=df,\n", + " input_id=\"raw_dataset\",\n", + " target_column=lending_club.target_column,\n", + ")\n", + "\n", + "vm_preprocess_dataset = vm.init_dataset(\n", + " dataset=preprocess_df,\n", + " input_id=\"preprocess_dataset\",\n", + " target_column=lending_club.target_column,\n", + ")\n", + "\n", + "vm_fe_dataset = vm.init_dataset(\n", + " dataset=fe_df,\n", + " input_id=\"fe_dataset\",\n", + " target_column=lending_club.target_column,\n", + ")\n", + "\n", + "vm_train_ds = vm.init_dataset(\n", + " dataset=train_df,\n", + " input_id=\"train_dataset\",\n", + " target_column=lending_club.target_column,\n", + ")\n", + "\n", + "vm_test_ds = vm.init_dataset(\n", + " dataset=test_df,\n", + " input_id=\"test_dataset\",\n", + " target_column=lending_club.target_column,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Initialize a model object\n", + "\n", + "You will also need to initialize a ValidMind model object (`vm_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()`](https://docs.validmind.ai/validmind/validmind.html#init_model):" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "vm_xgb_model = vm.init_model(\n", + " xgb_model,\n", + " input_id=\"xgb_model\",\n", + ")\n", + "\n", + "vm_rf_model = vm.init_model(\n", + " rf_model,\n", + " input_id=\"rf_model\",\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Assign prediction values and probabilities to the datasets\n", + "\n", + "With our model now trained, we'll move on to assigning both the predictive probabilities coming directly from the model's predictions, and the binary prediction after applying the cutoff threshold described in the previous steps. \n", + "- These tasks are achieved through the use of the `assign_predictions()` method associated with the VM `dataset` object.\n", + "- This method links the model's class prediction values and probabilities to our VM train and test datasets." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "# XGBoost\n", + "vm_train_ds.assign_predictions(\n", + " model=vm_xgb_model,\n", + " prediction_values=train_xgb_binary_predictions,\n", + " prediction_probabilities=train_xgb_prob,\n", + ")\n", + "\n", + "vm_test_ds.assign_predictions(\n", + " model=vm_xgb_model,\n", + " prediction_values=test_xgb_binary_predictions,\n", + " prediction_probabilities=test_xgb_prob,\n", + ")\n", + "\n", + "# Random Forest\n", + "vm_train_ds.assign_predictions(\n", + " model=vm_rf_model,\n", + " prediction_values=train_rf_binary_predictions,\n", + " prediction_probabilities=train_rf_prob,\n", + ")\n", + "\n", + "vm_test_ds.assign_predictions(\n", + " model=vm_rf_model,\n", + " prediction_values=test_rf_binary_predictions,\n", + " prediction_probabilities=test_rf_prob,\n", + ")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Compute credit risk scores\n", + "\n", + "In this phase, we translate model predictions into actionable scores using probability estimates generated by our trained model." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "train_xgb_scores = lending_club.compute_scores(train_xgb_prob)\n", + "test_xgb_scores = lending_club.compute_scores(test_xgb_prob)\n", + "\n", + "# Assign scores to the datasets\n", + "vm_train_ds.add_extra_column(\"xgb_scores\", train_xgb_scores)\n", + "vm_test_ds.add_extra_column(\"xgb_scores\", test_xgb_scores)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Raw data" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.DatasetDescription:raw_data\",\n", + " inputs={\n", + " \"dataset\": vm_raw_dataset,\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.DescriptiveStatistics:raw_data\",\n", + " inputs={\n", + " \"dataset\": vm_raw_dataset,\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.MissingValues:raw_data\",\n", + " inputs={\n", + " \"dataset\": vm_raw_dataset,\n", + " },\n", + " params={\n", + " \"min_threshold\": 1\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.ClassImbalance:raw_data\",\n", + " inputs={\n", + " \"dataset\": vm_raw_dataset,\n", + " },\n", + " params={\n", + " \"min_percent_threshold\": 10\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.Duplicates:raw_data\",\n", + " inputs={\n", + " \"dataset\": vm_raw_dataset,\n", + " },\n", + " params={\n", + " \"min_threshold\": 1\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.HighCardinality:raw_data\",\n", + " inputs={\n", + " \"dataset\": vm_raw_dataset,\n", + " },\n", + " params={\n", + " \"num_threshold\": 100,\n", + " \"percent_threshold\": 0.1,\n", + " \"threshold_type\": \"percent\"\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.Skewness:raw_data\",\n", + " inputs={\n", + " \"dataset\": vm_raw_dataset,\n", + " },\n", + " params={\n", + " \"max_threshold\": 1\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.UniqueRows:raw_data\",\n", + " inputs={\n", + " \"dataset\": vm_raw_dataset,\n", + " },\n", + " params={\n", + " \"min_percent_threshold\": 1\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.TooManyZeroValues:raw_data\",\n", + " inputs={\n", + " \"dataset\": vm_raw_dataset,\n", + " },\n", + " params={\n", + " \"max_percent_threshold\": 0.03\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.IQROutliersTable:raw_data\",\n", + " inputs={\n", + " \"dataset\": vm_raw_dataset,\n", + " },\n", + " params={\n", + " \"threshold\": 5\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Pre-processed data" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.DescriptiveStatistics:preprocessed_data\",\n", + " inputs={\n", + " \"dataset\": vm_preprocess_dataset,\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.TabularDescriptionTables:preprocessed_data\",\n", + " inputs={\n", + " \"dataset\": vm_preprocess_dataset\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.MissingValues:preprocessed_data\",\n", + " inputs={\n", + " \"dataset\": vm_preprocess_dataset,\n", + " },\n", + " params={\n", + " \"min_threshold\": 1\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.TabularNumericalHistograms:preprocessed_data\",\n", + " inputs={\n", + " \"dataset\": vm_preprocess_dataset\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.TabularCategoricalBarPlots:preprocessed_data\",\n", + " inputs={\n", + " \"dataset\": vm_preprocess_dataset\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.TargetRateBarPlots:preprocessed_data\",\n", + " inputs={\n", + " \"dataset\": vm_preprocess_dataset\n", + " },\n", + " params={\n", + " \"default_column\": lending_club.target_column,\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Development data" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.DescriptiveStatistics:development_data\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.TabularDescriptionTables:development_data\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.ClassImbalance:development_data\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " params={\n", + " \"min_percent_threshold\": 10\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.UniqueRows:development_data\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " params={\n", + " \"min_percent_threshold\": 1\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.TabularNumericalHistograms:development_data\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Feature selection" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.MutualInformation:development_data\",\n", + " input_grid ={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " params={\n", + " \"min_threshold\": 0.01,\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.PearsonCorrelationMatrix:development_data\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.HighPearsonCorrelation:development_data\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " params={\n", + " \"max_threshold\": 0.3,\n", + " \"top_n_correlations\": 10\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.WOEBinTable\",\n", + " input_grid={\n", + " \"dataset\": [vm_preprocess_dataset]\n", + " },\n", + " params={\n", + " \"breaks_adj\": lending_club.breaks_adj,\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.WOEBinPlots\",\n", + " input_grid={\n", + " \"dataset\": [vm_preprocess_dataset]\n", + " },\n", + " params={\n", + " \"breaks_adj\": lending_club.breaks_adj,\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Model training" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.DatasetSplit\",\n", + " inputs={\n", + " \"datasets\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.ModelMetadata\",\n", + " input_grid={\n", + " \"model\": [vm_xgb_model, vm_rf_model],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.ModelParameters\",\n", + " input_grid={\n", + " \"model\": [vm_xgb_model, vm_rf_model],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Model selection" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.statsmodels.GINITable\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model, vm_rf_model],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.ClassifierPerformance\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model, vm_rf_model],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.TrainingTestDegradation:XGBoost\",\n", + " inputs={\n", + " \"datasets\": [vm_train_ds, vm_test_ds],\n", + " \"model\": vm_xgb_model,\n", + " },\n", + " params={\n", + " \"max_threshold\": 0.1\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.TrainingTestDegradation:RandomForest\",\n", + " inputs={\n", + " \"datasets\": [vm_train_ds, vm_test_ds],\n", + " \"model\": vm_rf_model,\n", + " },\n", + " params={\n", + " \"max_threshold\": 0.1\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " # Run the test\n", + " result = run_test(\n", + " \"validmind.model_validation.sklearn.HyperParametersTuning\",\n", + " inputs={\n", + " \"model\": vm_xgb_model,\n", + " \"dataset\": vm_train_ds,\n", + " },\n", + " params={\n", + " \"param_grid\": {'n_estimators': [50, 100]},\n", + " \"scoring\": ['roc_auc', 'recall'],\n", + " \"fit_params\": {'eval_set': [(x_test, y_test)], 'verbose': False},\n", + " \"thresholds\": [0.3, 0.5],\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Class discrimination" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.ROCCurve\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.MinimumROCAUCScore\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model],\n", + " },\n", + " params={\n", + " \"min_threshold\": 0.5\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.statsmodels.PredictionProbabilitiesHistogram\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.statsmodels.CumulativePredictionProbabilities\",\n", + " input_grid={\n", + " \"model\": [vm_xgb_model],\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.PopulationStabilityIndex\",\n", + " inputs={\n", + " \"datasets\": [vm_train_ds, vm_test_ds],\n", + " \"model\": vm_xgb_model,\n", + " },\n", + " params={\n", + " \"num_bins\": 10,\n", + " \"mode\": \"fixed\"\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Classification accuracy" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.ClassifierThresholdOptimization\",\n", + " inputs={\n", + " \"dataset\": vm_train_ds,\n", + " \"model\": vm_xgb_model\n", + " },\n", + " params={\n", + " \"target_recall\": 0.8 # Find a threshold that achieves a recall of 80%\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.CalibrationCurve\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.ConfusionMatrix\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.MinimumAccuracy\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model],\n", + " },\n", + " params={\n", + " \"min_threshold\": 0.7\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.MinimumF1Score\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model],\n", + " },\n", + " params={\n", + " \"min_threshold\": 0.5\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.PrecisionRecallCurve\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model]\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Model diagnosis" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.WeakspotsDiagnosis\",\n", + " inputs={\n", + " \"datasets\": [vm_train_ds, vm_test_ds],\n", + " \"model\": vm_xgb_model,\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.OverfitDiagnosis\",\n", + " inputs={\n", + " \"model\": vm_xgb_model,\n", + " \"datasets\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " params={\n", + " \"cut_off_threshold\": 0.04\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.RobustnessDiagnosis\",\n", + " inputs={\n", + " \"datasets\": [vm_train_ds, vm_test_ds],\n", + " \"model\": vm_xgb_model,\n", + " },\n", + " params={\n", + " \"scaling_factor_std_dev_list\": [\n", + " 0.1,\n", + " 0.2,\n", + " 0.3,\n", + " 0.4,\n", + " 0.5\n", + " ],\n", + " \"performance_decay_threshold\": 0.05\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Model explainability" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.PermutationFeatureImportance\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " \"model\": [vm_xgb_model]\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.FeaturesAUC\",\n", + " input_grid={\n", + " \"model\": [vm_xgb_model],\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.SHAPGlobalImportance\",\n", + " input_grid={\n", + " \"model\": [vm_xgb_model],\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " params={\n", + " \"kernel_explainer_samples\": 10,\n", + " \"tree_or_linear_explainer_samples\": 200,\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Scoring evaluation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.statsmodels.ScorecardHistogram\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds, vm_test_ds],\n", + " },\n", + " params={\n", + " \"score_column\": \"xgb_scores\",\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.data_validation.ScoreBandDefaultRates\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds],\n", + " \"model\": [vm_xgb_model],\n", + " },\n", + " params = {\n", + " \"score_column\": \"xgb_scores\",\n", + " \"score_bands\": [500, 540, 570]\n", + " }\n", + " ).log()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run=True\n", + "if run:\n", + "\n", + " run_test(\n", + " \"validmind.model_validation.sklearn.ScoreProbabilityAlignment\",\n", + " input_grid={\n", + " \"dataset\": [vm_train_ds],\n", + " \"model\": [vm_xgb_model],\n", + " },\n", + " params={\n", + " \"score_column\": \"xgb_scores\",\n", + " },\n", + " ).log()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "## Next steps\n", + "\n", + "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.\n", + "\n", + "\n", + "\n", + "### Work with your model documentation\n", + "\n", + "1. In the ValidMind Platform, go to the **Documentation** page for the model you registered earlier. ([Need more help?](https://docs.validmind.ai/guide/model-documentation/working-with-model-documentation.html))\n", + "\n", + "2. Expand the following sections and take a look around:\n", + "\n", + " - **2. Data Preparation**\n", + " - **3. Model Development**\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 (hint: some of the tests in **2.3. Feature Selection and Engineering** look like they need some attention), view guidelines, collaborate with validators, and submit your model documentation for approval when it's ready.\n", + "\n", + "\n", + "\n", + "### Discover more learning resources\n", + "\n", + "We offer many interactive notebooks to help you document models:\n", + "\n", + "- [Run tests & test suites](https://docs.validmind.ai/developer/model-testing/testing-overview.html)\n", + "- [Code samples](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", + "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, + "metadata": {}, + "outputs": [], + "source": [ + "%pip show validmind" + ] + }, + { + "cell_type": "markdown", + "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", + "metadata": {}, + "source": [ + "You may need to restart your kernel after running the upgrade package for changes to be applied." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "validmind-eEL8LtKG-py3.10", + "language": "python", + "name": "python3" + }, + "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.10.13" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/tests/unit_tests/data_validation/test_UniqueRows.py b/tests/unit_tests/data_validation/test_UniqueRows.py index 9f62a6d6c..0a3affe3b 100644 --- a/tests/unit_tests/data_validation/test_UniqueRows.py +++ b/tests/unit_tests/data_validation/test_UniqueRows.py @@ -55,7 +55,10 @@ def test_unique_rows_default_threshold(self): def test_low_uniqueness(self): # Test dataset with low uniqueness - results, passed = UniqueRows(self.vm_dataset_duplicates) + # Set threshold to 5% to make the test fail + results, passed = UniqueRows( + self.vm_dataset_duplicates, min_percent_threshold=5 + ) # Check return types self.assertIsInstance(results, list) @@ -68,6 +71,6 @@ def test_low_uniqueness(self): self.assertIn("Percentage of Unique Values (%)", result) self.assertIn("Pass/Fail", result) - # Should fail with low uniqueness + # Should fail with uniqueness below 5% self.assertFalse(passed) - self.assertTrue(any(row["Pass/Fail"] == "Fail" for row in results)) + self.assertTrue(all(row["Pass/Fail"] == "Fail" for row in results)) diff --git a/validmind/datasets/credit_risk/lending_club.py b/validmind/datasets/credit_risk/lending_club.py index 24413f5b6..133ea0702 100644 --- a/validmind/datasets/credit_risk/lending_club.py +++ b/validmind/datasets/credit_risk/lending_club.py @@ -355,33 +355,76 @@ def _woebin(df): return bins_df -def split(df, add_constant=False): +def split(df, validation_size=None, test_size=0.2, add_constant=False): + """ + Split dataset into train, validation (optional), and test sets. + + Args: + df: Input DataFrame + validation_split: If None, returns train/test split. If float, returns train/val/test split + test_size: Proportion of data for test set (default: 0.2) + add_constant: Whether to add constant column for statsmodels (default: False) + + Returns: + If validation_size is None: + train_df, test_df + If validation_size is float: + train_df, validation_df, test_df + """ df = df.copy() - # Splitting the dataset into training and test sets - train_df, test_df = train_test_split(df, test_size=0.2, random_state=42) + # First split off the test set + train_val_df, test_df = train_test_split(df, test_size=test_size, random_state=42) if add_constant: - # Add a constant to the model for both training and testing datasets - train_df = sm.add_constant(train_df) test_df = sm.add_constant(test_df) - # Calculate and print details for the training dataset - print("After splitting the dataset into training and test sets:") - print( - f"Training Dataset:\nRows: {train_df.shape[0]}\nColumns: {train_df.shape[1]}\nMissing values: {train_df.isnull().sum().sum()}\n" + if validation_size is None: + if add_constant: + train_val_df = sm.add_constant(train_val_df) + + # Print details for two-way split + print("After splitting the dataset into training and test sets:") + print( + f"Training Dataset:\nRows: {train_val_df.shape[0]}\nColumns: {train_val_df.shape[1]}\n" + f"Missing values: {train_val_df.isnull().sum().sum()}\n" + ) + print( + f"Test Dataset:\nRows: {test_df.shape[0]}\nColumns: {test_df.shape[1]}\n" + f"Missing values: {test_df.isnull().sum().sum()}\n" + ) + + return train_val_df, test_df + + # Calculate validation size as proportion of remaining data + val_size = validation_size / (1 - test_size) + train_df, validation_df = train_test_split( + train_val_df, test_size=val_size, random_state=42 ) - # Calculate and print details for the test dataset + if add_constant: + train_df = sm.add_constant(train_df) + validation_df = sm.add_constant(validation_df) + + # Print details for three-way split + print("After splitting the dataset into training, validation, and test sets:") print( - f"Test Dataset:\nRows: {test_df.shape[0]}\nColumns: {test_df.shape[1]}\nMissing values: {test_df.isnull().sum().sum()}\n" + f"Training Dataset:\nRows: {train_df.shape[0]}\nColumns: {train_df.shape[1]}\n" + f"Missing values: {train_df.isnull().sum().sum()}\n" + ) + print( + f"Validation Dataset:\nRows: {validation_df.shape[0]}\nColumns: {validation_df.shape[1]}\n" + f"Missing values: {validation_df.isnull().sum().sum()}\n" + ) + print( + f"Test Dataset:\nRows: {test_df.shape[0]}\nColumns: {test_df.shape[1]}\n" + f"Missing values: {test_df.isnull().sum().sum()}\n" ) - return train_df, test_df + return train_df, validation_df, test_df def compute_scores(probabilities): - target_score = score_params["target_score"] target_odds = score_params["target_odds"] pdo = score_params["pdo"] @@ -389,6 +432,393 @@ def compute_scores(probabilities): factor = pdo / np.log(2) offset = target_score - (factor * np.log(target_odds)) - scores = offset + factor * np.log(probabilities / (1 - probabilities)) + # Add negative sign to reverse the relationship + scores = offset - factor * np.log(probabilities / (1 - probabilities)) return scores + + +def get_demo_test_config(x_test=None, y_test=None): + """Get demo test configuration. + + Args: + x_test: Test features DataFrame + y_test: Test target Series + + Returns: + dict: Test configuration dictionary + """ + default_config = {} + + # RAW DATA TESTS + default_config["validmind.data_validation.DatasetDescription:raw_data"] = { + "inputs": { + "dataset": "raw_dataset", + } + } + default_config["validmind.data_validation.DescriptiveStatistics:raw_data"] = { + "inputs": { + "dataset": "raw_dataset", + } + } + default_config["validmind.data_validation.MissingValues:raw_data"] = { + "inputs": { + "dataset": "raw_dataset", + }, + "params": {"min_threshold": 1}, + } + default_config["validmind.data_validation.ClassImbalance:raw_data"] = { + "inputs": { + "dataset": "raw_dataset", + }, + "params": {"min_percent_threshold": 10}, + } + default_config["validmind.data_validation.Duplicates:raw_data"] = { + "inputs": { + "dataset": "raw_dataset", + }, + "params": {"min_threshold": 1}, + } + default_config["validmind.data_validation.HighCardinality:raw_data"] = { + "inputs": { + "dataset": "raw_dataset", + }, + "params": { + "num_threshold": 100, + "percent_threshold": 0.1, + "threshold_type": "percent", + }, + } + default_config["validmind.data_validation.Skewness:raw_data"] = { + "inputs": { + "dataset": "raw_dataset", + }, + "params": {"max_threshold": 1}, + } + default_config["validmind.data_validation.UniqueRows:raw_data"] = { + "inputs": { + "dataset": "raw_dataset", + }, + "params": {"min_percent_threshold": 1}, + } + default_config["validmind.data_validation.TooManyZeroValues:raw_data"] = { + "inputs": { + "dataset": "raw_dataset", + }, + "params": {"max_percent_threshold": 0.03}, + } + default_config["validmind.data_validation.IQROutliersTable:raw_data"] = { + "inputs": { + "dataset": "raw_dataset", + }, + "params": {"threshold": 5}, + } + + # PREPROCESSED DATA TESTS + default_config[ + "validmind.data_validation.DescriptiveStatistics:preprocessed_data" + ] = { + "inputs": { + "dataset": "preprocess_dataset", + } + } + default_config[ + "validmind.data_validation.TabularDescriptionTables:preprocessed_data" + ] = { + "inputs": { + "dataset": "preprocess_dataset", + } + } + default_config["validmind.data_validation.MissingValues:preprocessed_data"] = { + "inputs": { + "dataset": "preprocess_dataset", + }, + "params": {"min_threshold": 1}, + } + default_config[ + "validmind.data_validation.TabularNumericalHistograms:preprocessed_data" + ] = { + "inputs": { + "dataset": "preprocess_dataset", + } + } + default_config[ + "validmind.data_validation.TabularCategoricalBarPlots:preprocessed_data" + ] = { + "inputs": { + "dataset": "preprocess_dataset", + } + } + default_config["validmind.data_validation.TargetRateBarPlots:preprocessed_data"] = { + "inputs": { + "dataset": "preprocess_dataset", + }, + "params": {"default_column": "loan_status"}, + } + + # DEVELOPMENT DATA TESTS + default_config[ + "validmind.data_validation.DescriptiveStatistics:development_data" + ] = {"input_grid": {"dataset": ["train_dataset", "test_dataset"]}} + + default_config[ + "validmind.data_validation.TabularDescriptionTables:development_data" + ] = {"input_grid": {"dataset": ["train_dataset", "test_dataset"]}} + + default_config["validmind.data_validation.ClassImbalance:development_data"] = { + "input_grid": {"dataset": ["train_dataset", "test_dataset"]}, + "params": {"min_percent_threshold": 10}, + } + + default_config["validmind.data_validation.UniqueRows:development_data"] = { + "input_grid": {"dataset": ["train_dataset", "test_dataset"]}, + "params": {"min_percent_threshold": 1}, + } + + default_config[ + "validmind.data_validation.TabularNumericalHistograms:development_data" + ] = {"input_grid": {"dataset": ["train_dataset", "test_dataset"]}} + + # FEATURE SELECTION TESTS + default_config["validmind.data_validation.MutualInformation:development_data"] = { + "input_grid": {"dataset": ["train_dataset", "test_dataset"]}, + "params": {"min_threshold": 0.01}, + } + + default_config[ + "validmind.data_validation.PearsonCorrelationMatrix:development_data" + ] = {"input_grid": {"dataset": ["train_dataset", "test_dataset"]}} + + default_config[ + "validmind.data_validation.HighPearsonCorrelation:development_data" + ] = { + "input_grid": {"dataset": ["train_dataset", "test_dataset"]}, + "params": {"max_threshold": 0.3, "top_n_correlations": 10}, + } + + default_config["validmind.data_validation.WOEBinTable"] = { + "input_grid": {"dataset": ["preprocess_dataset"]}, + "params": {"breaks_adj": breaks_adj}, + } + + default_config["validmind.data_validation.WOEBinPlots"] = { + "input_grid": {"dataset": ["preprocess_dataset"]}, + "params": {"breaks_adj": breaks_adj}, + } + + # MODEL TRAINING TESTS + default_config["validmind.data_validation.DatasetSplit"] = { + "inputs": {"datasets": ["train_dataset", "test_dataset"]} + } + + default_config["validmind.model_validation.ModelMetadata"] = { + "input_grid": {"model": ["xgb_model", "rf_model"]} + } + + default_config["validmind.model_validation.sklearn.ModelParameters"] = { + "input_grid": {"model": ["xgb_model", "rf_model"]} + } + + # MODEL SELECTION TESTS + default_config["validmind.model_validation.statsmodels.GINITable"] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model", "rf_model"], + } + } + + default_config["validmind.model_validation.sklearn.ClassifierPerformance"] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model", "rf_model"], + } + } + + default_config[ + "validmind.model_validation.sklearn.TrainingTestDegradation:XGBoost" + ] = { + "inputs": {"datasets": ["train_dataset", "test_dataset"], "model": "xgb_model"}, + "params": {"max_threshold": 0.1}, + } + + default_config[ + "validmind.model_validation.sklearn.TrainingTestDegradation:RandomForest" + ] = { + "inputs": {"datasets": ["train_dataset", "test_dataset"], "model": "rf_model"}, + "params": {"max_threshold": 0.1}, + } + + default_config["validmind.model_validation.sklearn.HyperParametersTuning"] = { + "inputs": {"model": "xgb_model", "dataset": "train_dataset"}, + "params": { + "param_grid": {"n_estimators": [50, 100]}, + "scoring": ["roc_auc", "recall"], + "fit_params": { + "eval_set": [(x_test, y_test)], + "verbose": False, + }, + "thresholds": [0.3, 0.5], + }, + } + + # MODEL PERFORMANCE - DISCRIMINATION TESTS + default_config["validmind.model_validation.sklearn.ROCCurve"] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model"], + } + } + + default_config["validmind.model_validation.sklearn.MinimumROCAUCScore"] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model"], + }, + "params": {"min_threshold": 0.5}, + } + + default_config[ + "validmind.model_validation.statsmodels.PredictionProbabilitiesHistogram" + ] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model"], + } + } + + default_config[ + "validmind.model_validation.statsmodels.CumulativePredictionProbabilities" + ] = { + "input_grid": { + "model": ["xgb_model"], + "dataset": ["train_dataset", "test_dataset"], + } + } + + default_config["validmind.model_validation.sklearn.PopulationStabilityIndex"] = { + "inputs": {"datasets": ["train_dataset", "test_dataset"], "model": "xgb_model"}, + "params": {"num_bins": 10, "mode": "fixed"}, + } + + # MODEL PERFORMANCE - ACCURACY TESTS + default_config["validmind.model_validation.sklearn.ConfusionMatrix"] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model"], + } + } + + default_config["validmind.model_validation.sklearn.MinimumAccuracy"] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model"], + }, + "params": {"min_threshold": 0.7}, + } + + default_config["validmind.model_validation.sklearn.MinimumF1Score"] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model"], + }, + "params": {"min_threshold": 0.5}, + } + + default_config["validmind.model_validation.sklearn.PrecisionRecallCurve"] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model"], + } + } + + default_config["validmind.model_validation.sklearn.CalibrationCurve"] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model"], + } + } + + default_config[ + "validmind.model_validation.sklearn.ClassifierThresholdOptimization" + ] = { + "inputs": {"dataset": "train_dataset", "model": "xgb_model"}, + "params": { + "target_recall": 0.8 # Find a threshold that achieves a recall of 80% + }, + } + + # MODEL PERFORMANCE - SCORING TESTS + default_config["validmind.model_validation.statsmodels.ScorecardHistogram"] = { + "input_grid": {"dataset": ["train_dataset", "test_dataset"]}, + "params": {"score_column": "xgb_scores"}, + } + + default_config["validmind.data_validation.ScoreBandDefaultRates"] = { + "input_grid": {"dataset": ["train_dataset"], "model": ["xgb_model"]}, + "params": { + "score_column": "xgb_scores", + "score_bands": [504, 537, 570], # Creates four score bands + }, + } + + default_config["validmind.model_validation.sklearn.ScoreProbabilityAlignment"] = { + "input_grid": {"dataset": ["train_dataset"], "model": ["xgb_model"]}, + "params": {"score_column": "xgb_scores"}, + } + + # MODEL DIAGNOSIS TESTS + default_config["validmind.model_validation.sklearn.WeakspotsDiagnosis"] = { + "inputs": { + "datasets": ["train_dataset", "test_dataset"], + "model": "xgb_model", + }, + } + + default_config["validmind.model_validation.sklearn.OverfitDiagnosis"] = { + "inputs": { + "model": "xgb_model", + "datasets": ["train_dataset", "test_dataset"], + }, + "params": {"cut_off_threshold": 0.04}, + } + + default_config["validmind.model_validation.sklearn.RobustnessDiagnosis"] = { + "inputs": { + "datasets": ["train_dataset", "test_dataset"], + "model": "xgb_model", + }, + "params": { + "scaling_factor_std_dev_list": [0.1, 0.2, 0.3, 0.4, 0.5], + "performance_decay_threshold": 0.05, + }, + } + + # EXPLAINABILITY TESTS + default_config[ + "validmind.model_validation.sklearn.PermutationFeatureImportance" + ] = { + "input_grid": { + "dataset": ["train_dataset", "test_dataset"], + "model": ["xgb_model"], + } + } + + default_config["validmind.model_validation.FeaturesAUC"] = { + "input_grid": { + "model": ["xgb_model"], + "dataset": ["train_dataset", "test_dataset"], + }, + } + + default_config["validmind.model_validation.sklearn.SHAPGlobalImportance"] = { + "input_grid": { + "model": ["xgb_model"], + "dataset": ["train_dataset", "test_dataset"], + }, + "params": { + "kernel_explainer_samples": 10, + "tree_or_linear_explainer_samples": 200, + }, + } + + return default_config diff --git a/validmind/tests/data_validation/MutualInformation.py b/validmind/tests/data_validation/MutualInformation.py new file mode 100644 index 000000000..6358a5c1b --- /dev/null +++ b/validmind/tests/data_validation/MutualInformation.py @@ -0,0 +1,129 @@ +# Copyright © 2023-2024 ValidMind Inc. All rights reserved. +# See the LICENSE file in the root of this repository for details. +# SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial + +import plotly.graph_objects as go +from sklearn.feature_selection import mutual_info_classif, mutual_info_regression +from validmind import tags, tasks +from validmind.vm_models import VMDataset +from validmind.vm_models.result import RawData + + +@tags("feature_selection", "data_analysis") +@tasks("classification", "regression") +def MutualInformation( + dataset: VMDataset, min_threshold: float = 0.01, task: str = "classification" +): + """ + Calculates mutual information scores between features and target variable to evaluate feature relevance. + + ### Purpose + + The Mutual Information test quantifies the predictive power of each feature by measuring its statistical + dependency with the target variable. This helps identify relevant features for model training and + detect potential redundant or irrelevant variables, supporting feature selection decisions and model + interpretability. + + ### Test Mechanism + + The test employs sklearn's mutual_info_classif/mutual_info_regression functions to compute mutual + information between each feature and the target. It produces a normalized score (0 to 1) for each + feature, where higher scores indicate stronger relationships. Results are presented in both tabular + format and visualized through a bar plot with a configurable threshold line. + + ### Signs of High Risk + + - Many features showing very low mutual information scores + - Key business features exhibiting unexpectedly low scores + - All features showing similar, low information content + - Large discrepancy between business importance and MI scores + - Highly skewed distribution of MI scores + - Critical features below the minimum threshold + - Unexpected zero or near-zero scores for known important features + - Inconsistent scores across different data samples + + ### Strengths + + - Captures non-linear relationships between features and target + - Scale-invariant measurement of feature relevance + - Works for both classification and regression tasks + - Provides interpretable scores (0 to 1 scale) + - Supports automated feature selection + - No assumptions about data distribution + - Handles numerical and categorical features + - Computationally efficient for most datasets + + ### Limitations + + - Requires sufficient data for reliable estimates + - May be computationally intensive for very large datasets + - Cannot detect redundant features (pairwise relationships) + - Sensitive to feature discretization for continuous variables + - Does not account for feature interactions + - May underestimate importance of rare but crucial events + - Cannot handle missing values directly + - May be affected by extreme class imbalance + """ + if task not in ["classification", "regression"]: + raise ValueError("task must be either 'classification' or 'regression'") + + X = dataset.x + y = dataset.y + + # Select appropriate MI function based on task type + if task == "classification": + mi_scores = mutual_info_classif(X, y) + else: + mi_scores = mutual_info_regression(X, y) + + # Create DataFrame for raw data + raw_data = RawData( + feature=dataset.feature_columns, + mutual_information_score=mi_scores.tolist(), + pass_fail=["Pass" if score >= min_threshold else "Fail" for score in mi_scores], + ) + + # Create Plotly figure + fig = go.Figure() + + # Sort data for better visualization + sorted_indices = sorted( + range(len(mi_scores)), key=lambda k: mi_scores[k], reverse=True + ) + sorted_features = [dataset.feature_columns[i] for i in sorted_indices] + sorted_scores = [mi_scores[i] for i in sorted_indices] + + # Add bar plot + fig.add_trace( + go.Bar( + x=sorted_features, + y=sorted_scores, + marker_color=[ + "blue" if score >= min_threshold else "red" for score in sorted_scores + ], + name="Mutual Information Score", + ) + ) + + # Add threshold line + fig.add_hline( + y=min_threshold, + line_dash="dash", + line_color="gray", + annotation_text=f"Threshold ({min_threshold})", + annotation_position="right", + ) + + # Update layout + fig.update_layout( + title="Mutual Information Scores by Feature", + xaxis_title="Features", + yaxis_title="Mutual Information Score", + xaxis_tickangle=-45, + showlegend=False, + width=1000, + height=600, + template="plotly_white", + ) + + return raw_data, fig diff --git a/validmind/tests/data_validation/ScoreBandDefaultRates.py b/validmind/tests/data_validation/ScoreBandDefaultRates.py new file mode 100644 index 000000000..9056295e3 --- /dev/null +++ b/validmind/tests/data_validation/ScoreBandDefaultRates.py @@ -0,0 +1,135 @@ +import pandas as pd +import numpy as np +from validmind import tags, tasks +from validmind.vm_models import VMDataset, VMModel + + +@tags("visualization", "credit_risk", "scorecard") +@tasks("classification") +def ScoreBandDefaultRates( + dataset: VMDataset, + model: VMModel, + score_column: str = "score", + score_bands: list = None, +): + """ + Analyzes default rates and population distribution across credit score bands. + + ### Purpose + + The Score Band Default Rates test evaluates the discriminatory power of credit scores by analyzing + default rates across different score bands. This helps validate score effectiveness, supports + policy decisions, and provides insights into portfolio risk distribution. + + ### Test Mechanism + + The test segments the score distribution into bands and calculates key metrics for each band: + 1. Population count and percentage in each band + 2. Default rate within each band + 3. Cumulative statistics across bands + The results show how well the scores separate good and bad accounts. + + ### Signs of High Risk + + - Non-monotonic default rates across score bands + - Insufficient population in critical score bands + - Unexpected default rates for score ranges + - High concentration in specific score bands + - Similar default rates across adjacent bands + - Unstable default rates in key decision bands + - Extreme population skewness + - Poor risk separation between bands + + ### Strengths + + - Clear view of score effectiveness + - Supports policy threshold decisions + - Easy to interpret and communicate + - Directly links to business decisions + - Shows risk segmentation power + - Identifies potential score issues + - Helps validate scoring model + - Supports portfolio monitoring + + ### Limitations + + - Sensitive to band definition choices + - May mask within-band variations + - Requires sufficient data in each band + - Cannot capture non-linear patterns + - Point-in-time analysis only + - No temporal trend information + - Assumes band boundaries are appropriate + - May oversimplify risk patterns + """ + + if score_column not in dataset.df.columns: + raise ValueError( + f"The required column '{score_column}' is not present in the dataset with input_id {dataset.input_id}" + ) + + df = dataset._df.copy() + + # Default score bands if none provided + if score_bands is None: + score_bands = [410, 440, 470] + + # Create band labels + band_labels = [ + f"{score_bands[i]}-{score_bands[i+1]}" for i in range(len(score_bands) - 1) + ] + band_labels.insert(0, f"<{score_bands[0]}") + band_labels.append(f">{score_bands[-1]}") + + # Bin the scores with infinite upper bound + df["score_band"] = pd.cut( + df[score_column], bins=[-np.inf] + score_bands + [np.inf], labels=band_labels + ) + + # Calculate min and max scores for the total row + min_score = df[score_column].min() + max_score = df[score_column].max() + + # Get predicted classes (0/1) + y_pred = dataset.y_pred(model) + + # Calculate metrics by band using target_column name + results = [] + for band in band_labels: + band_mask = df["score_band"] == band + population = band_mask.sum() + observed_defaults = df[band_mask][dataset.target_column].sum() + predicted_defaults = y_pred[ + band_mask + ].sum() # Sum of 1s gives number of predicted defaults + + results.append( + { + "Score Band": band, + "Population Count": population, + "Population (%)": population / len(df) * 100, + "Predicted Default Rate (%)": ( + predicted_defaults / population * 100 if population > 0 else 0 + ), + "Observed Default Rate (%)": ( + observed_defaults / population * 100 if population > 0 else 0 + ), + } + ) + + # Add total row + total_population = len(df) + total_observed = df[dataset.target_column].sum() + total_predicted = y_pred.sum() # Total number of predicted defaults + + results.append( + { + "Score Band": f"Total ({min_score:.0f}-{max_score:.0f})", + "Population Count": total_population, + "Population (%)": sum(r["Population (%)"] for r in results), + "Predicted Default Rate (%)": total_predicted / total_population * 100, + "Observed Default Rate (%)": total_observed / total_population * 100, + } + ) + + return pd.DataFrame(results) diff --git a/validmind/tests/data_validation/TooManyZeroValues.py b/validmind/tests/data_validation/TooManyZeroValues.py index 095e526a1..1adf5a811 100644 --- a/validmind/tests/data_validation/TooManyZeroValues.py +++ b/validmind/tests/data_validation/TooManyZeroValues.py @@ -71,13 +71,13 @@ def TooManyZeroValues(dataset: VMDataset, max_percent_threshold: float = 0.03): continue n_zeros = value_counts[0] - p_zeros = n_zeros / df.shape[0] + p_zeros = (n_zeros / df.shape[0]) * 100 table.append( { "Column": col, "Number of Zero Values": n_zeros, - "Percentage of Zero Values (%)": p_zeros * 100, + "Percentage of Zero Values (%)": p_zeros, "Pass/Fail": "Pass" if p_zeros < max_percent_threshold else "Fail", } ) diff --git a/validmind/tests/data_validation/UniqueRows.py b/validmind/tests/data_validation/UniqueRows.py index 1d9f075f8..e6e0278bf 100644 --- a/validmind/tests/data_validation/UniqueRows.py +++ b/validmind/tests/data_validation/UniqueRows.py @@ -61,7 +61,9 @@ def UniqueRows(dataset: VMDataset, min_percent_threshold: float = 1): "Number of Unique Values": unique_rows[col], "Percentage of Unique Values (%)": unique_rows[col] / rows * 100, "Pass/Fail": ( - "Pass" if unique_rows[col] / rows >= min_percent_threshold else "Fail" + "Pass" + if (unique_rows[col] / rows * 100) >= min_percent_threshold + else "Fail" ), } for col in unique_rows.index diff --git a/validmind/tests/model_validation/sklearn/CalibrationCurve.py b/validmind/tests/model_validation/sklearn/CalibrationCurve.py new file mode 100644 index 000000000..71739bbb8 --- /dev/null +++ b/validmind/tests/model_validation/sklearn/CalibrationCurve.py @@ -0,0 +1,116 @@ +# Copyright © 2023-2024 ValidMind Inc. All rights reserved. +# See the LICENSE file in the root of this repository for details. +# SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial + +from sklearn.calibration import calibration_curve +import plotly.graph_objects as go +from validmind import tags, tasks +from validmind.vm_models import VMModel, VMDataset +from validmind.vm_models.result import RawData + + +@tags("sklearn", "model_performance", "classification") +@tasks("classification") +def CalibrationCurve(model: VMModel, dataset: VMDataset, n_bins: int = 10): + """ + Evaluates the calibration of probability estimates by comparing predicted probabilities against observed + frequencies. + + ### Purpose + + The Calibration Curve test assesses how well a model's predicted probabilities align with actual + observed frequencies. This is crucial for applications requiring accurate probability estimates, + such as risk assessment, decision-making systems, and cost-sensitive applications where probability + calibration directly impacts business decisions. + + ### Test Mechanism + + The test uses sklearn's calibration_curve function to: + 1. Sort predictions into bins based on predicted probabilities + 2. Calculate the mean predicted probability in each bin + 3. Compare against the observed frequency of positive cases + 4. Plot the results against the perfect calibration line (y=x) + The resulting curve shows how well the predicted probabilities match empirical probabilities. + + ### Signs of High Risk + + - Significant deviation from the perfect calibration line + - Systematic overconfidence (predictions too close to 0 or 1) + - Systematic underconfidence (predictions clustered around 0.5) + - Empty or sparse bins indicating poor probability coverage + - Sharp discontinuities in the calibration curve + - Different calibration patterns across different probability ranges + - Consistent over/under estimation in critical probability regions + - Large confidence intervals in certain probability ranges + + ### Strengths + + - Visual and intuitive interpretation of probability quality + - Identifies systematic biases in probability estimates + - Supports probability threshold selection + - Helps understand model confidence patterns + - Applicable across different classification models + - Enables comparison between different models + - Guides potential need for recalibration + - Critical for risk-sensitive applications + + ### Limitations + + - Sensitive to the number of bins chosen + - Requires sufficient samples in each bin for reliable estimates + - May mask local calibration issues within bins + - Does not account for feature-dependent calibration issues + - Limited to binary classification problems + - Cannot detect all forms of miscalibration + - Assumes bin boundaries are appropriate for the problem + - May be affected by class imbalance + """ + prob_true, prob_pred = calibration_curve( + dataset.y, dataset.y_prob(model), n_bins=n_bins + ) + + # Create DataFrame for raw data + raw_data = RawData( + mean_predicted_probability=prob_pred, observed_frequency=prob_true + ) + + # Create Plotly figure + fig = go.Figure() + + # Add perfect calibration line + fig.add_trace( + go.Scatter( + x=[0, 1], + y=[0, 1], + mode="lines", + name="Perfect Calibration", + line=dict(dash="dash", color="gray"), + ) + ) + + # Add calibration curve + fig.add_trace( + go.Scatter( + x=prob_pred, + y=prob_true, + mode="lines+markers", + name="Model Calibration", + line=dict(color="blue"), + marker=dict(size=8), + ) + ) + + # Update layout + fig.update_layout( + title="Calibration Curve", + xaxis_title="Mean Predicted Probability", + yaxis_title="Observed Frequency", + xaxis=dict(range=[0, 1]), + yaxis=dict(range=[0, 1]), + width=800, + height=600, + showlegend=True, + template="plotly_white", + ) + + return raw_data, fig diff --git a/validmind/tests/model_validation/sklearn/ClassifierThresholdOptimization.py b/validmind/tests/model_validation/sklearn/ClassifierThresholdOptimization.py new file mode 100644 index 000000000..04972ab6c --- /dev/null +++ b/validmind/tests/model_validation/sklearn/ClassifierThresholdOptimization.py @@ -0,0 +1,257 @@ +import numpy as np +import pandas as pd +import plotly.graph_objects as go +from plotly.subplots import make_subplots +from sklearn.metrics import ( + roc_curve, + precision_recall_curve, + confusion_matrix, +) +from validmind import tags, tasks +from validmind.vm_models import VMDataset, VMModel + + +def find_optimal_threshold(y_true, y_prob, method="youden", target_recall=None): + """ + Find the optimal classification threshold using various methods. + + Args: + y_true: True binary labels + y_prob: Predicted probabilities + method: Method to use for finding optimal threshold + target_recall: Required if method='target_recall' + + Returns: + dict: Dictionary containing threshold and metrics + """ + # Get ROC and PR curve points + fpr, tpr, thresholds_roc = roc_curve(y_true, y_prob) + precision, recall, thresholds_pr = precision_recall_curve(y_true, y_prob) + + # Find optimal threshold based on method + if method == "naive": + optimal_threshold = 0.5 + elif method == "youden": + j_scores = tpr - fpr + best_idx = np.argmax(j_scores) + optimal_threshold = thresholds_roc[best_idx] + elif method == "f1": + f1_scores = 2 * (precision * recall) / (precision + recall) + best_idx = np.argmax(f1_scores) + optimal_threshold = ( + thresholds_pr[best_idx] if best_idx < len(thresholds_pr) else 1.0 + ) + elif method == "precision_recall": + diff = abs(precision - recall) + best_idx = np.argmin(diff) + optimal_threshold = ( + thresholds_pr[best_idx] if best_idx < len(thresholds_pr) else 1.0 + ) + elif method == "target_recall": + if target_recall is None: + raise ValueError( + "target_recall must be specified when method='target_recall'" + ) + idx = np.argmin(abs(recall - target_recall)) + optimal_threshold = thresholds_pr[idx] if idx < len(thresholds_pr) else 1.0 + else: + raise ValueError(f"Unknown method: {method}") + + # Calculate predictions with optimal threshold + y_pred = (y_prob >= optimal_threshold).astype(int) + + # Calculate confusion matrix + tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel() + + # Calculate metrics directly + metrics = { + "method": method, + "threshold": optimal_threshold, + "precision": tp / (tp + fp) if (tp + fp) > 0 else 0, + "recall": tp / (tp + fn) if (tp + fn) > 0 else 0, + "f1_score": 2 * tp / (2 * tp + fp + fn) if (2 * tp + fp + fn) > 0 else 0, + "accuracy": (tp + tn) / (tp + tn + fp + fn), + } + + return metrics + + +@tags("model_validation", "threshold_optimization", "classification_metrics") +@tasks("classification") +def ClassifierThresholdOptimization( + dataset: VMDataset, model: VMModel, methods=None, target_recall=None +): + """ + Analyzes and visualizes different threshold optimization methods for binary classification models. + + ### Purpose + + The Classifier Threshold Optimization test identifies optimal decision thresholds using various + methods to balance different performance metrics. This helps adapt the model's decision boundary + to specific business requirements, such as minimizing false positives in fraud detection or + achieving target recall in medical diagnosis. + + ### Test Mechanism + + The test implements multiple threshold optimization methods: + 1. Youden's J statistic (maximizing sensitivity + specificity - 1) + 2. F1-score optimization (balancing precision and recall) + 3. Precision-Recall equality point + 4. Target recall achievement + 5. Naive (0.5) threshold + For each method, it computes ROC and PR curves, identifies optimal points, and provides + comprehensive performance metrics at each threshold. + + ### Signs of High Risk + + - Large discrepancies between different optimization methods + - Optimal thresholds far from the default 0.5 + - Poor performance metrics across all thresholds + - Significant gap between achieved and target recall + - Unstable thresholds across different methods + - Extreme trade-offs between precision and recall + - Threshold optimization showing minimal impact + - Business metrics not improving with optimization + + ### Strengths + + - Multiple optimization strategies for different needs + - Visual and numerical results for comparison + - Support for business-driven optimization (target recall) + - Comprehensive performance metrics at each threshold + - Integration with ROC and PR curves + - Handles class imbalance through various metrics + - Enables informed threshold selection + - Supports cost-sensitive decision making + + ### Limitations + + - Assumes cost of false positives/negatives are known + - May need adjustment for highly imbalanced datasets + - Threshold might not be stable across different samples + - Cannot handle multi-class problems directly + - Optimization methods may conflict with business needs + - Requires sufficient validation data + - May not capture temporal changes in optimal threshold + - Single threshold may not be optimal for all subgroups + + Args: + dataset: VMDataset containing features and target + model: VMModel containing predictions + methods: List of methods to compare (default: ['youden', 'f1', 'precision_recall']) + target_recall: Target recall value if using 'target_recall' method + + Returns: + Dictionary containing: + - table: DataFrame comparing different threshold optimization methods + (using weighted averages for precision, recall, and f1) + - figure: Plotly figure showing ROC and PR curves with optimal thresholds + """ + # Verify binary classification + unique_values = np.unique(dataset.y) + if len(unique_values) != 2: + raise ValueError("Target variable must be binary") + + if methods is None: + methods = ["naive", "youden", "f1", "precision_recall"] + if target_recall is not None: + methods.append("target_recall") + + y_true = dataset.y + y_prob = dataset.y_prob(model) + + # Get curve points for plotting + fpr, tpr, thresholds_roc = roc_curve(y_true, y_prob) + precision, recall, thresholds_pr = precision_recall_curve(y_true, y_prob) + + # Calculate optimal thresholds and metrics + results = [] + optimal_points = {} + + for method in methods: + metrics = find_optimal_threshold(y_true, y_prob, method, target_recall) + results.append(metrics) + + # Store optimal points for plotting + if method == "youden": + idx = np.argmax(tpr - fpr) + optimal_points[method] = { + "x": fpr[idx], + "y": tpr[idx], + "threshold": thresholds_roc[idx], + } + elif method in ["f1", "precision_recall", "target_recall"]: + idx = np.argmin(abs(thresholds_pr - metrics["threshold"])) + optimal_points[method] = { + "x": recall[idx], + "y": precision[idx], + "threshold": metrics["threshold"], + } + + # Create visualization + fig = make_subplots( + rows=1, cols=2, subplot_titles=("ROC Curve", "Precision-Recall Curve") + ) + + # Plot ROC curve + fig.add_trace( + go.Scatter(x=fpr, y=tpr, name="ROC Curve", line=dict(color="blue")), + row=1, + col=1, + ) + + # Plot PR curve + fig.add_trace( + go.Scatter(x=recall, y=precision, name="PR Curve", line=dict(color="green")), + row=1, + col=2, + ) + + # Add optimal points + colors = { + "youden": "red", + "f1": "orange", + "precision_recall": "purple", + "target_recall": "brown", + } + + for method, points in optimal_points.items(): + if method == "youden": + fig.add_trace( + go.Scatter( + x=[points["x"]], + y=[points["y"]], + name=f'{method} (t={points["threshold"]:.2f})', + mode="markers", + marker=dict(size=10, color=colors[method]), + ), + row=1, + col=1, + ) + else: + fig.add_trace( + go.Scatter( + x=[points["x"]], + y=[points["y"]], + name=f'{method} (t={points["threshold"]:.2f})', + mode="markers", + marker=dict(size=10, color=colors[method]), + ), + row=1, + col=2, + ) + + # Update layout + fig.update_layout( + height=500, title_text="Threshold Optimization Analysis", showlegend=True + ) + + fig.update_xaxes(title_text="False Positive Rate", row=1, col=1) + fig.update_xaxes(title_text="Recall", row=1, col=2) + fig.update_yaxes(title_text="True Positive Rate", row=1, col=1) + fig.update_yaxes(title_text="Precision", row=1, col=2) + + # Create results table and sort by threshold descending + table = pd.DataFrame(results).sort_values("threshold", ascending=False) + + return fig, table diff --git a/validmind/tests/model_validation/sklearn/HyperParametersTuning.py b/validmind/tests/model_validation/sklearn/HyperParametersTuning.py index 88b8eb209..12a28ee04 100644 --- a/validmind/tests/model_validation/sklearn/HyperParametersTuning.py +++ b/validmind/tests/model_validation/sklearn/HyperParametersTuning.py @@ -2,73 +2,133 @@ # See the LICENSE file in the root of this repository for details. # SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial -from typing import Union - +from typing import Union, Dict, List from sklearn.model_selection import GridSearchCV +from sklearn.metrics import make_scorer, recall_score from validmind import tags, tasks -from validmind.errors import SkipTestError from validmind.vm_models import VMDataset, VMModel +@tags("sklearn", "model_performance") +@tasks("classification", "clustering") +def custom_recall(y_true, y_pred_proba, threshold=0.5): + y_pred = (y_pred_proba >= threshold).astype(int) + return recall_score(y_true, y_pred) + + @tags("sklearn", "model_performance") @tasks("classification", "clustering") def HyperParametersTuning( model: VMModel, dataset: VMDataset, - param_grid: Union[dict, None] = None, - scoring: Union[str, None] = None, + param_grid: dict, + scoring: Union[str, List, Dict], + thresholds: Union[float, List[float]] = 0.5, + fit_params: dict = None, ): """ - Exerts exhaustive grid search to identify optimal hyperparameters for the model, improving performance. - - ### Purpose: - - The "HyperParametersTuning" metric aims to find the optimal set of hyperparameters for a given model. The test is - designed to enhance the performance of the model by determining the best configuration of hyperparameters. The - parameters that are being optimized are defined by the parameter grid provided to the metric. - - ### Test Mechanism: - - The HyperParametersTuning test employs a grid search mechanism using the GridSearchCV function from the - scikit-learn library. The grid search algorithm systematically works through multiple combinations of parameter - values, cross-validating to determine which combination gives the best model performance. The chosen model and the - parameter grid passed for tuning are necessary inputs. Once the grid search is complete, the test caches and - returns details of the best model and its associated parameters. - - ### Signs of High Risk: - - - The test raises a SkipTestError if the param_grid is not supplied, indicating a lack of specific parameters to - optimize, which can be risky for certain model types reliant on parameter tuning. - - Poorly chosen scoring metrics that do not align well with the specific model or problem at hand could reflect - potential risks or failures in achieving optimal performance. - - ### Strengths: - - - Provides a comprehensive exploration mechanism to identify the best set of hyperparameters for the supplied - model, thereby enhancing its performance. - - Implements GridSearchCV, simplifying and automating the time-consuming task of hyperparameter tuning. - - ### Limitations: - - - The grid search algorithm can be computationally expensive, especially with large datasets or complex models, and - can be time-consuming as it tests all possible combinations within the specified parameter grid. - - The effectiveness of the tuning is heavily dependent on the quality of data and only accepts datasets with - numerical or ordered categories. - - Assumes that the same set of hyperparameters is optimal for all problem sets, which may not be true in every - scenario. - - There's a potential risk of overfitting the model if the training set is not representative of the data that the - model will be applied to. + Performs exhaustive grid search over specified parameter ranges to find optimal model configurations + across different metrics and decision thresholds. + + ### Purpose + + The Hyperparameter Tuning test systematically explores the model's parameter space to identify optimal + configurations. It supports multiple optimization metrics and decision thresholds, providing a comprehensive + view of how different parameter combinations affect various aspects of model performance. + + ### Test Mechanism + + The test uses scikit-learn's GridSearchCV to perform cross-validation for each parameter combination. + For each specified threshold and optimization metric, it creates a scoring dictionary with + threshold-adjusted metrics, performs grid search with cross-validation, records best parameters and + corresponding scores, and combines results into a comparative table. This process is repeated for each + optimization metric to provide a comprehensive view of model performance under different configurations. + + ### Signs of High Risk + + - Large performance variations across different parameter combinations + - Significant discrepancies between different optimization metrics + - Best parameters at the edges of the parameter grid + - Unstable performance across different thresholds + - Overly complex model configurations (risk of overfitting) + - Very different optimal parameters for different metrics + - Cross-validation scores showing high variance + - Extreme parameter values in best configurations + + ### Strengths + + - Comprehensive exploration of parameter space + - Supports multiple optimization metrics + - Allows threshold optimization + - Provides comparative view across different configurations + - Uses cross-validation for robust evaluation + - Helps understand trade-offs between different metrics + - Enables systematic parameter selection + - Supports both classification and clustering tasks + + ### Limitations + + - Computationally expensive for large parameter grids + - May not find global optimum (limited to grid points) + - Cannot handle dependencies between parameters + - Memory intensive for large datasets + - Limited to scikit-learn compatible models + - Cross-validation splits may not preserve time series structure + - Grid search may miss optimal values between grid points + - Resource intensive for high-dimensional parameter spaces """ - if not param_grid: - raise SkipTestError("'param_grid' dictionary must be provided to run this test") - - estimators = GridSearchCV(model.model, param_grid=param_grid, scoring=scoring) - estimators.fit(dataset.x, dataset.y) - - return [ - { - "Best Model": estimators.best_estimator_, - "Best Parameters": estimators.best_params_, - } - ] + results = [] + metrics = ( + scoring + if isinstance(scoring, list) + else list(scoring.keys()) if isinstance(scoring, dict) else [scoring] + ) + + # Convert single threshold to list + if isinstance(thresholds, (int, float)): + thresholds = [thresholds] + + # For each threshold + for threshold in thresholds: + # Create scoring dict with current threshold + scoring_dict = {} + for metric in metrics: + if metric == "recall": + scoring_dict[metric] = make_scorer( + custom_recall, needs_proba=True, threshold=threshold + ) + elif metric == "roc_auc": + scoring_dict[metric] = "roc_auc" # threshold independent + # Add other metrics as needed + + # Run GridSearchCV for each optimization metric + for optimize_for in metrics: + estimators = GridSearchCV( + model.model, + param_grid=param_grid, + scoring=scoring_dict, + refit=optimize_for, # Optimize for current metric + ) + + # Fit model + fit_params = fit_params or {} + estimators.fit(dataset.x_df(), dataset.y, **fit_params) + + # Get results for this optimization + best_index = estimators.best_index_ + row_result = { + "Optimized for": optimize_for, + "Threshold": threshold, + "Best Parameters": estimators.best_params_, + } + + # Add scores for all metrics + for metric in metrics: + row_result[f"{metric}"] = estimators.cv_results_[f"mean_test_{metric}"][ + best_index + ] + + results.append(row_result) + + return results diff --git a/validmind/tests/model_validation/sklearn/ModelParameters.py b/validmind/tests/model_validation/sklearn/ModelParameters.py new file mode 100644 index 000000000..62983d134 --- /dev/null +++ b/validmind/tests/model_validation/sklearn/ModelParameters.py @@ -0,0 +1,74 @@ +# Copyright © 2023-2024 ValidMind Inc. All rights reserved. +# See the LICENSE file in the root of this repository for details. +# SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial + +import pandas as pd +from validmind import tags, tasks + + +@tags("model_training", "metadata") +@tasks("classification", "regression") +def ModelParameters(model, model_params=None): + """ + Extracts and displays model parameters in a structured format for transparency and reproducibility. + + ### Purpose + + The Model Parameters test is designed to provide transparency into model configuration and ensure + reproducibility of machine learning models. It accomplishes this by extracting and presenting all + relevant parameters that define the model's behavior, making it easier to audit, validate, and + reproduce model training. + + ### Test Mechanism + + The test leverages scikit-learn's API convention of get_params() to extract model parameters. It + produces a structured DataFrame containing parameter names and their corresponding values. For models + that follow scikit-learn's API (including XGBoost, RandomForest, and other estimators), all + parameters are automatically extracted and displayed. + + ### Signs of High Risk + + - Missing crucial parameters that should be explicitly set + - Extreme parameter values that could indicate overfitting (e.g., unlimited tree depth) + - Inconsistent parameters across different versions of the same model type + - Parameter combinations known to cause instability or poor performance + - Default values used for critical parameters that should be tuned + + ### Strengths + + - Universal compatibility with scikit-learn API-compliant models + - Ensures transparency in model configuration + - Facilitates model reproducibility and version control + - Enables systematic parameter auditing + - Supports both classification and regression models + - Helps identify potential configuration issues + + ### Limitations + + - Only works with models implementing scikit-learn's get_params() method + - Cannot capture dynamic parameters set during model training + - Does not validate parameter values for model-specific appropriateness + - Parameter meanings and impacts may vary across different model types + - Cannot detect indirect parameter interactions or their effects on model performance + """ + # Check if model implements get_params() + if not hasattr(model.model, "get_params"): + return pd.DataFrame() + + # Get all model parameters + params = model.model.get_params() + + # If model_params is None, use all parameters from get_params() + if model_params is None: + model_params = sorted(params.keys()) # Sort for consistent ordering + + # Create DataFrame with parameters and their values + param_df = pd.DataFrame( + [ + {"Parameter": param, "Value": str(params.get(param, "Not specified"))} + for param in model_params + if params.get(param) is not None + ] + ) + + return param_df diff --git a/validmind/tests/model_validation/sklearn/ScoreProbabilityAlignment.py b/validmind/tests/model_validation/sklearn/ScoreProbabilityAlignment.py new file mode 100644 index 000000000..fefbd49bc --- /dev/null +++ b/validmind/tests/model_validation/sklearn/ScoreProbabilityAlignment.py @@ -0,0 +1,126 @@ +import pandas as pd +import plotly.graph_objects as go +from validmind import tags, tasks +from validmind.vm_models import VMModel, VMDataset + + +@tags("visualization", "credit_risk", "calibration") +@tasks("classification") +def ScoreProbabilityAlignment( + model: VMModel, dataset: VMDataset, score_column: str = "score", n_bins: int = 10 +): + """ + Analyzes the alignment between credit scores and predicted probabilities. + + ### Purpose + + The Score-Probability Alignment test evaluates how well credit scores align with + predicted default probabilities. This helps validate score scaling, identify potential + calibration issues, and ensure scores reflect risk appropriately. + + ### Test Mechanism + + The test: + 1. Groups scores into bins + 2. Calculates average predicted probability per bin + 3. Tests monotonicity of relationship + 4. Analyzes probability distribution within score bands + + ### Signs of High Risk + + - Non-monotonic relationship between scores and probabilities + - Large probability variations within score bands + - Unexpected probability jumps between adjacent bands + - Poor alignment with expected odds-to-score relationship + - Inconsistent probability patterns across score ranges + - Clustering of probabilities at extreme values + - Score bands with similar probability profiles + - Unstable probability estimates in key decision bands + + ### Strengths + + - Direct validation of score-to-probability relationship + - Identifies potential calibration issues + - Supports score band validation + - Helps understand model behavior + - Useful for policy setting + - Visual and numerical results + - Easy to interpret + - Supports regulatory documentation + + ### Limitations + + - Sensitive to bin selection + - Requires sufficient data per bin + - May mask within-bin variations + - Point-in-time analysis only + - Cannot detect all forms of miscalibration + - Assumes scores should align with probabilities + - May oversimplify complex relationships + - Limited to binary outcomes + """ + if score_column not in dataset.df.columns: + raise ValueError(f"Score column '{score_column}' not found in dataset") + + # Get predicted probabilities + y_prob = dataset.y_prob(model) + + # Create score bins + df = dataset.df.copy() + df["probability"] = y_prob + + # Create score bins with equal width + df["score_bin"] = pd.qcut(df[score_column], n_bins, duplicates="drop") + + # Calculate statistics per bin + results = [] + for bin_name, group in df.groupby("score_bin"): + bin_stats = { + "Score Range": f"{bin_name.left:.0f}-{bin_name.right:.0f}", + "Mean Score": group[score_column].mean(), + "Population Count": len(group), + "Population (%)": len(group) / len(df) * 100, + "Mean Probability (%)": group["probability"].mean() * 100, + "Min Probability (%)": group["probability"].min() * 100, + "Max Probability (%)": group["probability"].max() * 100, + "Probability Std": group["probability"].std() * 100, + } + results.append(bin_stats) + + results_df = pd.DataFrame(results) + + # Create visualization + fig = go.Figure() + + # Add probability range + fig.add_trace( + go.Scatter( + x=results_df["Mean Score"], + y=results_df["Mean Probability (%)"], + mode="lines+markers", + name="Mean Probability", + line=dict(color="blue"), + error_y=dict( + type="data", + symmetric=False, + array=results_df["Max Probability (%)"] + - results_df["Mean Probability (%)"], + arrayminus=results_df["Mean Probability (%)"] + - results_df["Min Probability (%)"], + color="gray", + ), + ) + ) + + # Update layout + fig.update_layout( + title="Score-Probability Alignment", + xaxis_title="Score", + yaxis_title="Default Probability (%)", + showlegend=True, + template="plotly_white", + width=800, + height=600, + ) + + return results_df, fig diff --git a/validmind/utils.py b/validmind/utils.py index 42b3ec75b..e45325949 100644 --- a/validmind/utils.py +++ b/validmind/utils.py @@ -459,18 +459,23 @@ def get_dataset_info(dataset): def preview_test_config(config): - formatted_json = json.dumps(config, indent=4) + """Preview test configuration in a collapsible HTML section. + + Args: + config (dict): Test configuration dictionary + """ + + try: + formatted_json = json.dumps(serialize(config), indent=4) + except TypeError as e: + logger.error(f"JSON serialization failed: {e}") + return - # JavaScript + HTML for the collapsible section collapsible_html = f""" @@ -556,3 +561,14 @@ def inspect_obj(obj): # Loop through the parameters and print detailed information for param_name, param in sig.parameters.items(): print(f"{param_name} - ({param.default})") + + +def serialize(obj): + """Convert objects to JSON-serializable format with readable descriptions.""" + if isinstance(obj, dict): + return {k: serialize(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return [serialize(x) for x in obj] + elif isinstance(obj, (pd.DataFrame, pd.Series)): + return "" # Simple empty string for non-serializable objects + return obj From 43d4f74a94eeebd42d9f1af7b507cfe666655ab8 Mon Sep 17 00:00:00 2001 From: Juan Date: Thu, 2 Jan 2025 14:59:58 +0100 Subject: [PATCH 02/10] Update validmind install --- .../credit_risk/application_scorecard_full_suite.ipynb | 2 +- .../credit_risk/application_scorecard_with_ml.ipynb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb b/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb index ccfc69d86..f3897f2cf 100644 --- a/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb +++ b/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb @@ -142,7 +142,7 @@ "metadata": {}, "outputs": [], "source": [ - "%pip install -q -e ../../../../developer-framework" + "%pip install -q validmind" ] }, { diff --git a/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb b/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb index 6dbfee911..a710c876b 100644 --- a/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb +++ b/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb @@ -142,7 +142,7 @@ "metadata": {}, "outputs": [], "source": [ - "%pip install -q -e ../../../../developer-framework" + "%pip install -q validmind" ] }, { From 01de056d0d69950fed37ccb3caa22819ffad4bd4 Mon Sep 17 00:00:00 2001 From: Juan Date: Thu, 2 Jan 2025 15:09:33 +0100 Subject: [PATCH 03/10] Add copyright headers --- .../credit_risk/application_scorecard_full_suite.ipynb | 9 +++------ validmind/tests/data_validation/ScoreBandDefaultRates.py | 4 ++++ .../sklearn/ClassifierThresholdOptimization.py | 4 ++++ .../sklearn/ScoreProbabilityAlignment.py | 4 ++++ 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb b/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb index f3897f2cf..965446378 100644 --- a/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb +++ b/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb @@ -646,13 +646,10 @@ "metadata": {}, "outputs": [], "source": [ - "run=True\n", - "if run:\n", + "from validmind.utils import preview_test_config\n", "\n", - " from validmind.utils import preview_test_config\n", - "\n", - " test_config = lending_club.get_demo_test_config(x_test, y_test)\n", - " preview_test_config(test_config)" + "test_config = lending_club.get_demo_test_config(x_test, y_test)\n", + "preview_test_config(test_config)" ] }, { diff --git a/validmind/tests/data_validation/ScoreBandDefaultRates.py b/validmind/tests/data_validation/ScoreBandDefaultRates.py index 9056295e3..567c07279 100644 --- a/validmind/tests/data_validation/ScoreBandDefaultRates.py +++ b/validmind/tests/data_validation/ScoreBandDefaultRates.py @@ -1,3 +1,7 @@ +# Copyright © 2023-2024 ValidMind Inc. All rights reserved. +# See the LICENSE file in the root of this repository for details. +# SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial + import pandas as pd import numpy as np from validmind import tags, tasks diff --git a/validmind/tests/model_validation/sklearn/ClassifierThresholdOptimization.py b/validmind/tests/model_validation/sklearn/ClassifierThresholdOptimization.py index 04972ab6c..1cdc62998 100644 --- a/validmind/tests/model_validation/sklearn/ClassifierThresholdOptimization.py +++ b/validmind/tests/model_validation/sklearn/ClassifierThresholdOptimization.py @@ -1,3 +1,7 @@ +# Copyright © 2023-2024 ValidMind Inc. All rights reserved. +# See the LICENSE file in the root of this repository for details. +# SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial + import numpy as np import pandas as pd import plotly.graph_objects as go diff --git a/validmind/tests/model_validation/sklearn/ScoreProbabilityAlignment.py b/validmind/tests/model_validation/sklearn/ScoreProbabilityAlignment.py index fefbd49bc..dadb3e974 100644 --- a/validmind/tests/model_validation/sklearn/ScoreProbabilityAlignment.py +++ b/validmind/tests/model_validation/sklearn/ScoreProbabilityAlignment.py @@ -1,3 +1,7 @@ +# Copyright © 2023-2024 ValidMind Inc. All rights reserved. +# See the LICENSE file in the root of this repository for details. +# SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial + import pandas as pd import plotly.graph_objects as go from validmind import tags, tasks From 27397f57fa88fbbdcafcb236b945213c6b85c4e4 Mon Sep 17 00:00:00 2001 From: Juan Date: Fri, 3 Jan 2025 15:51:38 +0100 Subject: [PATCH 04/10] Add env variable to add external context for test descriptions. --- .../application_scorecard_with_ml.ipynb | 907 +++++++++++++++++- .../sklearn/ConfusionMatrix.py | 1 + .../CumulativePredictionProbabilities.py | 11 +- .../PredictionProbabilitiesHistogram.py | 5 +- 4 files changed, 886 insertions(+), 38 deletions(-) diff --git a/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb b/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb index a710c876b..620edac77 100644 --- a/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb +++ b/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb @@ -138,9 +138,21 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\u001b[33mWARNING: visions 0.7.6 does not provide the extra 'type-image-path'\u001b[0m\u001b[33m\n", + "\u001b[0m\n", + "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n", + "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n", + "Note: you may need to restart the kernel to use updated packages.\n" + ] + } + ], "source": [ "%pip install -q validmind" ] @@ -179,9 +191,19 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "2025-01-03 15:41:50,510 - INFO(validmind.api_client): 🎉 Connected to ValidMind!\n", + "📊 Model: [JM] Credit Risk Scorecard (ID: cm5gljv9100021nignfpbkvvc)\n", + "📁 Document Type: model_documentation\n" + ] + } + ], "source": [ "# Load your model identifier credentials from an `.env` file\n", "\n", @@ -241,9 +263,73 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "aeda8e9baaca448e8e8ce41ceeadab8e", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "Accordion(children=(HTML(value='

Empty Section

'), Accordion(children=(VBox(children=(HTML(value='\\n\n", + "import hljs from 'https://unpkg.com/@highlightjs/cdn-assets@11.9.0/es/highlight.min.js';\n", + "import python from 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/es/languages/python.min.js';\n", + "\n", + "hljs.registerLanguage('python', python);\n", + "hljs.highlightAll();\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "vm.preview_template()" ] @@ -261,9 +347,186 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Loading data from an offline .gz file: /Users/juanvalidmind/Dev/github/validmind/developer-framework/validmind/datasets/credit_risk/datasets/lending_club_loan_data_2007_2014_clean.csv.gz\n", + "Attempting to read from .gz file: /Users/juanvalidmind/Dev/github/validmind/developer-framework/validmind/datasets/credit_risk/datasets/lending_club_loan_data_2007_2014_clean.csv.gz\n", + "Data loaded successfully.\n", + "Rows: 227214, Columns: 16, Missing values: 8673\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
loan_amntfunded_amnt_invtermint_rateinstallmentgradesub_gradeemp_lengthhome_ownershipannual_incverification_statusloan_statuspurposeopen_acctotal_acctotal_pymnt
050004975.036 months10.65162.87BB210+ yearsRENT24000.0Verified0.0credit_card3.09.05861.071414
125002500.060 months15.2759.83CC4< 1 yearRENT30000.0Source Verified1.0car3.04.01008.710000
224002400.036 months15.9684.33CC510+ yearsRENT12252.0Not Verified0.0small_business2.010.03003.653644
31000010000.036 months13.49339.31CC110+ yearsRENT49200.0Source Verified0.0other10.037.012226.302210
450005000.036 months7.90156.46AA43 yearsRENT36000.0Source Verified0.0wedding9.012.05631.377753
\n", + "
" + ], + "text/plain": [ + " loan_amnt funded_amnt_inv term int_rate installment grade \\\n", + "0 5000 4975.0 36 months 10.65 162.87 B \n", + "1 2500 2500.0 60 months 15.27 59.83 C \n", + "2 2400 2400.0 36 months 15.96 84.33 C \n", + "3 10000 10000.0 36 months 13.49 339.31 C \n", + "4 5000 5000.0 36 months 7.90 156.46 A \n", + "\n", + " sub_grade emp_length home_ownership annual_inc verification_status \\\n", + "0 B2 10+ years RENT 24000.0 Verified \n", + "1 C4 < 1 year RENT 30000.0 Source Verified \n", + "2 C5 10+ years RENT 12252.0 Not Verified \n", + "3 C1 10+ years RENT 49200.0 Source Verified \n", + "4 A4 3 years RENT 36000.0 Source Verified \n", + "\n", + " loan_status purpose open_acc total_acc total_pymnt \n", + "0 0.0 credit_card 3.0 9.0 5861.071414 \n", + "1 1.0 car 3.0 4.0 1008.710000 \n", + "2 0.0 small_business 2.0 10.0 3003.653644 \n", + "3 0.0 other 10.0 37.0 12226.302210 \n", + "4 0.0 wedding 9.0 12.0 5631.377753 " + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "df = lending_club.load_data(source=\"offline\")\n", "\n", @@ -289,9 +552,194 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Filtering 'purpose' to 'debt_consolidation' and 'credit_card':\n", + "Rows: 177825\n", + "Columns: 16\n", + "Missing values: 6507\n", + "\n", + "Filtering out 'grade' F and G:\n", + "Rows: 172165\n", + "Columns: 16\n", + "Missing values: 6352\n", + "\n", + "Filtering out 'sub_grade' F and G:\n", + "Rows: 172165\n", + "Columns: 16\n", + "Missing values: 6352\n", + "\n", + "Filtering out 'home_ownership' OTHER, NONE, ANY:\n", + "Rows: 172045\n", + "Columns: 16\n", + "Missing values: 6350\n", + "\n", + "Dropping specified features:\n", + "Rows: 172045\n", + "Columns: 13\n", + "Missing values: 6350\n", + "\n", + "Dropping rows with any missing values:\n", + "Rows: 165695\n", + "Columns: 13\n", + "Missing values: 0\n", + "\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
termint_rateinstallmentgradesub_gradeemp_lengthhome_ownershipannual_incverification_statusloan_statuspurposeopen_acctotal_acc
03610.65162.87BB210RENT24000.0Verified0credit_card3.09.0
86014.65153.45CC35OWN72000.0Not Verified0debt_consolidation14.023.0
93612.69402.54BB510OWN75000.0Source Verified0debt_consolidation12.034.0
103613.49305.38CC10RENT30000.0Source Verified1debt_consolidation4.09.0
11369.9196.68BB13RENT15000.0Source Verified0credit_card11.011.0
\n", + "
" + ], + "text/plain": [ + " term int_rate installment grade sub_grade emp_length home_ownership \\\n", + "0 36 10.65 162.87 B B2 10 RENT \n", + "8 60 14.65 153.45 C C3 5 OWN \n", + "9 36 12.69 402.54 B B5 10 OWN \n", + "10 36 13.49 305.38 C C1 0 RENT \n", + "11 36 9.91 96.68 B B1 3 RENT \n", + "\n", + " annual_inc verification_status loan_status purpose open_acc \\\n", + "0 24000.0 Verified 0 credit_card 3.0 \n", + "8 72000.0 Not Verified 0 debt_consolidation 14.0 \n", + "9 75000.0 Source Verified 0 debt_consolidation 12.0 \n", + "10 30000.0 Source Verified 1 debt_consolidation 4.0 \n", + "11 15000.0 Source Verified 0 credit_card 11.0 \n", + "\n", + " total_acc \n", + "0 9.0 \n", + "8 23.0 \n", + "9 34.0 \n", + "10 9.0 \n", + "11 11.0 " + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "preprocess_df = lending_club.preprocess(df)\n", "preprocess_df.head()" @@ -314,9 +762,189 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Performing binning with breaks_adj: {'loan_amnt': [5000, 10000, 15000, 20000, 25000], 'int_rate': [10, 15, 20], 'annual_inc': [50000, 100000, 150000]}\n", + "[INFO] creating woe binning ...\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n", + "Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n", + "Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n", + "Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n", + "Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[INFO] converting into woe values ...\n", + "Successfully converted features to WoE values.\n", + "Rows: 165695\n", + "Columns: 13\n", + "Missing values: 0\n", + "\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
loan_statusgrade_woesub_grade_woeopen_acc_woeverification_status_woehome_ownership_woeannual_inc_woepurpose_woeinstallment_woeemp_length_woeterm_woeint_rate_woetotal_acc_woe
00-0.396915-0.336648-0.1357840.1448950.1144610.272855-0.157770-0.191738-0.016348-0.215312-0.2023970.085175
800.1861880.3379160.023460-0.2437890.053303-0.0542310.051351-0.191738-0.0163480.654502-0.2023970.032958
90-0.396915-0.3366480.0234600.0893500.053303-0.0542310.0513510.128420-0.016348-0.215312-0.202397-0.101325
1010.186188-0.336648-0.1357840.0893500.1144610.2728550.051351-0.0133700.053758-0.215312-0.2023970.085175
110-0.396915-0.3366480.0234600.0893500.1144610.272855-0.157770-0.191738-0.016348-0.215312-1.0677450.085175
\n", + "
" + ], + "text/plain": [ + " loan_status grade_woe sub_grade_woe open_acc_woe \\\n", + "0 0 -0.396915 -0.336648 -0.135784 \n", + "8 0 0.186188 0.337916 0.023460 \n", + "9 0 -0.396915 -0.336648 0.023460 \n", + "10 1 0.186188 -0.336648 -0.135784 \n", + "11 0 -0.396915 -0.336648 0.023460 \n", + "\n", + " verification_status_woe home_ownership_woe annual_inc_woe purpose_woe \\\n", + "0 0.144895 0.114461 0.272855 -0.157770 \n", + "8 -0.243789 0.053303 -0.054231 0.051351 \n", + "9 0.089350 0.053303 -0.054231 0.051351 \n", + "10 0.089350 0.114461 0.272855 0.051351 \n", + "11 0.089350 0.114461 0.272855 -0.157770 \n", + "\n", + " installment_woe emp_length_woe term_woe int_rate_woe total_acc_woe \n", + "0 -0.191738 -0.016348 -0.215312 -0.202397 0.085175 \n", + "8 -0.191738 -0.016348 0.654502 -0.202397 0.032958 \n", + "9 0.128420 -0.016348 -0.215312 -0.202397 -0.101325 \n", + "10 -0.013370 0.053758 -0.215312 -0.202397 0.085175 \n", + "11 -0.191738 -0.016348 -0.215312 -1.067745 0.085175 " + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "fe_df = lending_club.feature_engineering(preprocess_df)\n", "fe_df.head()" @@ -337,9 +965,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "After splitting the dataset into training and test sets:\n", + "Training Dataset:\n", + "Rows: 132556\n", + "Columns: 13\n", + "Missing values: 0\n", + "\n", + "Test Dataset:\n", + "Rows: 33139\n", + "Columns: 13\n", + "Missing values: 0\n", + "\n" + ] + } + ], "source": [ "# Split the data\n", "train_df, test_df = lending_club.split(fe_df, test_size=0.2)\n", @@ -353,9 +999,53 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
XGBClassifier(base_score=None, booster=None, callbacks=None,\n",
+       "              colsample_bylevel=None, colsample_bynode=None,\n",
+       "              colsample_bytree=None, device=None, early_stopping_rounds=10,\n",
+       "              enable_categorical=False, eval_metric=['error', 'logloss', 'auc'],\n",
+       "              feature_types=None, gamma=None, grow_policy=None,\n",
+       "              importance_type=None, interaction_constraints=None,\n",
+       "              learning_rate=None, max_bin=None, max_cat_threshold=None,\n",
+       "              max_cat_to_onehot=None, max_delta_step=None, max_depth=None,\n",
+       "              max_leaves=None, min_child_weight=None, missing=nan,\n",
+       "              monotone_constraints=None, multi_strategy=None, n_estimators=50,\n",
+       "              n_jobs=None, num_parallel_tree=None, random_state=42, ...)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
" + ], + "text/plain": [ + "XGBClassifier(base_score=None, booster=None, callbacks=None,\n", + " colsample_bylevel=None, colsample_bynode=None,\n", + " colsample_bytree=None, device=None, early_stopping_rounds=10,\n", + " enable_categorical=False, eval_metric=['error', 'logloss', 'auc'],\n", + " feature_types=None, gamma=None, grow_policy=None,\n", + " importance_type=None, interaction_constraints=None,\n", + " learning_rate=None, max_bin=None, max_cat_threshold=None,\n", + " max_cat_to_onehot=None, max_delta_step=None, max_depth=None,\n", + " max_leaves=None, min_child_weight=None, missing=nan,\n", + " monotone_constraints=None, multi_strategy=None, n_estimators=50,\n", + " n_jobs=None, num_parallel_tree=None, random_state=42, ...)" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Define the XGBoost model\n", "xgb_model = xgb.XGBClassifier(\n", @@ -378,9 +1068,23 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/html": [ + "
RandomForestClassifier(n_estimators=50, random_state=42)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
" + ], + "text/plain": [ + "RandomForestClassifier(n_estimators=50, random_state=42)" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Define the Random Forest model\n", "rf_model = RandomForestClassifier(\n", @@ -594,9 +1298,18 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "2025-01-03 15:42:12,957 - INFO(validmind.vm_models.dataset.dataset): Extra column xgb_scores with 132556 values added to the dataset\n", + "2025-01-03 15:42:12,961 - INFO(validmind.vm_models.dataset.dataset): Extra column xgb_scores with 33139 values added to the dataset\n" + ] + } + ], "source": [ "train_xgb_scores = lending_club.compute_scores(train_xgb_prob)\n", "test_xgb_scores = lending_club.compute_scores(test_xgb_prob)\n", @@ -606,6 +1319,78 @@ "vm_test_ds.add_extra_column(\"xgb_scores\", test_xgb_scores)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Adding custom context to the LLM descriptions\n", + "\n", + "To enable the LLM descriptions context, you need to set the `VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED` environment variable to `1`. This will enable the LLM descriptions context, which will be used to provide additional context to the LLM descriptions. This is a global setting that will affect all tests." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ[\"VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED\"] = \"1\"\n", + "\n", + "context = \"\"\"\n", + "\n", + "FORMAT FOR THE LLM DESCRIPTIONS: \n", + " **** is designed to .\n", + "\n", + " The test operates by \n", + "\n", + " The primary advantages of this test include \n", + "\n", + " Users should be aware that \n", + "\n", + " **Key Insights:**\n", + "\n", + " The test results reveal:\n", + "\n", + " - ****: \n", + " - ****: \n", + " ...\n", + "\n", + " Based on these results, \n", + "\n", + "\n", + "ADDITIONAL INSTRUCTIONS:\n", + " Present insights in order from general to specific, with each insight as a single bullet point with bold title.\n", + "\n", + " Each insight should be self-contained and complete, avoiding sub-bullets or nested structures. \n", + " Your insights should progressively cover:\n", + " 1. Overall scope and distribution\n", + " 2. Complete breakdown of all elements with specific values\n", + " 3. Natural groupings and patterns\n", + " 4. Comparative analysis between datasets/categories\n", + " 5. Stability and variations\n", + " 6. Notable relationships or dependencies\n", + "\n", + " Remember:\n", + " - Keep all insights at the same level (no sub-bullets or nested structures)\n", + " - Make each insight complete and self-contained\n", + " - Include specific numerical values and ranges\n", + " - Cover all elements in the results comprehensively\n", + " - Maintain clear, concise language\n", + " - Use only \"- **Title**: Description\" format for insights\n", + " - Progress naturally from general to specific observations\n", + "\n", + "\"\"\".strip()\n", + "\n", + "os.environ[\"VALIDMIND_LLM_DESCRIPTIONS_CONTEXT\"] = context" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -1455,9 +2240,73 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "bea01e1bbc8a4ba487b60051fa698c73", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "VBox(children=(HTML(value=\"

Confusion Matrix

\\n\\n

Confusion Matrix is designed to e…" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "run=True\n", "if run:\n", diff --git a/validmind/tests/model_validation/sklearn/ConfusionMatrix.py b/validmind/tests/model_validation/sklearn/ConfusionMatrix.py index 8367fdde7..6d1db3f41 100644 --- a/validmind/tests/model_validation/sklearn/ConfusionMatrix.py +++ b/validmind/tests/model_validation/sklearn/ConfusionMatrix.py @@ -106,6 +106,7 @@ def ConfusionMatrix(dataset: VMDataset, model: VMModel): autosize=False, width=600, height=600, + title_text="Confusion Matrix", ) fig.add_annotation( diff --git a/validmind/tests/model_validation/statsmodels/CumulativePredictionProbabilities.py b/validmind/tests/model_validation/statsmodels/CumulativePredictionProbabilities.py index fa83f3a68..48fe9c878 100644 --- a/validmind/tests/model_validation/statsmodels/CumulativePredictionProbabilities.py +++ b/validmind/tests/model_validation/statsmodels/CumulativePredictionProbabilities.py @@ -9,22 +9,21 @@ from validmind import tags, tasks -@tags("visualization", "credit_risk", "logistic_regression") +@tags("visualization", "credit_risk") @tasks("classification") def CumulativePredictionProbabilities(dataset, model, title="Cumulative Probabilities"): """ - Visualizes cumulative probabilities of positive and negative classes for both training and testing in logistic - regression models. + Visualizes cumulative probabilities of positive and negative classes for both training and testing in classification models. ### Purpose This metric is utilized to evaluate the distribution of predicted probabilities for positive and negative classes - in a logistic regression model. It provides a visual assessment of the model's behavior by plotting the cumulative + in a classification model. It provides a visual assessment of the model's behavior by plotting the cumulative probabilities for positive and negative classes across both the training and test datasets. ### Test Mechanism - The logistic regression model is evaluated by first computing the predicted probabilities for each instance in both + The classification model is evaluated by first computing the predicted probabilities for each instance in both the training and test datasets, which are then added as a new column in these sets. The cumulative probabilities for positive and negative classes are subsequently calculated and sorted in ascending order. Cumulative distributions of these probabilities are created for both positive and negative classes across both training and @@ -51,7 +50,7 @@ def CumulativePredictionProbabilities(dataset, model, title="Cumulative Probabil ### Limitations - - Exclusive to classification tasks and specifically to logistic regression models. + - Exclusive to classification tasks and specifically to classification models. - Graphical results necessitate human interpretation and may not be directly applicable for automated risk detection. - The method does not give a solitary quantifiable measure of model risk, instead, it offers a visual diff --git a/validmind/tests/model_validation/statsmodels/PredictionProbabilitiesHistogram.py b/validmind/tests/model_validation/statsmodels/PredictionProbabilitiesHistogram.py index 42a6e5459..964ab5aca 100644 --- a/validmind/tests/model_validation/statsmodels/PredictionProbabilitiesHistogram.py +++ b/validmind/tests/model_validation/statsmodels/PredictionProbabilitiesHistogram.py @@ -9,7 +9,7 @@ from validmind import tags, tasks -@tags("visualization", "credit_risk", "logistic_regression") +@tags("visualization", "credit_risk") @tasks("classification") def PredictionProbabilitiesHistogram( dataset, model, title="Histogram of Predictive Probabilities" @@ -22,7 +22,7 @@ def PredictionProbabilitiesHistogram( The Prediction Probabilities Histogram test is designed to generate histograms displaying the Probability of Default (PD) predictions for both positive and negative classes in training and testing datasets. This helps in - evaluating the performance of a logistic regression model, particularly for credit risk prediction. + evaluating the performance of a classification model. ### Test Mechanism @@ -52,7 +52,6 @@ def PredictionProbabilitiesHistogram( ### Limitations - Specifically tailored for binary classification scenarios and not suited for multi-class classification tasks. - - Mainly applicable to logistic regression models, and may not be effective for other model types. - Provides a robust visual representation but lacks a quantifiable measure to assess model performance. """ From dd1dd7236c6c3863637b4a1b65d92666449cb9d1 Mon Sep 17 00:00:00 2001 From: Juan Date: Fri, 3 Jan 2025 18:42:05 +0100 Subject: [PATCH 05/10] Add ENV variable to input additional context to LLM-based test descriptions --- .../application_scorecard_full_suite.ipynb | 125 ++- .../application_scorecard_with_ml.ipynb | 894 +----------------- 2 files changed, 112 insertions(+), 907 deletions(-) diff --git a/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb b/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb index 965446378..1e956cc1a 100644 --- a/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb +++ b/notebooks/code_samples/credit_risk/application_scorecard_full_suite.ipynb @@ -16,55 +16,6 @@ "This interactive notebook provides a step-by-step guide for loading a demo dataset, preprocessing the raw data, training a model for testing, setting up test inputs, initializing the required ValidMind objects, running the test, and then logging the results to ValidMind." ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Contents \n", - "- [About ValidMind](#toc1_) \n", - " - [Before you begin](#toc1_1_) \n", - " - [New to ValidMind?](#toc1_2_) \n", - " - [Key concepts](#toc1_3_) \n", - "- [Install the ValidMind Library](#toc2_) \n", - "- [Initialize the ValidMind Library](#toc3_) \n", - " - [Get your code snippet](#toc3_1_) \n", - "- [Initialize the Python environment](#toc4_) \n", - " - [Preview the documentation template](#toc4_1_) \n", - "- [Load the sample dataset](#toc5_) \n", - " - [Prepocess the dataset](#toc5_1_) \n", - " - [Feature engineering](#toc5_2_) \n", - "- [Train the model](#toc6_) \n", - " - [Compute probabilities](#toc6_1_) \n", - " - [Compute binary predictions](#toc6_2_) \n", - " - [Compute scores](#toc6_3_) \n", - "- [Document the model](#toc7_) \n", - " - [Initialize the ValidMind datasets](#toc7_1_) \n", - " - [Initialize a model object](#toc7_2_) \n", - " - [Assign prediction values and probabilities to the datasets](#toc7_3_) \n", - " - [Assign scores to the datasets](#toc7_4_) \n", - " - [Data validation](#toc7_5_) \n", - " - [Run tests for raw data tests](#toc7_5_1_) \n", - " - [Run tests for preprocessed data](#toc7_5_2_) \n", - " - [Run tests for WoE analysis](#toc7_5_3_) \n", - " - [Model validation](#toc7_6_) \n", - " - [Run tests for model training](#toc7_6_1_) \n", - " - [Run tests for model evaluation](#toc7_6_2_) \n", - " - [Run tests for model explainability](#toc7_6_3_) \n", - "- [Next steps](#toc8_) \n", - " - [Work with your model documentation](#toc8_1_) \n", - " - [Discover more learning resources](#toc8_2_)\n", - "- [Upgrade ValidMind](#toc9_) \n", - "\n", - "\n", - "" - ] - }, { "cell_type": "markdown", "metadata": {}, @@ -605,6 +556,82 @@ "vm_test_ds.add_extra_column(\"xgb_scores\", test_xgb_scores)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Adding custom context to the LLM descriptions\n", + "\n", + "To enable the LLM descriptions context, you need to set the `VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED` environment variable to `1`. This will enable the LLM descriptions context, which will be used to provide additional context to the LLM descriptions. This is a global setting that will affect all tests." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ[\"VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED\"] = \"1\"\n", + "\n", + "context = \"\"\"\n", + "FORMAT FOR THE LLM DESCRIPTIONS: \n", + " **** is designed to .\n", + "\n", + " The test operates by \n", + "\n", + " The primary advantages of this test include \n", + "\n", + " Users should be aware that \n", + "\n", + " **Key Insights:**\n", + "\n", + " The test results reveal:\n", + "\n", + " - ****: \n", + " - ****: \n", + " ...\n", + "\n", + " Based on these results, \n", + "\n", + "ADDITIONAL INSTRUCTIONS:\n", + " Present insights in order from general to specific, with each insight as a single bullet point with bold title.\n", + "\n", + " For each metric in the test results, include in the test overview:\n", + " - The metric's purpose and what it measures\n", + " - Its mathematical formula in LaTeX notation\n", + " - The range of possible values\n", + " - What constitutes good/bad performance\n", + " - How to interpret different values\n", + "\n", + " Each insight should progressively cover:\n", + " 1. Overall scope and distribution\n", + " 2. Complete breakdown of all elements with specific values\n", + " 3. Natural groupings and patterns\n", + " 4. Comparative analysis between datasets/categories\n", + " 5. Stability and variations\n", + " 6. Notable relationships or dependencies\n", + "\n", + " Remember:\n", + " - Keep all insights at the same level (no sub-bullets or nested structures)\n", + " - Make each insight complete and self-contained\n", + " - Include specific numerical values and ranges\n", + " - Cover all elements in the results comprehensively\n", + " - Maintain clear, concise language\n", + " - Use only \"- **Title**: Description\" format for insights\n", + " - Progress naturally from general to specific observations\n", + "\n", + "\"\"\".strip()\n", + "\n", + "os.environ[\"VALIDMIND_LLM_DESCRIPTIONS_CONTEXT\"] = context" + ] + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb b/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb index 620edac77..03a6180b8 100644 --- a/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb +++ b/notebooks/code_samples/credit_risk/application_scorecard_with_ml.ipynb @@ -16,55 +16,6 @@ "This interactive notebook provides a step-by-step guide for loading a demo dataset, preprocessing the raw data, training a model for testing, setting up test inputs, initializing the required ValidMind objects, running the test, and then logging the results to ValidMind." ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Contents \n", - "- [About ValidMind](#toc1_) \n", - " - [Before you begin](#toc1_1_) \n", - " - [New to ValidMind?](#toc1_2_) \n", - " - [Key concepts](#toc1_3_) \n", - "- [Install the ValidMind Library](#toc2_) \n", - "- [Initialize the ValidMind Library](#toc3_) \n", - " - [Get your code snippet](#toc3_1_) \n", - "- [Initialize the Python environment](#toc4_) \n", - " - [Preview the documentation template](#toc4_1_) \n", - "- [Load the sample dataset](#toc5_) \n", - " - [Prepocess the dataset](#toc5_1_) \n", - " - [Feature engineering](#toc5_2_) \n", - "- [Train the model](#toc6_) \n", - " - [Compute probabilities](#toc6_1_) \n", - " - [Compute binary predictions](#toc6_2_) \n", - " - [Compute scores](#toc6_3_) \n", - "- [Document the model](#toc7_) \n", - " - [Initialize the ValidMind datasets](#toc7_1_) \n", - " - [Initialize a model object](#toc7_2_) \n", - " - [Assign prediction values and probabilities to the datasets](#toc7_3_) \n", - " - [Assign scores to the datasets](#toc7_4_) \n", - " - [Data validation](#toc7_5_) \n", - " - [Run tests for raw data tests](#toc7_5_1_) \n", - " - [Run tests for preprocessed data](#toc7_5_2_) \n", - " - [Run tests for WoE analysis](#toc7_5_3_) \n", - " - [Model validation](#toc7_6_) \n", - " - [Run tests for model training](#toc7_6_1_) \n", - " - [Run tests for model evaluation](#toc7_6_2_) \n", - " - [Run tests for model explainability](#toc7_6_3_) \n", - "- [Next steps](#toc8_) \n", - " - [Work with your model documentation](#toc8_1_) \n", - " - [Discover more learning resources](#toc8_2_)\n", - "- [Upgrade ValidMind](#toc9_) \n", - "\n", - "\n", - "" - ] - }, { "cell_type": "markdown", "metadata": {}, @@ -138,21 +89,9 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\u001b[33mWARNING: visions 0.7.6 does not provide the extra 'type-image-path'\u001b[0m\u001b[33m\n", - "\u001b[0m\n", - "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n", - "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n", - "Note: you may need to restart the kernel to use updated packages.\n" - ] - } - ], + "outputs": [], "source": [ "%pip install -q validmind" ] @@ -191,19 +130,9 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "2025-01-03 15:41:50,510 - INFO(validmind.api_client): 🎉 Connected to ValidMind!\n", - "📊 Model: [JM] Credit Risk Scorecard (ID: cm5gljv9100021nignfpbkvvc)\n", - "📁 Document Type: model_documentation\n" - ] - } - ], + "outputs": [], "source": [ "# Load your model identifier credentials from an `.env` file\n", "\n", @@ -263,73 +192,9 @@ }, { "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "aeda8e9baaca448e8e8ce41ceeadab8e", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Accordion(children=(HTML(value='

Empty Section

'), Accordion(children=(VBox(children=(HTML(value='\\n\n", - "import hljs from 'https://unpkg.com/@highlightjs/cdn-assets@11.9.0/es/highlight.min.js';\n", - "import python from 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/es/languages/python.min.js';\n", - "\n", - "hljs.registerLanguage('python', python);\n", - "hljs.highlightAll();\n", - "\n" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/html": [ - "\n", - "\n" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "vm.preview_template()" ] @@ -347,186 +212,9 @@ }, { "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Loading data from an offline .gz file: /Users/juanvalidmind/Dev/github/validmind/developer-framework/validmind/datasets/credit_risk/datasets/lending_club_loan_data_2007_2014_clean.csv.gz\n", - "Attempting to read from .gz file: /Users/juanvalidmind/Dev/github/validmind/developer-framework/validmind/datasets/credit_risk/datasets/lending_club_loan_data_2007_2014_clean.csv.gz\n", - "Data loaded successfully.\n", - "Rows: 227214, Columns: 16, Missing values: 8673\n" - ] - }, - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
loan_amntfunded_amnt_invtermint_rateinstallmentgradesub_gradeemp_lengthhome_ownershipannual_incverification_statusloan_statuspurposeopen_acctotal_acctotal_pymnt
050004975.036 months10.65162.87BB210+ yearsRENT24000.0Verified0.0credit_card3.09.05861.071414
125002500.060 months15.2759.83CC4< 1 yearRENT30000.0Source Verified1.0car3.04.01008.710000
224002400.036 months15.9684.33CC510+ yearsRENT12252.0Not Verified0.0small_business2.010.03003.653644
31000010000.036 months13.49339.31CC110+ yearsRENT49200.0Source Verified0.0other10.037.012226.302210
450005000.036 months7.90156.46AA43 yearsRENT36000.0Source Verified0.0wedding9.012.05631.377753
\n", - "
" - ], - "text/plain": [ - " loan_amnt funded_amnt_inv term int_rate installment grade \\\n", - "0 5000 4975.0 36 months 10.65 162.87 B \n", - "1 2500 2500.0 60 months 15.27 59.83 C \n", - "2 2400 2400.0 36 months 15.96 84.33 C \n", - "3 10000 10000.0 36 months 13.49 339.31 C \n", - "4 5000 5000.0 36 months 7.90 156.46 A \n", - "\n", - " sub_grade emp_length home_ownership annual_inc verification_status \\\n", - "0 B2 10+ years RENT 24000.0 Verified \n", - "1 C4 < 1 year RENT 30000.0 Source Verified \n", - "2 C5 10+ years RENT 12252.0 Not Verified \n", - "3 C1 10+ years RENT 49200.0 Source Verified \n", - "4 A4 3 years RENT 36000.0 Source Verified \n", - "\n", - " loan_status purpose open_acc total_acc total_pymnt \n", - "0 0.0 credit_card 3.0 9.0 5861.071414 \n", - "1 1.0 car 3.0 4.0 1008.710000 \n", - "2 0.0 small_business 2.0 10.0 3003.653644 \n", - "3 0.0 other 10.0 37.0 12226.302210 \n", - "4 0.0 wedding 9.0 12.0 5631.377753 " - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "df = lending_club.load_data(source=\"offline\")\n", "\n", @@ -552,194 +240,9 @@ }, { "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Filtering 'purpose' to 'debt_consolidation' and 'credit_card':\n", - "Rows: 177825\n", - "Columns: 16\n", - "Missing values: 6507\n", - "\n", - "Filtering out 'grade' F and G:\n", - "Rows: 172165\n", - "Columns: 16\n", - "Missing values: 6352\n", - "\n", - "Filtering out 'sub_grade' F and G:\n", - "Rows: 172165\n", - "Columns: 16\n", - "Missing values: 6352\n", - "\n", - "Filtering out 'home_ownership' OTHER, NONE, ANY:\n", - "Rows: 172045\n", - "Columns: 16\n", - "Missing values: 6350\n", - "\n", - "Dropping specified features:\n", - "Rows: 172045\n", - "Columns: 13\n", - "Missing values: 6350\n", - "\n", - "Dropping rows with any missing values:\n", - "Rows: 165695\n", - "Columns: 13\n", - "Missing values: 0\n", - "\n" - ] - }, - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
termint_rateinstallmentgradesub_gradeemp_lengthhome_ownershipannual_incverification_statusloan_statuspurposeopen_acctotal_acc
03610.65162.87BB210RENT24000.0Verified0credit_card3.09.0
86014.65153.45CC35OWN72000.0Not Verified0debt_consolidation14.023.0
93612.69402.54BB510OWN75000.0Source Verified0debt_consolidation12.034.0
103613.49305.38CC10RENT30000.0Source Verified1debt_consolidation4.09.0
11369.9196.68BB13RENT15000.0Source Verified0credit_card11.011.0
\n", - "
" - ], - "text/plain": [ - " term int_rate installment grade sub_grade emp_length home_ownership \\\n", - "0 36 10.65 162.87 B B2 10 RENT \n", - "8 60 14.65 153.45 C C3 5 OWN \n", - "9 36 12.69 402.54 B B5 10 OWN \n", - "10 36 13.49 305.38 C C1 0 RENT \n", - "11 36 9.91 96.68 B B1 3 RENT \n", - "\n", - " annual_inc verification_status loan_status purpose open_acc \\\n", - "0 24000.0 Verified 0 credit_card 3.0 \n", - "8 72000.0 Not Verified 0 debt_consolidation 14.0 \n", - "9 75000.0 Source Verified 0 debt_consolidation 12.0 \n", - "10 30000.0 Source Verified 1 debt_consolidation 4.0 \n", - "11 15000.0 Source Verified 0 credit_card 11.0 \n", - "\n", - " total_acc \n", - "0 9.0 \n", - "8 23.0 \n", - "9 34.0 \n", - "10 9.0 \n", - "11 11.0 " - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "preprocess_df = lending_club.preprocess(df)\n", "preprocess_df.head()" @@ -762,189 +265,9 @@ }, { "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Performing binning with breaks_adj: {'loan_amnt': [5000, 10000, 15000, 20000, 25000], 'int_rate': [10, 15, 20], 'annual_inc': [50000, 100000, 150000]}\n", - "[INFO] creating woe binning ...\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n", - "Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n", - "Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n", - "Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n", - "Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[INFO] converting into woe values ...\n", - "Successfully converted features to WoE values.\n", - "Rows: 165695\n", - "Columns: 13\n", - "Missing values: 0\n", - "\n" - ] - }, - { - "data": { - "text/html": [ - "
\n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
loan_statusgrade_woesub_grade_woeopen_acc_woeverification_status_woehome_ownership_woeannual_inc_woepurpose_woeinstallment_woeemp_length_woeterm_woeint_rate_woetotal_acc_woe
00-0.396915-0.336648-0.1357840.1448950.1144610.272855-0.157770-0.191738-0.016348-0.215312-0.2023970.085175
800.1861880.3379160.023460-0.2437890.053303-0.0542310.051351-0.191738-0.0163480.654502-0.2023970.032958
90-0.396915-0.3366480.0234600.0893500.053303-0.0542310.0513510.128420-0.016348-0.215312-0.202397-0.101325
1010.186188-0.336648-0.1357840.0893500.1144610.2728550.051351-0.0133700.053758-0.215312-0.2023970.085175
110-0.396915-0.3366480.0234600.0893500.1144610.272855-0.157770-0.191738-0.016348-0.215312-1.0677450.085175
\n", - "
" - ], - "text/plain": [ - " loan_status grade_woe sub_grade_woe open_acc_woe \\\n", - "0 0 -0.396915 -0.336648 -0.135784 \n", - "8 0 0.186188 0.337916 0.023460 \n", - "9 0 -0.396915 -0.336648 0.023460 \n", - "10 1 0.186188 -0.336648 -0.135784 \n", - "11 0 -0.396915 -0.336648 0.023460 \n", - "\n", - " verification_status_woe home_ownership_woe annual_inc_woe purpose_woe \\\n", - "0 0.144895 0.114461 0.272855 -0.157770 \n", - "8 -0.243789 0.053303 -0.054231 0.051351 \n", - "9 0.089350 0.053303 -0.054231 0.051351 \n", - "10 0.089350 0.114461 0.272855 0.051351 \n", - "11 0.089350 0.114461 0.272855 -0.157770 \n", - "\n", - " installment_woe emp_length_woe term_woe int_rate_woe total_acc_woe \n", - "0 -0.191738 -0.016348 -0.215312 -0.202397 0.085175 \n", - "8 -0.191738 -0.016348 0.654502 -0.202397 0.032958 \n", - "9 0.128420 -0.016348 -0.215312 -0.202397 -0.101325 \n", - "10 -0.013370 0.053758 -0.215312 -0.202397 0.085175 \n", - "11 -0.191738 -0.016348 -0.215312 -1.067745 0.085175 " - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "fe_df = lending_club.feature_engineering(preprocess_df)\n", "fe_df.head()" @@ -965,27 +288,9 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "After splitting the dataset into training and test sets:\n", - "Training Dataset:\n", - "Rows: 132556\n", - "Columns: 13\n", - "Missing values: 0\n", - "\n", - "Test Dataset:\n", - "Rows: 33139\n", - "Columns: 13\n", - "Missing values: 0\n", - "\n" - ] - } - ], + "outputs": [], "source": [ "# Split the data\n", "train_df, test_df = lending_club.split(fe_df, test_size=0.2)\n", @@ -999,53 +304,9 @@ }, { "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
XGBClassifier(base_score=None, booster=None, callbacks=None,\n",
-       "              colsample_bylevel=None, colsample_bynode=None,\n",
-       "              colsample_bytree=None, device=None, early_stopping_rounds=10,\n",
-       "              enable_categorical=False, eval_metric=['error', 'logloss', 'auc'],\n",
-       "              feature_types=None, gamma=None, grow_policy=None,\n",
-       "              importance_type=None, interaction_constraints=None,\n",
-       "              learning_rate=None, max_bin=None, max_cat_threshold=None,\n",
-       "              max_cat_to_onehot=None, max_delta_step=None, max_depth=None,\n",
-       "              max_leaves=None, min_child_weight=None, missing=nan,\n",
-       "              monotone_constraints=None, multi_strategy=None, n_estimators=50,\n",
-       "              n_jobs=None, num_parallel_tree=None, random_state=42, ...)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
" - ], - "text/plain": [ - "XGBClassifier(base_score=None, booster=None, callbacks=None,\n", - " colsample_bylevel=None, colsample_bynode=None,\n", - " colsample_bytree=None, device=None, early_stopping_rounds=10,\n", - " enable_categorical=False, eval_metric=['error', 'logloss', 'auc'],\n", - " feature_types=None, gamma=None, grow_policy=None,\n", - " importance_type=None, interaction_constraints=None,\n", - " learning_rate=None, max_bin=None, max_cat_threshold=None,\n", - " max_cat_to_onehot=None, max_delta_step=None, max_depth=None,\n", - " max_leaves=None, min_child_weight=None, missing=nan,\n", - " monotone_constraints=None, multi_strategy=None, n_estimators=50,\n", - " n_jobs=None, num_parallel_tree=None, random_state=42, ...)" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "# Define the XGBoost model\n", "xgb_model = xgb.XGBClassifier(\n", @@ -1068,23 +329,9 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
RandomForestClassifier(n_estimators=50, random_state=42)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
" - ], - "text/plain": [ - "RandomForestClassifier(n_estimators=50, random_state=42)" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "# Define the Random Forest model\n", "rf_model = RandomForestClassifier(\n", @@ -1298,18 +545,9 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "2025-01-03 15:42:12,957 - INFO(validmind.vm_models.dataset.dataset): Extra column xgb_scores with 132556 values added to the dataset\n", - "2025-01-03 15:42:12,961 - INFO(validmind.vm_models.dataset.dataset): Extra column xgb_scores with 33139 values added to the dataset\n" - ] - } - ], + "outputs": [], "source": [ "train_xgb_scores = lending_club.compute_scores(train_xgb_prob)\n", "test_xgb_scores = lending_club.compute_scores(test_xgb_prob)\n", @@ -1338,7 +576,6 @@ "os.environ[\"VALIDMIND_LLM_DESCRIPTIONS_CONTEXT_ENABLED\"] = \"1\"\n", "\n", "context = \"\"\"\n", - "\n", "FORMAT FOR THE LLM DESCRIPTIONS: \n", " **** is designed to .\n", @@ -1364,12 +601,17 @@ " Based on these results, \n", "\n", - "\n", "ADDITIONAL INSTRUCTIONS:\n", " Present insights in order from general to specific, with each insight as a single bullet point with bold title.\n", "\n", - " Each insight should be self-contained and complete, avoiding sub-bullets or nested structures. \n", - " Your insights should progressively cover:\n", + " For each metric in the test results, include in the test overview:\n", + " - The metric's purpose and what it measures\n", + " - Its mathematical formula in LaTeX notation\n", + " - The range of possible values\n", + " - What constitutes good/bad performance\n", + " - How to interpret different values\n", + "\n", + " Each insight should progressively cover:\n", " 1. Overall scope and distribution\n", " 2. Complete breakdown of all elements with specific values\n", " 3. Natural groupings and patterns\n", @@ -2240,73 +1482,9 @@ }, { "cell_type": "code", - "execution_count": 18, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "bea01e1bbc8a4ba487b60051fa698c73", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "VBox(children=(HTML(value=\"

Confusion Matrix

\\n\\n

Confusion Matrix is designed to e…" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/html": [ - "\n", - "\n" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/html": [ - "\n", - "\n" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "run=True\n", "if run:\n", From 51009b681680e0b7b1533f4d18d1cdbede48746d Mon Sep 17 00:00:00 2001 From: Juan Date: Fri, 3 Jan 2025 21:19:17 +0100 Subject: [PATCH 06/10] Fix unit tests --- tests/test_integration_tests.py | 5 +++++ .../data_validation/test_TooManyZeroValues.py | 19 +++++++++++-------- .../data_validation/TooManyZeroValues.py | 9 +++++---- .../sklearn/HyperParametersTuning.py | 15 +++++++++++---- 4 files changed, 32 insertions(+), 16 deletions(-) diff --git a/tests/test_integration_tests.py b/tests/test_integration_tests.py index 82e83fc36..95943809c 100644 --- a/tests/test_integration_tests.py +++ b/tests/test_integration_tests.py @@ -44,6 +44,11 @@ "validmind.data_validation.ProtectedClassesCombination", "validmind.data_validation.ProtectedClassesDisparity", "validmind.data_validation.ProtectedClassesThresholdOptimizer", + # The customer churn classification dataset contains a string column 'Germany' which is not supported by the MutualInformation test + "validmind.data_validation.MutualInformation", + # The required column 'score' is not present in the dataset with input_id test_dataset + "validmind.data_validation.ScoreBandDefaultRates", + "validmind.data_validation.ScoreProbabilityAlignment", ] SKIPPED_TESTS = [] SUCCESSFUL_TESTS = [] diff --git a/tests/unit_tests/data_validation/test_TooManyZeroValues.py b/tests/unit_tests/data_validation/test_TooManyZeroValues.py index 121238f2b..d1b0d3356 100644 --- a/tests/unit_tests/data_validation/test_TooManyZeroValues.py +++ b/tests/unit_tests/data_validation/test_TooManyZeroValues.py @@ -37,7 +37,7 @@ def setUp(self): ) def test_too_many_zeros_default_threshold(self): - # Test with default threshold (3%) + # Test with default threshold (0.03 or 0.03%) results, passed = TooManyZeroValues(self.vm_dataset) # Check return types @@ -47,22 +47,25 @@ def test_too_many_zeros_default_threshold(self): # Check results structure self.assertEqual(len(results), 2) # Should only check numeric columns for result in results: - self.assertIn("Column", result) + self.assertIn("Variable", result) + self.assertIn("Row Count", result) self.assertIn("Number of Zero Values", result) self.assertIn("Percentage of Zero Values (%)", result) self.assertIn("Pass/Fail", result) # Verify specific results - few_zeros_result = next(r for r in results if r["Column"] == "few_zeros") - many_zeros_result = next(r for r in results if r["Column"] == "many_zeros") + few_zeros_result = next(r for r in results if r["Variable"] == "few_zeros") + many_zeros_result = next(r for r in results if r["Variable"] == "many_zeros") - self.assertEqual(few_zeros_result["Pass/Fail"], "Pass") # 1% should pass - self.assertEqual(many_zeros_result["Pass/Fail"], "Fail") # 5% should fail - self.assertFalse(passed) # Overall test should fail due to many_zeros + # 1% should fail as it's > 0.03% + self.assertEqual(few_zeros_result["Pass/Fail"], "Fail") + # 5% should fail as it's > 0.03% + self.assertEqual(many_zeros_result["Pass/Fail"], "Fail") + self.assertFalse(passed) # Overall test should fail as both columns fail def test_custom_threshold(self): # Test with higher threshold (6%) - results, passed = TooManyZeroValues(self.vm_dataset, max_percent_threshold=0.06) + results, passed = TooManyZeroValues(self.vm_dataset, max_percent_threshold=6) # Both columns should pass with higher threshold self.assertTrue(passed) diff --git a/validmind/tests/data_validation/TooManyZeroValues.py b/validmind/tests/data_validation/TooManyZeroValues.py index 1adf5a811..539f3f424 100644 --- a/validmind/tests/data_validation/TooManyZeroValues.py +++ b/validmind/tests/data_validation/TooManyZeroValues.py @@ -61,24 +61,25 @@ def TooManyZeroValues(dataset: VMDataset, max_percent_threshold: float = 0.03): issues. """ df = dataset.df - table = [] for col in dataset.feature_columns_numeric: value_counts = df[col].value_counts() + row_count = df.shape[0] if 0 not in value_counts.index: continue n_zeros = value_counts[0] - p_zeros = (n_zeros / df.shape[0]) * 100 + p_zeros = (n_zeros / row_count) * 100 table.append( { - "Column": col, + "Variable": col, + "Row Count": row_count, "Number of Zero Values": n_zeros, "Percentage of Zero Values (%)": p_zeros, - "Pass/Fail": "Pass" if p_zeros < max_percent_threshold else "Fail", + "Pass/Fail": ("Pass" if p_zeros < (max_percent_threshold) else "Fail"), } ) diff --git a/validmind/tests/model_validation/sklearn/HyperParametersTuning.py b/validmind/tests/model_validation/sklearn/HyperParametersTuning.py index 12a28ee04..e439c9e99 100644 --- a/validmind/tests/model_validation/sklearn/HyperParametersTuning.py +++ b/validmind/tests/model_validation/sklearn/HyperParametersTuning.py @@ -23,8 +23,8 @@ def HyperParametersTuning( model: VMModel, dataset: VMDataset, param_grid: dict, - scoring: Union[str, List, Dict], - thresholds: Union[float, List[float]] = 0.5, + scoring: Union[str, List, Dict] = None, + thresholds: Union[float, List[float]] = None, fit_params: dict = None, ): """ @@ -79,14 +79,21 @@ def HyperParametersTuning( - Resource intensive for high-dimensional parameter spaces """ results = [] + + # Handle default scoring + if scoring is None: + scoring = "accuracy" # Default to accuracy as the scoring metric + metrics = ( scoring if isinstance(scoring, list) else list(scoring.keys()) if isinstance(scoring, dict) else [scoring] ) - # Convert single threshold to list - if isinstance(thresholds, (int, float)): + # Handle default threshold + if thresholds is None: + thresholds = [0.5] # Default to standard 0.5 threshold + elif isinstance(thresholds, (int, float)): thresholds = [thresholds] # For each threshold From baed1e6caf73a673387a799cee492a5a87ba406d Mon Sep 17 00:00:00 2001 From: Juan Date: Fri, 3 Jan 2025 21:55:15 +0100 Subject: [PATCH 07/10] Fix integration tests and HyperParametersTuning --- tests/test_integration_tests.py | 2 +- .../sklearn/HyperParametersTuning.py | 26 +++++++++++-------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/tests/test_integration_tests.py b/tests/test_integration_tests.py index 95943809c..6da9996c3 100644 --- a/tests/test_integration_tests.py +++ b/tests/test_integration_tests.py @@ -48,7 +48,7 @@ "validmind.data_validation.MutualInformation", # The required column 'score' is not present in the dataset with input_id test_dataset "validmind.data_validation.ScoreBandDefaultRates", - "validmind.data_validation.ScoreProbabilityAlignment", + "validmind.model_validation.sklearn.ScoreProbabilityAlignment", ] SKIPPED_TESTS = [] SUCCESSFUL_TESTS = [] diff --git a/validmind/tests/model_validation/sklearn/HyperParametersTuning.py b/validmind/tests/model_validation/sklearn/HyperParametersTuning.py index e439c9e99..8635cf705 100644 --- a/validmind/tests/model_validation/sklearn/HyperParametersTuning.py +++ b/validmind/tests/model_validation/sklearn/HyperParametersTuning.py @@ -18,7 +18,7 @@ def custom_recall(y_true, y_pred_proba, threshold=0.5): @tags("sklearn", "model_performance") -@tasks("classification", "clustering") +@tasks("clustering", "classification") def HyperParametersTuning( model: VMModel, dataset: VMDataset, @@ -100,22 +100,26 @@ def HyperParametersTuning( for threshold in thresholds: # Create scoring dict with current threshold scoring_dict = {} - for metric in metrics: - if metric == "recall": - scoring_dict[metric] = make_scorer( - custom_recall, needs_proba=True, threshold=threshold - ) - elif metric == "roc_auc": - scoring_dict[metric] = "roc_auc" # threshold independent - # Add other metrics as needed + if scoring is not None: # Only create scoring_dict if scoring was provided + for metric in metrics: + if metric == "recall": + scoring_dict[metric] = make_scorer( + custom_recall, needs_proba=True, threshold=threshold + ) + elif metric == "roc_auc": + scoring_dict[metric] = "roc_auc" # threshold independent + else: + scoring_dict[metric] = metric # Run GridSearchCV for each optimization metric for optimize_for in metrics: estimators = GridSearchCV( model.model, param_grid=param_grid, - scoring=scoring_dict, - refit=optimize_for, # Optimize for current metric + scoring=( + scoring_dict if scoring_dict else None + ), # Use None if no scoring provided + refit=optimize_for, ) # Fit model From 3c349002d05baefa82d1221a3e02bfdf9b52f60c Mon Sep 17 00:00:00 2001 From: Juan Date: Fri, 3 Jan 2025 22:37:37 +0100 Subject: [PATCH 08/10] Fix lint --- .../sklearn/HyperParametersTuning.py | 73 +++++++++++-------- 1 file changed, 41 insertions(+), 32 deletions(-) diff --git a/validmind/tests/model_validation/sklearn/HyperParametersTuning.py b/validmind/tests/model_validation/sklearn/HyperParametersTuning.py index 8635cf705..d4adb41d1 100644 --- a/validmind/tests/model_validation/sklearn/HyperParametersTuning.py +++ b/validmind/tests/model_validation/sklearn/HyperParametersTuning.py @@ -17,6 +17,42 @@ def custom_recall(y_true, y_pred_proba, threshold=0.5): return recall_score(y_true, y_pred) +def _get_metrics(scoring): + """Convert scoring parameter to list of metrics.""" + if scoring is None: + return ["accuracy"] + return ( + scoring + if isinstance(scoring, list) + else list(scoring.keys()) if isinstance(scoring, dict) else [scoring] + ) + + +def _get_thresholds(thresholds): + """Convert thresholds parameter to list.""" + if thresholds is None: + return [0.5] + return [thresholds] if isinstance(thresholds, (int, float)) else thresholds + + +def _create_scoring_dict(scoring, metrics, threshold): + """Create scoring dictionary for GridSearchCV.""" + if scoring is None: + return None + + scoring_dict = {} + for metric in metrics: + if metric == "recall": + scoring_dict[metric] = make_scorer( + custom_recall, needs_proba=True, threshold=threshold + ) + elif metric == "roc_auc": + scoring_dict[metric] = "roc_auc" + else: + scoring_dict[metric] = metric + return scoring_dict + + @tags("sklearn", "model_performance") @tasks("clustering", "classification") def HyperParametersTuning( @@ -79,51 +115,24 @@ def HyperParametersTuning( - Resource intensive for high-dimensional parameter spaces """ results = [] - - # Handle default scoring - if scoring is None: - scoring = "accuracy" # Default to accuracy as the scoring metric - - metrics = ( - scoring - if isinstance(scoring, list) - else list(scoring.keys()) if isinstance(scoring, dict) else [scoring] - ) - - # Handle default threshold - if thresholds is None: - thresholds = [0.5] # Default to standard 0.5 threshold - elif isinstance(thresholds, (int, float)): - thresholds = [thresholds] + metrics = _get_metrics(scoring) + thresholds = _get_thresholds(thresholds) + fit_params = fit_params or {} # For each threshold for threshold in thresholds: - # Create scoring dict with current threshold - scoring_dict = {} - if scoring is not None: # Only create scoring_dict if scoring was provided - for metric in metrics: - if metric == "recall": - scoring_dict[metric] = make_scorer( - custom_recall, needs_proba=True, threshold=threshold - ) - elif metric == "roc_auc": - scoring_dict[metric] = "roc_auc" # threshold independent - else: - scoring_dict[metric] = metric + scoring_dict = _create_scoring_dict(scoring, metrics, threshold) # Run GridSearchCV for each optimization metric for optimize_for in metrics: estimators = GridSearchCV( model.model, param_grid=param_grid, - scoring=( - scoring_dict if scoring_dict else None - ), # Use None if no scoring provided + scoring=scoring_dict, refit=optimize_for, ) # Fit model - fit_params = fit_params or {} estimators.fit(dataset.x_df(), dataset.y, **fit_params) # Get results for this optimization From f2cda085642c16d5d52383ecf5d8bc761a4b4da4 Mon Sep 17 00:00:00 2001 From: Juan Date: Fri, 3 Jan 2025 23:01:38 +0100 Subject: [PATCH 09/10] Fix HyperParametersTuning --- .../sklearn/HyperParametersTuning.py | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/validmind/tests/model_validation/sklearn/HyperParametersTuning.py b/validmind/tests/model_validation/sklearn/HyperParametersTuning.py index d4adb41d1..1e9e30acf 100644 --- a/validmind/tests/model_validation/sklearn/HyperParametersTuning.py +++ b/validmind/tests/model_validation/sklearn/HyperParametersTuning.py @@ -114,28 +114,37 @@ def HyperParametersTuning( - Grid search may miss optimal values between grid points - Resource intensive for high-dimensional parameter spaces """ + fit_params = fit_params or {} + + # Simple case: no scoring and no thresholds + if scoring is None and thresholds is None: + estimators = GridSearchCV(model.model, param_grid=param_grid, scoring=None) + estimators.fit(dataset.x_df(), dataset.y, **fit_params) + return [ + { + "Best Model": estimators.best_estimator_, + "Best Parameters": estimators.best_params_, + } + ] + + # Complex case: with scoring or thresholds results = [] metrics = _get_metrics(scoring) thresholds = _get_thresholds(thresholds) - fit_params = fit_params or {} - # For each threshold for threshold in thresholds: scoring_dict = _create_scoring_dict(scoring, metrics, threshold) - # Run GridSearchCV for each optimization metric for optimize_for in metrics: estimators = GridSearchCV( model.model, param_grid=param_grid, scoring=scoring_dict, - refit=optimize_for, + refit=optimize_for if scoring is not None else True, ) - # Fit model estimators.fit(dataset.x_df(), dataset.y, **fit_params) - # Get results for this optimization best_index = estimators.best_index_ row_result = { "Optimized for": optimize_for, @@ -143,11 +152,10 @@ def HyperParametersTuning( "Best Parameters": estimators.best_params_, } - # Add scores for all metrics - for metric in metrics: - row_result[f"{metric}"] = estimators.cv_results_[f"mean_test_{metric}"][ - best_index - ] + score_key = ( + "mean_test_score" if scoring is None else f"mean_test_{optimize_for}" + ) + row_result[optimize_for] = estimators.cv_results_[score_key][best_index] results.append(row_result) From 58d1a1a62c6a5f63d70bbb2a94f819abdc82c142 Mon Sep 17 00:00:00 2001 From: Juan Date: Fri, 3 Jan 2025 23:23:29 +0100 Subject: [PATCH 10/10] 2.7.4 --- pyproject.toml | 2 +- validmind/__version__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 2eb972312..8c8e86fa4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ description = "ValidMind Library" license = "Commercial License" name = "validmind" readme = "README.pypi.md" -version = "2.7.3" +version = "2.7.4" [tool.poetry.dependencies] aiohttp = {extras = ["speedups"], version = "*"} diff --git a/validmind/__version__.py b/validmind/__version__.py index 573a7705c..e617a4c52 100644 --- a/validmind/__version__.py +++ b/validmind/__version__.py @@ -1 +1 @@ -__version__ = "2.7.3" +__version__ = "2.7.4"