• Documentation
    • About ​ValidMind
    • Get Started
    • Guides
    • Support
    • Releases

    • Python Library
    • ValidMind Library

    • ValidMind Academy
    • Training Courses
  • Documentation
    • About ​ValidMind
    • Get Started
    • Guides
    • Support
    • Releases

    • Python Library
    • ValidMind Library

    • ValidMind Academy
    • Training Courses
  • Log In
    • Public Internet
    • ValidMind Platform · US1
    • ValidMind Platform · CA1

    • Private Link
    • Virtual Private ValidMind (VPV)

    • Which login should I use?
  1. Run tests & test suites
  2. Load dataset predictions
  • ValidMind Library
  • Supported models

  • Quickstart
  • Quickstart for model documentation
  • Quickstart for model validation
  • Install and initialize ValidMind Library
  • Store model credentials in .env files

  • Model Development
  • 1 — Set up ValidMind Library
  • 2 — Start model development process
  • 3 — Integrate custom tests
  • 4 — Finalize testing & documentation

  • Model Validation
  • 1 — Set up ValidMind Library for validation
  • 2 — Start model validation process
  • 3 — Developing a challenger model
  • 4 — Finalize validation & reporting

  • Model Testing
  • Run tests & test suites
    • Add context to LLM-generated test descriptions
    • Intro to Assign Scores
    • Configure dataset features
    • Document multiple results for the same test
    • Explore test suites
    • Explore tests
    • Dataset Column Filters when Running Tests
    • Load dataset predictions
    • Log metrics over time
    • Run individual documentation sections
    • Run documentation tests with custom configurations
    • Run tests with multiple datasets
    • Intro to Unit Metrics
    • Understand and utilize RawData in ValidMind tests
    • Introduction to ValidMind Dataset and Model Objects
    • Run Tests
      • Run dataset based tests
      • Run comparison tests
  • Test descriptions
    • Data Validation
      • ACFandPACFPlot
      • ADF
      • AutoAR
      • AutoMA
      • AutoStationarity
      • BivariateScatterPlots
      • BoxPierce
      • ChiSquaredFeaturesTable
      • ClassImbalance
      • DatasetDescription
      • DatasetSplit
      • DescriptiveStatistics
      • DickeyFullerGLS
      • Duplicates
      • EngleGrangerCoint
      • FeatureTargetCorrelationPlot
      • HighCardinality
      • HighPearsonCorrelation
      • IQROutliersBarPlot
      • IQROutliersTable
      • IsolationForestOutliers
      • JarqueBera
      • KPSS
      • LaggedCorrelationHeatmap
      • LJungBox
      • MissingValues
      • MissingValuesBarPlot
      • MutualInformation
      • PearsonCorrelationMatrix
      • PhillipsPerronArch
      • ProtectedClassesCombination
      • ProtectedClassesDescription
      • ProtectedClassesDisparity
      • ProtectedClassesThresholdOptimizer
      • RollingStatsPlot
      • RunsTest
      • ScatterPlot
      • ScoreBandDefaultRates
      • SeasonalDecompose
      • ShapiroWilk
      • Skewness
      • SpreadPlot
      • TabularCategoricalBarPlots
      • TabularDateTimeHistograms
      • TabularDescriptionTables
      • TabularNumericalHistograms
      • TargetRateBarPlots
      • TimeSeriesDescription
      • TimeSeriesDescriptiveStatistics
      • TimeSeriesFrequency
      • TimeSeriesHistogram
      • TimeSeriesLinePlot
      • TimeSeriesMissingValues
      • TimeSeriesOutliers
      • TooManyZeroValues
      • UniqueRows
      • WOEBinPlots
      • WOEBinTable
      • ZivotAndrewsArch
      • Nlp
        • CommonWords
        • Hashtags
        • LanguageDetection
        • Mentions
        • PolarityAndSubjectivity
        • Punctuations
        • Sentiment
        • StopWords
        • TextDescription
        • Toxicity
    • Model Validation
      • BertScore
      • BleuScore
      • ClusterSizeDistribution
      • ContextualRecall
      • FeaturesAUC
      • MeteorScore
      • ModelMetadata
      • ModelPredictionResiduals
      • RegardScore
      • RegressionResidualsPlot
      • RougeScore
      • TimeSeriesPredictionsPlot
      • TimeSeriesPredictionWithCI
      • TimeSeriesR2SquareBySegments
      • TokenDisparity
      • ToxicityScore
      • Embeddings
        • ClusterDistribution
        • CosineSimilarityComparison
        • CosineSimilarityDistribution
        • CosineSimilarityHeatmap
        • DescriptiveAnalytics
        • EmbeddingsVisualization2D
        • EuclideanDistanceComparison
        • EuclideanDistanceHeatmap
        • PCAComponentsPairwisePlots
        • StabilityAnalysisKeyword
        • StabilityAnalysisRandomNoise
        • StabilityAnalysisSynonyms
        • StabilityAnalysisTranslation
        • TSNEComponentsPairwisePlots
      • Ragas
        • AnswerCorrectness
        • AspectCritic
        • ContextEntityRecall
        • ContextPrecision
        • ContextPrecisionWithoutReference
        • ContextRecall
        • Faithfulness
        • NoiseSensitivity
        • ResponseRelevancy
        • SemanticSimilarity
      • Sklearn
        • AdjustedMutualInformation
        • AdjustedRandIndex
        • CalibrationCurve
        • ClassifierPerformance
        • ClassifierThresholdOptimization
        • ClusterCosineSimilarity
        • ClusterPerformanceMetrics
        • CompletenessScore
        • ConfusionMatrix
        • FeatureImportance
        • FowlkesMallowsScore
        • HomogeneityScore
        • HyperParametersTuning
        • KMeansClustersOptimization
        • MinimumAccuracy
        • MinimumF1Score
        • MinimumROCAUCScore
        • ModelParameters
        • ModelsPerformanceComparison
        • OverfitDiagnosis
        • PermutationFeatureImportance
        • PopulationStabilityIndex
        • PrecisionRecallCurve
        • RegressionErrors
        • RegressionErrorsComparison
        • RegressionPerformance
        • RegressionR2Square
        • RegressionR2SquareComparison
        • RobustnessDiagnosis
        • ROCCurve
        • ScoreProbabilityAlignment
        • SHAPGlobalImportance
        • SilhouettePlot
        • TrainingTestDegradation
        • VMeasure
        • WeakspotsDiagnosis
      • Statsmodels
        • AutoARIMA
        • CumulativePredictionProbabilities
        • DurbinWatsonTest
        • GINITable
        • KolmogorovSmirnov
        • Lilliefors
        • PredictionProbabilitiesHistogram
        • RegressionCoeffs
        • RegressionFeatureSignificance
        • RegressionModelForecastPlot
        • RegressionModelForecastPlotLevels
        • RegressionModelSensitivityPlot
        • RegressionModelSummary
        • RegressionPermutationFeatureImportance
        • ScorecardHistogram
    • Ongoing Monitoring
      • CalibrationCurveDrift
      • ClassDiscriminationDrift
      • ClassificationAccuracyDrift
      • ClassImbalanceDrift
      • ConfusionMatrixDrift
      • CumulativePredictionProbabilitiesDrift
      • FeatureDrift
      • PredictionAcrossEachFeature
      • PredictionCorrelation
      • PredictionProbabilitiesHistogramDrift
      • PredictionQuantilesAcrossFeatures
      • ROCCurveDrift
      • ScoreBandsDrift
      • ScorecardHistogramDrift
      • TargetPredictionDistributionPlot
    • Prompt Validation
      • Bias
      • Clarity
      • Conciseness
      • Delimitation
      • NegativeInstruction
      • Robustness
      • Specificity
  • Test sandbox beta

  • Notebooks
  • Code samples
    • Capital Markets
      • Quickstart for knockout option pricing model documentation
      • Quickstart for Heston option pricing model using QuantLib
    • Code Explainer
      • Quickstart for model code documentation
    • Credit Risk
      • Document an application scorecard model
      • Document an application scorecard model
      • Document a credit risk model
      • Document an application scorecard model
      • Document an Excel-based application scorecard model
    • Custom Tests
      • Implement custom tests
      • Integrate external test providers
    • Model Validation
      • Validate an application scorecard model
    • Nlp and Llm
      • Sentiment analysis of financial data using a large language model (LLM)
      • Summarization of financial data using a large language model (LLM)
      • Sentiment analysis of financial data using Hugging Face NLP models
      • Summarization of financial data using Hugging Face NLP models
      • Automate news summarization using LLMs
      • Prompt validation for large language models (LLMs)
      • RAG Model Benchmarking Demo
      • RAG Model Documentation Demo
    • Ongoing Monitoring
      • Ongoing Monitoring for Application Scorecard
      • Quickstart for ongoing monitoring of models with ValidMind
    • Regression
      • Document a California Housing Price Prediction regression model
    • Time Series
      • Document a time series forecasting model
      • Document a time series forecasting model

  • Reference
  • ValidMind Library Python API
  • ​ValidMind Public REST API

