独立模型卡工具包演示

此“独立”笔记本展示了如何在不依赖 TFX/MLMD 上下文的情况下使用模型卡工具包 (Model Card Toolkit)。

在 TensorFlow.org 上查看 在 Google Colab 中运行 在 GitHub 上查看 下载笔记本

目标

本笔记本演示了如何在 Jupyter/Colab 环境中使用模型卡工具包来生成模型卡。您可以在 https://modelcards.withgoogle.com/about 了解更多关于模型卡的信息。

在本演示中,我们使用了一个 Keras 模型。但以下逻辑通常也适用于其他机器学习框架。

设置

我们首先需要 a) 安装并导入必要的包,b) 下载数据。

升级 Pip 并安装模型卡工具包

pip install --upgrade pip
pip install 'model-card-toolkit>=1.0.0'
pip install 'tensorflow>=2.3.1'
pip install 'tensorflow-datasets>=4.8.2'

您重启运行时了吗?

如果您使用的是 Google Colab,首次运行上述单元格时,必须重新启动运行时(运行时 > 重新启动运行时...)。这是因为 Colab 加载软件包的方式所致。

导入

import tensorflow as tf
import numpy as np
import model_card_toolkit as mct
from model_card_toolkit.documentation.examples import cats_vs_dogs
from model_card_toolkit.utils.graphics import figure_to_base64str
import tempfile
import matplotlib.pyplot as plt
from IPython import display
import requests
import os
import zipfile

模型

我们将使用一个基于 MobileNetV2 架构的预训练模型,这是一种流行的 16 层图像分类模型。我们的模型经过训练,可以使用 猫狗大战 (Cats vs Dogs) 数据集来区分猫和狗。模型训练基于 TensorFlow 迁移学习教程

URL = 'https://storage.googleapis.com/cats_vs_dogs_model/cats_vs_dogs_model.zip'
BASE_PATH = tempfile.mkdtemp()
ZIP_PATH = os.path.join(BASE_PATH, 'cats_vs_dogs_model.zip')
MODEL_PATH = os.path.join(BASE_PATH,'cats_vs_dogs_model')

r = requests.get(URL, allow_redirects=True)
open(ZIP_PATH, 'wb').write(r.content)

with zipfile.ZipFile(ZIP_PATH, 'r') as zip_ref:
    zip_ref.extractall(BASE_PATH)

model = tf.keras.models.load_model(MODEL_PATH)
WARNING:tensorflow:SavedModel saved prior to TF 2.5 detected when loading Keras model. Please ensure that you are saving the model with model.save() or tf.keras.models.save_model(), *NOT* tf.saved_model.save(). To confirm, there should be a file named "keras_metadata.pb" in the SavedModel directory.
WARNING:tensorflow:SavedModel saved prior to TF 2.5 detected when loading Keras model. Please ensure that you are saving the model with model.save() or tf.keras.models.save_model(), *NOT* tf.saved_model.save(). To confirm, there should be a file named "keras_metadata.pb" in the SavedModel directory.
2023-10-03 09:12:20.736066: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1960] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://tensorflowcn.cn/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...

数据集

在猫狗大战数据集中,label=0 对应猫,label=1 对应狗。

def compute_accuracy(data):
  x = np.stack(data['examples'])
  y = np.asarray(data['labels'])
  _, metric = model.evaluate(x, y)
  return metric
examples = cats_vs_dogs.get_data()
print('num validation examples:', len(examples['combined']['examples']))
print('num cat examples:', len(examples['cat']['examples']))
print('num dog examples:', len(examples['dog']['examples']))
num validation examples: 320
num cat examples: 149
num dog examples: 171
2023-10-03 09:12:30.081069: W tensorflow/core/kernels/data/cache_dataset_ops.cc:854] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset  will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead.
accuracy = compute_accuracy(examples['combined'])
cat_accuracy = compute_accuracy(examples['cat'])
dog_accuracy = compute_accuracy(examples['dog'])
10/10 [==============================] - 2s 77ms/step - loss: 0.0794 - binary_accuracy: 0.9812
5/5 [==============================] - 1s 74ms/step - loss: 0.0608 - binary_accuracy: 0.9933
6/6 [==============================] - 0s 65ms/step - loss: 0.0956 - binary_accuracy: 0.9708

