Summarization of financial data using Hugging Face NLP models

Document a natural language processing (NLP) model using ValidMind to summarize financial news, based on a dataset of just over 300,000 unique news articles written by journalists at CNN and the Daily Mail.

This interactive notebook shows you how to set up the ValidMind Developer Framework, initialize the client library, and load the dataset, followed by running the model validation tests provided by the framework to quickly generate documentation about the data and model.

About ValidMind

ValidMind’s platform enables organizations to identify, document, and manage model risks for all types of models, including AI/ML models, LLMs, and statistical models. As a model developer, you use the ValidMind Developer Framework to automate documentation and validation tests, and then use the ValidMind AI Risk Platform UI to collaborate on model documentation, these products simplify model risk management, facilitate compliance with regulations and institutional standards, and enhance collaboration between yourself and model validators.

If this is your first time trying out ValidMind, we recommend going through the following resources first:

Before you begin

For access to all features available in this notebook, create a free ValidMind account.

Signing up is FREE — Sign up now

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.

Install the client library

The client library provides Python support for the ValidMind Developer Framework. To install it:

%pip install -q validmind

Initialize the client library

ValidMind generates a unique code snippet for each registered model to connect with your developer environment. You initialize the client 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 into the Platform UI.

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

  3. Enter the model details, making sure to select NLP-based Text Summarization as the template and Marketing/Sales - Analytics as the use case, and click Continue. (Need more help?)

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

Next, replace this placeholder with your own code snippet:

# Replace with your code snippet

import validmind as vm

vm.init(
    api_host="https://api.prod.validmind.ai/api/v1/tracking",
    api_key="...",
    api_secret="...",
    project="...",
)

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()

Helper functions

Let’s define the following functions to help visualize datasets with long text fields:

import textwrap

from IPython.display import display, HTML
from tabulate import tabulate


def _format_cell_text(text, width=50):
    """Private function to format a cell's text."""
    return "\n".join([textwrap.fill(line, width=width) for line in text.split("\n")])


def _format_dataframe_for_tabulate(df):
    """Private function to format the entire DataFrame for tabulation."""
    df_out = df.copy()

    # Format all string columns
    for column in df_out.columns:
        if (
            df_out[column].dtype == object
        ):  # Check if column is of type object (likely strings)
            df_out[column] = df_out[column].apply(_format_cell_text)
    return df_out


def _dataframe_to_html_table(df):
    """Private function to convert a DataFrame to an HTML table."""
    headers = df.columns.tolist()
    table_data = df.values.tolist()
    return tabulate(table_data, headers=headers, tablefmt="html")


def display_formatted_dataframe(df, num_rows=None):
    """Primary function to format and display a DataFrame."""
    if num_rows is not None:
        df = df.head(num_rows)
    formatted_df = _format_dataframe_for_tabulate(df)
    html_table = _dataframe_to_html_table(formatted_df)
    display(HTML(html_table))

Load the dataset

The CNN Dailymail Dataset is an English-language dataset containing just over 300k unique news articles as written by journalists at CNN and the Daily Mail (https://huggingface.co/datasets/cnn_dailymail). The current version supports both extractive and abstractive summarization, though the original version was created for machine reading and comprehension and abstractive question answering.

import pandas as pd

df = pd.read_csv("./datasets/cnn_dailymail_100_with_predictions.csv")
display_formatted_dataframe(df, num_rows=5)
vm_raw_ds = vm.init_dataset(
    dataset=df,
    input_id="raw_dataset",
    text_column="article",
    target_column="highlights",
)

NLP data quality tests

Before we proceed with the analysis, it’s crucial to ensure the quality of our NLP data. We can run the data_preparation section of the template to validate the data’s integrity and suitability:

text_data_test_plan = vm.run_documentation_tests(
    section="data_preparation", inputs={"dataset": vm_raw_ds}
)
from transformers import pipeline, T5Tokenizer, T5ForConditionalGeneration

tokenizer = T5Tokenizer.from_pretrained("t5-small")
model = T5ForConditionalGeneration.from_pretrained("t5-small")

summarizer_model = pipeline(
    task="summarization",
    model=model,
    tokenizer=tokenizer,
    min_length=0,
    max_length=60,
    truncation=True,
)  # Note: We specify cache_dir to use predownloaded models.
vm_test_ds = vm.init_dataset(
    dataset=df,
    input_id="test_dataset",
    text_column="article",
    target_column="highlights",
)
vm_model = vm.init_model(
    summarizer_model,
)

# Assign model predictions to the test dataset
vm_test_ds.assign_predictions(vm_model, prediction_column="t5_prediction")

Run model validation tests

It’s possible to run a subset of tests on the documentation template by passing a section parameter to run_documentation_tests(). Let’s run only the tests that evaluate the model’s overall performance, including summarization metrics, by selecting the model_development section of the template:

summarization_results = vm.run_documentation_tests(
    section="model_development",
    inputs={
        "dataset": vm_test_ds,
        "model": vm_model,
    },
)

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: view the prompt validation test results as part of your model documentation in the ValidMind Platform UI:

  1. In the Platform UI, go to the Documentation page for the model you registered earlier.

  2. Expand 2. Data Preparation or 3. Model Development to review all test results.

What you can see now is a more easily consumable version of the prompt validation testing you just performed, along with other parts of your model documentation that still need to be completed.

If you want to learn more about where you are in the model documentation process, take a look at Get started with the ValidMind Developer Framework.