On this page

  • Contents
  • About ValidMind
    • Before you begin
    • New to ValidMind?
    • Key concepts
  • Install the ValidMind Library
  • Initialize the ValidMind Library
    • Preview the documentation template
  • Load the sample dataset
  • Prepocess the raw dataset
  • Train models for testing
  • Initialize ValidMind objects
    • Initialize the ValidMind models
    • Initialize the ValidMind datasets
  • Options to load predictions using the ValidMind Library
    • Load predictions from a file
    • Predictions calculated outside of VM
    • Assign predictions to the training dataset
    • Run an example test
    • Link an existing prediction column in the dataset with a model
    • Link an existing prediction column in the dataset with a model
    • Run an example test
    • Using predict_fn to store multiple columns
  • Next steps
    • Work with your model documentation
    • Discover more learning resources
  • Upgrade ValidMind
  • Edit this page
  • Report an issue
  1. Run tests & test suites
  2. Load dataset predictions

Load dataset predictions

To enable tests to make use of predictions, you can load predictions in ValidMind dataset objects in multiple different ways.

This interactive notebook includes the code required to load the demo dataset, preprocess the raw dataset and train a model for testing, and initialize ValidMind objects. Additionally, it offers options for loading predictions using the assign_predictions() function, such as loading predictions from a file, linking an existing prediction column in the dataset with a model, or allowing the ValidMind Library to run and link predictions to a model.