使用模型卡工具包

初始化模型卡工具包

第一步是初始化一个 ModelCardToolkit 对象,它维护资产,包括 模型卡 JSON 文件模型卡文档。调用 ModelCardToolkit.scaffold_assets() 来生成这些资产并返回一个 ModelCard 对象。

# https://github.com/tensorflow/model-card-toolkit/blob/master/model_card_toolkit/model_card_toolkit.py
model_card_dir = tempfile.mkdtemp()
toolkit = mct.ModelCardToolkit(model_card_dir)

# https://github.com/tensorflow/model-card-toolkit/blob/master/model_card_toolkit/model_card.py
model_card = toolkit.scaffold_assets()

注释模型卡

scaffold_assets() 返回的 ModelCard 对象有许多可以直接修改的字段。这些字段会呈现在最终生成的模型卡文档中。有关完整列表,请参阅 model_card.py。有关更多详细信息,请参阅 文档

文本字段

模型详细信息

model_card.model_details 包含许多基本元数据字段,例如 name(名称)、owners(所有者)和 version(版本)。您可以在 overview(概述)字段中提供模型的描述。

model_card.model_details.name = 'Fine-tuned MobileNetV2 Model for Cats vs. Dogs'
model_card.model_details.overview = (
    'This model distinguishes cat and dog images. It uses the MobileNetV2 '
    'architecture (https://arxiv.org/abs/1801.04381) and is trained on the '
    'Cats vs Dogs dataset '
    '(https://tensorflowcn.cn/datasets/catalog/cats_vs_dogs). This model '
    'performed with high accuracy on both Cat and Dog images.'
)
model_card.model_details.owners = [
  mct.Owner(name='Model Cards Team', contact='model-cards@google.com')
]
model_card.model_details.version = mct.Version(name='v1.0', date='08/28/2020')
model_card.model_details.references = [
    mct.Reference(reference='https://tensorflowcn.cn/guide/keras/transfer_learning'),
    mct.Reference(reference='https://arxiv.org/abs/1801.04381'),
]
model_card.model_details.licenses = [mct.License(identifier='Apache-2.0')]
model_card.model_details.citations = [mct.Citation(citation='https://github.com/tensorflow/model-card-toolkit/blob/master/model_card_toolkit/documentation/examples/Standalone_Model_Card_Toolkit_Demo.ipynb')]
定量分析

model_card.quantitative_analysis 包含有关模型性能指标的信息。

下面,我们为基于我们的数据集构建的假设模型创建一些合成的性能指标值。

model_card.quantitative_analysis.performance_metrics = [
  mct.PerformanceMetric(type='accuracy', value=str(accuracy)),
  mct.PerformanceMetric(type='accuracy', value=str(cat_accuracy), slice='cat'),
  mct.PerformanceMetric(type='accuracy', value=str(dog_accuracy), slice='Dog'),
]
注意事项

model_card.considerations 包含有关您模型的限定信息——什么是合适的用例、用户应该记住的局限性、应用的伦理考虑等。

model_card.considerations.use_cases = [
    mct.UseCase(description='This model classifies images of cats and dogs.')
]
model_card.considerations.limitations = [
    mct.Limitation(description='This model is not able to classify images of other classes.')
]
model_card.considerations.ethical_considerations = [mct.Risk(
    name=
        'While distinguishing between cats and dogs is generally agreed to be '
        'a benign application of machine learning, harmful results can occur '
        'when the model attempts to classify images that don’t contain cats or '
        'dogs.',
    mitigation_strategy=
        'Avoid application on non-dog and non-cat images.'
)]

图形字段

报告的最佳做法通常是提供有关模型训练数据及其在评估数据上表现的信息。模型卡工具包允许用户将此信息编码为可视化图表,并呈现在模型卡中。

