독립형 모델 카드 툴킷 데모

이 "독립형" 노트북은 TFX/MLMD 컨텍스트 없이 Model Card Toolkit을 사용하는 방법을 보여줍니다. TFX / MLMD와 모델 카드 툴킷을 사용하는 방법에 대한 자세한 내용은 확인하시기 바랍니다 MLMD 모델 카드 툴킷 데모 .

TensorFlow.org에서 보기 Google Colab에서 실행 GitHub에서 보기 노트북 다운로드

객관적인

이 노트북은 Jupyter/Colab 환경에서 Model Card Toolkit을 사용하여 모델 카드를 생성하는 방법을 보여줍니다. 당신은에서 모델 카드에 대해 자세히 알아볼 수 있습니다 https://modelcards.withgoogle.com/about

이 데모에서는 Keras 모델을 사용하고 있습니다. 그러나 아래 논리는 일반적으로 다른 ML 프레임워크에도 적용됩니다.

설정

먼저) 필요한 패키지를 설치 및 가져오고, b) 데이터를 다운로드해야 합니다.

Pip 20.2로 업그레이드하고 Model Card Toolkit 설치

pip install --upgrade pip==20.2
pip install 'model-card-toolkit>=1.0.0,<1.1'
pip install 'tensorflow>=2.3.1'

런타임을 다시 시작하셨습니까?

Google Colab을 사용하는 경우 위의 셀을 처음 실행할 때 런타임을 다시 시작해야 합니다(런타임 > 런타임 다시 시작...). Colab이 패키지를 로드하는 방식 때문입니다.

수입품

import tensorflow as tf
import numpy as np
import model_card_toolkit as mctlib
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

모델

우리는 떨어져 기반 아키텍처와 pretrained 모델을 사용합니다 MobileNetV2 , 인기있는 16 층 영상 분류 모델을. 우리의 모델은 betweens 고양이와 사용 개를 구별하도록 훈련 된 개들은 대 고양이를 데이터 세트. 모델 훈련은 기반으로했다 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.

데이터세트

고양이 대 개 데이터 세트에서 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
2022-01-07 19:54:14.702877: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] 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 [==============================] - 9s 12ms/step - loss: 0.0794 - binary_accuracy: 0.9812
5/5 [==============================] - 1s 41ms/step - loss: 0.0608 - binary_accuracy: 0.9933
6/6 [==============================] - 0s 34ms/step - loss: 0.0956 - binary_accuracy: 0.9708

모델 카드 도구 키트 사용

모델 카드 도구 키트 초기화

첫 번째 단계는 초기화하는 것입니다 ModelCardToolkit A 이하의 자산을 유지 객체 모델 카드 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()
mct = mctlib.ModelCardToolkit(model_card_dir)

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

모델 카드에 주석 달기

ModelCard 의해 리턴 된 객체 scaffold_assets() 직접 수정할 수있는 다수의 필드를 갖는다. 이러한 필드는 최종 생성된 모델 카드 문서에서 렌더링됩니다. 포괄적 인 목록을 참조 model_card.py을 . 참조 문서 자세한 내용을.

텍스트 필드

모델 세부 정보

model_card.model_details 다음과 같은 여러 기본 메타 데이터 필드가 포함되어 name , ownersversion . 당신은 당신의 모델에 대한 설명을 제공 할 수있는 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://www.tensorflow.org/datasets/catalog/cats_vs_dogs). This model '
    'performed with high accuracy on both Cat and Dog images.'
)
model_card.model_details.owners = [
  mctlib.Owner(name='Model Cards Team', contact='model-cards@google.com')
]
model_card.model_details.version = mctlib.Version(name='v1.0', date='08/28/2020')
model_card.model_details.references = [
    mctlib.Reference(reference='https://www.tensorflow.org/guide/keras/transfer_learning'),
    mctlib.Reference(reference='https://arxiv.org/abs/1801.04381'),
]
model_card.model_details.licenses = [mctlib.License(identifier='Apache-2.0')]
model_card.model_details.citations = [mctlib.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 = [
  mctlib.PerformanceMetric(type='accuracy', value=str(accuracy)),
  mctlib.PerformanceMetric(type='accuracy', value=str(cat_accuracy), slice='cat'),
  mctlib.PerformanceMetric(type='accuracy', value=str(dog_accuracy), slice='Dog'),
]
고려 사항

model_card.considerations 모델에 대한 정보를 자격을 포함 - 등 응용 프로그램의 윤리적 고려 사항, 어떤 사용자가 염두에 두어야한다는 제한이 무엇인지 적절한 사용 사례는 무엇인가

model_card.considerations.use_cases = [
    mctlib.UseCase(description='This model classifies images of cats and dogs.')
]
model_card.considerations.limitations = [
    mctlib.Limitation(description='This model is not able to classify images of other classes.')
]
model_card.considerations.ethical_considerations = [mctlib.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 Toolkit을 사용하면 모델 카드에서 렌더링된 시각화로 이 정보를 인코딩할 수 있습니다.

model_card 세 개의 그래프에 대한 섹션이 - model_card.model_parameters.data.train.graphics 데이터 세트 통계 교육을 model_card.model_parameters.data.eval.graphics 평가 데이터 세트 통계 및 model_card.quantitative_analysis.graphics 모델 성능의 정량 분석.

그래프는 다음과 같이 저장됩니다 base64로 문자열 . 당신이있는 경우 하기 matplotlib의 그림, 당신이 base64로 문자열로 변환 할 수 있습니다 model_card_toolkit.utils.graphics.figure_to_base64str() .

# 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(mctlib.Dataset())
model_card.model_parameters.data[0].graphics.collection = [
  mctlib.Graphic(name='Validation Set Size', image=validation_set_size_barchart),
]
model_card.quantitative_analysis.graphics.collection = [
  mctlib.Graphic(name='Accuracy', image=accuracy_barchart),
]

모델 카드 생성

모델 카드 문서를 생성해 보겠습니다. 사용 가능한 형식으로 저장됩니다 model_card_toolkit / 템플릿 . 여기에서는 HTML 및 Markdown 형식을 보여줍니다.

첫째, 우리는 업데이트해야 ModelCardToolkit 최신와 ModelCard .

mct.update_model_card(model_card)

이제, ModelCardToolkit 있는 모델 카드 문서를 생성 할 수 있습니다 ModelCardToolkit.export_format() .

# Generate a model card document in HTML (default)
html_doc = mct.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 = mct.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://www.tensorflow.org/datasets/catalog/cats_vs_dogs ). 이 모델은 고양이와 강아지 이미지 모두에서 높은 정확도로 수행되었습니다.

버전

이름: v1.0

날짜: 2020-08-28

소유자

  • 모델 카드 팀, model-cards@google.com

라이선스

  • 아파치-2.0

참고문헌

인용

고려 사항

사용 사례

  • 이 모델은 고양이와 개의 이미지를 분류합니다.

제한 사항

  • 이 모델은 다른 클래스의 이미지를 분류할 수 없습니다.

윤리적 고려 사항

  • 위험: 고양이와 개를 구별하는 것은 일반적으로 머신 러닝의 무해한 적용으로 동의되지만 모델이 고양이나 개가 포함되지 않은 이미지를 분류하려고 시도하면 유해한 결과가 발생할 수 있습니다.
    • 완화 전략: 개 및 고양이가 아닌 이미지에 적용하지 마십시오.

제도법

검증 세트 크기

정확성

측정항목

이름
정확성 0.981249988079071
정확도, 고양이 0.9932885766029358
정확도, 개 0.9707602262496948