Contents

  • About ValidMind
    • Before you begin
    • New to ValidMind?
    • Key concepts
  • Install the ValidMind Library
  • Initialize the ValidMind Library
    • Preview the documentation template
  • Load the sample dataset
  • Prepocess the raw dataset
  • Train models for testing
  • Initialize ValidMind objects
    • Initialize the ValidMind models
    • Initialize the ValidMind datasets
  • Options to load predictions using the ValidMind Library
    • Load predictions from a file
    • Predictions calculated outside of VM
    • Assign predictions to the training dataset
    • Run an example test
    • Link an existing prediction column in the dataset with a model
      • Link prediction column to a specific model
    • Link an existing prediction column in the dataset with a model
      • Pass <vm_model> in dataset interface
      • Through assign_predictions interface
    • Run an example test
    • Using predict_fn to store multiple columns
      • Create enhanced predict function
      • Initialize model with predict function
      • Assign predictions with multiple columns
      • Verify multiple columns in dataset
  • Next steps
    • Work with your model documentation
    • Discover more learning resources
  • Upgrade ValidMind

About ValidMind

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

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.

Before you begin

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

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

New to ValidMind?

If you haven't already seen our documentation on the ValidMind Library, we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting models and running tests, as well as find code samples and our Python Library API reference.

For access to all features available in this notebook, you'll need access to a ValidMind account.

Register with ValidMind

Key concepts

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

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

Tests: A function contained in the ValidMind 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.

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.

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

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

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

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.

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

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

Install the ValidMind Library

To install the library:

%pip install -q validmind

Initialize the ValidMind Library

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.

Get your code snippet:

  1. In a browser, log in to ValidMind.

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

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

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

    • Documentation template: Binary classification
    • Use case: Marketing/Sales - Attrition/Churn Management

    You can fill in other options according to your preference.

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

Next, replace this placeholder with your own code snippet:

# Load your model identifier credentials from an `.env` file

%load_ext dotenv
%dotenv .env

# Or replace with your code snippet

import validmind as vm

vm.init(
    # api_host="...",
    # api_key="...",
    # api_secret="...",
    # model="...",
)

Preview the documentation template

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

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

vm.preview_template()

Load the sample dataset

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

# Import the sample dataset from the library

from validmind.datasets.classification import customer_churn as demo_dataset

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

raw_df = demo_dataset.load_data()
raw_df.head()

Prepocess the raw dataset