model_card 有三个用于图形的部分——model_card.model_parameters.data.train.graphics(用于训练数据集统计)、model_card.model_parameters.data.eval.graphics(用于评估数据集统计)以及 model_card.quantitative_analysis.graphics(用于模型性能的定量分析)。

图形以 base64 字符串 形式存储。如果您有 matplotlib 图表,可以使用 model_card_toolkit.utils.graphics.figure_to_base64str() 将其转换为 base64 字符串。

# Validation Set Size Bar Chart
fig, ax = plt.subplots()
width = 0.75
rects0 = ax.bar(0, len(examples['combined']['examples']), width, label='Overall')
rects1 = ax.bar(1, len(examples['cat']['examples']), width, label='Cat')
rects2 = ax.bar(2, len(examples['dog']['examples']), width, label='Dog')
ax.set_xticks(np.arange(3))
ax.set_xticklabels(['Overall', 'Cat', 'Dog'])
ax.set_ylabel('Validation Set Size')
ax.set_xlabel('Slices')
ax.set_title('Validation Set Size for Slices')
validation_set_size_barchart = figure_to_base64str(fig)

png

# Acuracy Bar Chart
fig, ax = plt.subplots()
width = 0.75
rects0 = ax.bar(0, accuracy, width, label='Overall')
rects1 = ax.bar(1, cat_accuracy, width, label='Cat')
rects2 = ax.bar(2, dog_accuracy, width, label='Dog')
ax.set_xticks(np.arange(3))
ax.set_xticklabels(['Overall', 'Cat', 'Dog'])
ax.set_ylabel('Accuracy')
ax.set_xlabel('Slices')
ax.set_title('Accuracy on Slices')
accuracy_barchart = figure_to_base64str(fig)

png

现在我们可以将它们添加到我们的 ModelCard 中。

model_card.model_parameters.data.append(mct.Dataset())
model_card.model_parameters.data[0].graphics.collection = [
  mct.Graphic(name='Validation Set Size', image=validation_set_size_barchart),
]
model_card.quantitative_analysis.graphics.collection = [
  mct.Graphic(name='Accuracy', image=accuracy_barchart),
]

生成模型卡

让我们生成模型卡文档。可用格式存储在 model_card_toolkit/template 中。在此,我们将演示 HTML 和 Markdown 格式。

首先,我们需要使用最新的 ModelCard 更新 ModelCardToolkit

toolkit.update_model_card(model_card)

现在,ModelCardToolkit 可以通过 ModelCardToolkit.export_format() 生成模型卡文档。

# Generate a model card document in HTML (default)
html_doc = toolkit.export_format()

# Display the model card document in HTML
display.display(display.HTML(html_doc))

您还可以以其他格式(如 Markdown)输出模型卡。

# Generate a model card document in Markdown
md_path = os.path.join(model_card_dir, 'template/md/default_template.md.jinja')
md_doc = toolkit.export_format(template_path=md_path, output_file='model_card.md')

# Display the model card document in Markdown
display.display(display.Markdown(md_doc))

用于猫狗分类的微调 MobileNetV2 模型卡

模型详细信息

概览

此模型用于区分猫和狗的图像。它使用 MobileNetV2 架构 (https://arxiv.org/abs/1801.04381) 并在猫狗大战数据集上进行训练 (https://tensorflowcn.cn/datasets/catalog/cats_vs_dogs)。该模型在猫和狗的图像上均表现出很高的准确性。

版本

名称:v1.0

日期:2020年8月28日

所有者

  • 模型卡团队, model-cards@google.com

许可

  • Apache-2.0

参考文献

引用

注意事项

用例

  • 此模型用于对猫和狗的图像进行分类。

限制

  • 此模型无法对其他类别的图像进行分类。

伦理考量

  • 风险:虽然区分猫和狗通常被认为是机器学习的一种良性应用,但当模型试图分类不包含猫或狗的图像时,可能会产生有害结果。
  • 缓解策略:避免应用于非狗和非猫图像。

图形学

验证集大小

准确率 (Accuracy)

指标

名称
准确率 0.981249988079071
准确率,猫 0.9932885766029358
准确率,狗 0.9707602262496948