Preprocessing performs a number of operations to get ready for the subsequent steps:

  • Preprocess the data: Splits the DataFrame (df) into multiple datasets (train_df, validation_df, and test_df) using demo_dataset.preprocess to simplify preprocessing.
  • Separate features and targets: Drops the target column to create feature sets (x_train, x_val) and target sets (y_train, y_val).
train_df, validation_df, test_df = demo_dataset.preprocess(raw_df)
x_train = train_df.drop(demo_dataset.target_column, axis=1)
y_train = train_df[demo_dataset.target_column]
x_val = validation_df.drop(demo_dataset.target_column, axis=1)
y_val = validation_df[demo_dataset.target_column]

Train models for testing

  • Initialize XGBoost and Logistic Regression Classifiers
from sklearn.linear_model import LogisticRegression
import xgboost

%matplotlib inline

xgb = xgboost.XGBClassifier(early_stopping_rounds=10)
xgb.set_params(
    eval_metric=["error", "logloss", "auc"],
)
xgb.fit(
    x_train,
    y_train,
    eval_set=[(x_val, y_val)],
    verbose=False,
)

lr = LogisticRegression(random_state=0)
lr.fit(
    x_train,
    y_train,
)

Initialize ValidMind objects

Initialize the ValidMind models

vm_model_xgb = vm.init_model(
    xgb,
    input_id="xgb",
)
vm_model_lr = vm.init_model(
    lr,
    input_id="lr",
)

Initialize the ValidMind datasets

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

This function takes a number of arguments:

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

With all datasets ready, you can now initialize the raw, training and test datasets (raw_df, train_df and test_df) created earlier into their own dataset objects using vm.init_dataset():

vm_raw_ds = vm.init_dataset(
    input_id="raw_dataset",
    dataset=raw_df,
    target_column=demo_dataset.target_column,
)

vm_train_ds = vm.init_dataset(
    input_id="train_dataset",
    dataset=train_df,
    target_column=demo_dataset.target_column,
)
vm_test_ds = vm.init_dataset(
    input_id="test_dataset", dataset=test_df, target_column=demo_dataset.target_column
)

Options to load predictions using the ValidMind Library

Load predictions from a file

This creates a new column called <model_id>_prediction in the dataset and assigns metadata to track that the <model_id>_prediction column is linked to the model <model_id>

Predictions calculated outside of VM

import pandas as pd

train_xgb_prediction = pd.DataFrame(xgb.predict(x_train), columns=["xgb_prediction"])
test__xgb_prediction = pd.DataFrame(xgb.predict(x_val), columns=["xgb_prediction"])

train_lr_prediction = pd.DataFrame(lr.predict(x_train), columns=["lr_prediction"])
test_lr_prediction = pd.DataFrame(lr.predict(x_val), columns=["lr_prediction"])

Assign predictions to the training dataset

We can now use the assign_predictions() method from the Dataset object to link existing predictions to any model:

vm_train_ds.assign_predictions(
    model=vm_model_xgb, prediction_values=train_xgb_prediction.xgb_prediction.values
)
vm_train_ds.assign_predictions(
    model=vm_model_lr, prediction_values=train_lr_prediction.lr_prediction.values
)

Run an example test

Now, let's run an example test such as MinimumAccuracy twice to show how we're able to load the correct model predictions by using the model input parameter, even though we're passing the same train_ds dataset instance to the test:

full_suite = vm.tests.run_test(
    "validmind.model_validation.sklearn.MinimumAccuracy",
    inputs={"dataset": vm_train_ds, "model": vm_model_xgb},
)
full_suite = vm.tests.run_test(
    "validmind.model_validation.sklearn.MinimumAccuracy",
    inputs={
        "dataset": vm_train_ds,
        "model": vm_model_lr,
    },
)

Link an existing prediction column in the dataset with a model

This approach allows loading datasets that already have prediction columns in addition to feature and target columns. The ValidMind Library assigns metadata to track the predictions column that are linked to a given <vm_model> model.

train_df2 = train_df.copy()
train_df2["xgb_prediction"] = train_xgb_prediction.xgb_prediction.values
train_df2["lr_prediction"] = train_lr_prediction.lr_prediction.values
train_df2.head(5)
feature_columns = [
    "CreditScore",
    "Gender",
    "Age",
    "Tenure",
    "Balance",
    "NumOfProducts",
    "HasCrCard",
    "IsActiveMember",
    "EstimatedSalary",
    "Geography_France",
    "Geography_Germany",
    "Geography_Spain",
]

vm_train_ds = vm.init_dataset(
    dataset=train_df2,
    input_id="train_dataset",
    target_column=demo_dataset.target_column,
    feature_columns=feature_columns,
)

Link prediction column to a specific model

The prediction_column parameter informs the Dataset object about the model that should be linked to that column.

vm_train_ds.assign_predictions(model=vm_model_xgb, prediction_column="xgb_prediction")
vm_train_ds.assign_predictions(model=vm_model_lr, prediction_column="lr_prediction")
full_suite = vm.tests.run_test(
    "validmind.model_validation.sklearn.MinimumAccuracy",
    inputs={"dataset": vm_train_ds, "model": vm_model_xgb},
)
full_suite = vm.tests.run_test(
    "validmind.model_validation.sklearn.MinimumAccuracy",
    inputs={"dataset": vm_train_ds, "model": vm_model_lr},
)

Link an existing prediction column in the dataset with a model

This lets the ValidMind Library run model predictions, creates a new column called <model_id>_prediction, and assign metadata to track that the <model_id>_prediction column is linked to the <vm_model> model.

There are two ways run and assign model predictions with the ValidMind Library:

  • When initializing a Dataset with init_dataset(). This is the most straightforward method to assign predictions for a single model.
  • Using dataset.assign_predictions(). This allows assigning predictions to a dataset for one or more models.

Pass <vm_model> in dataset interface

feature_columns = [
    "CreditScore",
    "Gender",
    "Age",
    "Tenure",
    "Balance",
    "NumOfProducts",
    "HasCrCard",
    "IsActiveMember",
    "EstimatedSalary",
    "Geography_France",
    "Geography_Germany",
    "Geography_Spain",
]

vm_train_ds = vm.init_dataset(
    model=vm_model_xgb,
    dataset=train_df,
    input_id="train_dataset",
    target_column=demo_dataset.target_column,
    feature_columns=feature_columns,
)

Through assign_predictions interface

vm_train_ds = vm.init_dataset(
    dataset=train_df,
    input_id="train_dataset",
    target_column=demo_dataset.target_column,
    feature_columns=feature_columns,
)
Perform predictions using the same assign_predictions interface
vm_train_ds.assign_predictions(model=vm_model_xgb)
vm_train_ds.assign_predictions(model=vm_model_lr)

Run an example test

Now, let's run an example test such as MinimumAccuracy twice to show how we're able to load the correct model predictions by using the model input parameter, even though we're passing the same train_ds dataset instance to the test:

full_suite = vm.tests.run_test(
    "validmind.model_validation.sklearn.MinimumAccuracy",
    inputs={"dataset": vm_train_ds, "model": vm_model_xgb},
)
full_suite = vm.tests.run_test(
    "validmind.model_validation.sklearn.MinimumAccuracy",
    inputs={
        "dataset": vm_train_ds,
        "model": vm_model_lr,
    },
)

Using predict_fn to store multiple columns

The predict_fn parameter in vm.init_model() allows you to create models that return multiple pieces of information when making predictions. This is particularly useful when you want to capture additional metadata, confidence scores, feature importance, or any other model-related information alongside the main prediction.

By returning a dictionary from your predict function, ValidMind automatically creates separate columns for each key when you run assign_predictions().

Create enhanced predict function

Let's create a predict function that wraps our XGBoost model and returns multiple pieces of information: - prediction: The main class prediction - prediction_proba: The prediction probabilities for both classes - confidence: The maximum probability as a confidence score - model_info: Metadata about the model used

import numpy as np
import pandas as pd

def enhanced_xgb_predict_fn(input_data):
    """
    Enhanced predict function that returns multiple pieces of information.
    
    Args:
        input_data: Input features for prediction (single row as dictionary when called by ValidMind)
    
    Returns:
        dict: Dictionary containing prediction, probabilities, confidence, and model info
    """
    # Define the feature columns that the model was trained on
    # These are the same columns from x_train (excluding the target column 'Exited')
    training_features = [
        'CreditScore', 'Gender', 'Age', 'Tenure', 'Balance', 'NumOfProducts',
        'HasCrCard', 'IsActiveMember', 'EstimatedSalary', 'Geography_France',
        'Geography_Germany', 'Geography_Spain'
    ]
    
    # Convert dictionary input to DataFrame for model prediction
    # When called by ValidMind, input_data is a single row dictionary
    if isinstance(input_data, dict):
        # Filter to only include training features and convert to DataFrame
        filtered_data = {key: value for key, value in input_data.items() if key in training_features}
        input_df = pd.DataFrame([filtered_data])
        
        # Ensure all training features are present (in case some are missing)
        for feature in training_features:
            if feature not in input_df.columns:
                input_df[feature] = 0  # Default value for missing features
        
        # Reorder columns to match training order
        input_df = input_df[training_features]
    else:
        # Handle other input types (DataFrame, array, etc.)
        input_df = pd.DataFrame(input_data) if not isinstance(input_data, pd.DataFrame) else input_data
        # Filter to training features if it's a DataFrame
        if isinstance(input_df, pd.DataFrame):
            input_df = input_df[training_features]
    
    # Make predictions
    prediction = xgb.predict(input_df)
    prediction_proba = xgb.predict_proba(input_df)
    
    # Since we're processing one row at a time, extract the single values
    single_prediction = prediction[0] if len(prediction) > 0 else None
    single_proba = prediction_proba[0] if len(prediction_proba) > 0 else None
    
    # Calculate confidence as the maximum probability for this prediction
    confidence = np.max(single_proba) if single_proba is not None else None
    
    # Create model metadata
    model_info = {
        "model_type": "XGBClassifier",
        "n_estimators": xgb.n_estimators,
        "max_depth": xgb.max_depth,
        "feature_count": len(training_features),
        "features_used": training_features
    }
    
    return {
        "prediction": single_prediction,
        "prediction_proba": single_proba.tolist() if single_proba is not None else None,
        "confidence": confidence,
        "model_info": model_info
    }

Initialize model with predict function

Now we'll create a ValidMind model using the predict_fn parameter. This tells ValidMind to use our enhanced function instead of the model's default predict() method:

# Initialize ValidMind model with the enhanced predict function
vm_model_enhanced_xgb = vm.init_model(
    model=xgb,
    input_id="enhanced_xgb",
    predict_fn=enhanced_xgb_predict_fn 
)

print(f"Enhanced XGBoost model initialized with input_id: {vm_model_enhanced_xgb.input_id}")
print("This model now uses the predict function that handles dictionary inputs correctly")
print("It will return multiple columns when predictions are assigned to datasets")

Assign predictions with multiple columns

When we use assign_predictions() with our enhanced model, ValidMind will automatically create separate columns for each key returned by our predict function. Let's assign predictions to our test dataset:

# Create a fresh dataset for this demonstration
vm_test_ds_enhanced = vm.init_dataset(
    input_id="test_dataset_enhanced",
    dataset=test_df,
    target_column=demo_dataset.target_column
)

# This will create multiple columns based on the keys returned by our predict function
vm_test_ds_enhanced.assign_predictions(model=vm_model_enhanced_xgb)

Verify multiple columns in dataset

Let's examine the dataset to see all the columns that were created by our enhanced predict function. Each key from the returned dictionary becomes a separate column with the model's input_id as a prefix:

vm_test_ds_enhanced._df.head()

Next steps

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

Work with your model documentation

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

  2. Click and expand the Model Development section.

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

Discover more learning resources

We offer many interactive notebooks to help you document models:

  • Run tests & test suites
  • Code samples

Or, visit our documentation to learn more about ValidMind.

Upgrade ValidMind

After installing ValidMind, you’ll want to periodically make sure you are on the latest version to access any new features and other enhancements.

Retrieve the information for the currently installed version of ValidMind:

%pip show validmind

If the version returned is lower than the version indicated in our production open-source code, restart your notebook and run:

%pip install --upgrade validmind

You may need to restart your kernel after running the upgrade package for changes to be applied.

Dataset Column Filters when Running Tests
Log metrics over time
  • ValidMind Logo
    ©
    Copyright 2025 ValidMind Inc.
    All Rights Reserved.
    Cookie preferences
    Legal
  • Get started
    • Model development
    • Model validation
    • Setup & admin
  • Guides
    • Access
    • Configuration
    • Model inventory
    • Model documentation
    • Model validation
    • Model workflows
    • Reporting
    • Monitoring
    • Attestation
  • Library
    • For developers
    • For validators
    • Code samples
    • API Reference
  • Training
    • Learning paths
    • Courses
    • Videos
  • Support
    • Troubleshooting
    • FAQ
    • Get help
  • Community
    • Slack
    • GitHub
    • Blog
  • Edit this page
  • Report an issue