在 TensorFlow.org 上查看
|
在 Google Colab 中运行
|
在 GitHub 上查看
|
下载笔记本
|
查看 TF Hub 模型
|
在本教程中,您将学习如何使用 公平性指标 (Fairness Indicators) 来评估来自 TF Hub 的嵌入。本笔记本使用 Civil Comments 数据集。
设置
安装所需的库。
!pip install -q -U pip==20.2
!pip install fairness-indicators \
"absl-py==0.12.0" \
"pyarrow==2.0.0" \
"apache-beam==2.40.0" \
"avro-python3==1.9.1"
导入其他所需的库。
import os
import tempfile
import apache_beam as beam
from datetime import datetime
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_model_analysis as tfma
from tensorflow_model_analysis.addons.fairness.view import widget_view
from tensorflow_model_analysis.addons.fairness.post_export_metrics import fairness_indicators
from fairness_indicators import example_model
from fairness_indicators.tutorial_utils import util
数据集
在本笔记本中,您将使用 Civil Comments 数据集,该数据集包含 Civil Comments 平台 在 2017 年为进行中研究而公开的约 200 万条公共评论。这项工作由 Jigsaw 赞助,他们曾在 Kaggle 上举办过比赛,旨在帮助对有毒评论进行分类并最大限度地减少意外的模型偏差。
数据集中的每一条文本评论都有一个毒性标签,标签为 1 表示评论是有毒的,为 0 表示评论是无毒的。在数据中,一部分评论被标记了各种身份属性,包括性别、性取向、宗教以及种族或民族的类别。
准备数据
TensorFlow 使用 tf.io.FixedLenFeature 和 tf.io.VarLenFeature 解析数据中的特征。映射出输入特征、输出特征以及所有其他感兴趣的切片特征。
BASE_DIR = tempfile.gettempdir()
# The input and output features of the classifier
TEXT_FEATURE = 'comment_text'
LABEL = 'toxicity'
FEATURE_MAP = {
# input and output features
LABEL: tf.io.FixedLenFeature([], tf.float32),
TEXT_FEATURE: tf.io.FixedLenFeature([], tf.string),
# slicing features
'sexual_orientation': tf.io.VarLenFeature(tf.string),
'gender': tf.io.VarLenFeature(tf.string),
'religion': tf.io.VarLenFeature(tf.string),
'race': tf.io.VarLenFeature(tf.string),
'disability': tf.io.VarLenFeature(tf.string)
}
IDENTITY_TERMS = ['gender', 'sexual_orientation', 'race', 'religion', 'disability']
默认情况下,笔记本会下载此数据集的预处理版本,但如果需要,您可以使用原始数据集并重新运行处理步骤。
在原始数据集中,每条评论都标记有认为该评论属于特定身份的评估者百分比。例如,一条评论可能标记如下: { male: 0.3, female: 1.0, transgender: 0.0, heterosexual: 0.8, homosexual_gay_or_lesbian: 1.0 }。
处理步骤按类别(性别、性取向等)对身份进行分组,并删除评分低于 0.5 的身份。因此,上述示例将转换为:认为评论对应于特定身份的评估者的身份。例如,上面的评论将被标记为: { gender: [female], sexual_orientation: [heterosexual, homosexual_gay_or_lesbian] }
下载数据集。
download_original_data = False
if download_original_data:
train_tf_file = tf.keras.utils.get_file('train_tf.tfrecord',
'https://storage.googleapis.com/civil_comments_dataset/train_tf.tfrecord')
validate_tf_file = tf.keras.utils.get_file('validate_tf.tfrecord',
'https://storage.googleapis.com/civil_comments_dataset/validate_tf.tfrecord')
# The identity terms list will be grouped together by their categories
# (see 'IDENTITY_COLUMNS') on threshold 0.5. Only the identity term column,
# text column and label column will be kept after processing.
train_tf_file = util.convert_comments_data(train_tf_file)
validate_tf_file = util.convert_comments_data(validate_tf_file)
else:
train_tf_file = tf.keras.utils.get_file('train_tf_processed.tfrecord',
'https://storage.googleapis.com/civil_comments_dataset/train_tf_processed.tfrecord')
validate_tf_file = tf.keras.utils.get_file('validate_tf_processed.tfrecord',
'https://storage.googleapis.com/civil_comments_dataset/validate_tf_processed.tfrecord')
创建 TensorFlow 模型分析流水线
公平性指标库基于 TensorFlow 模型分析 (TFMA) 模型 运行。TFMA 模型将 TensorFlow 模型与额外的功能进行封装,以评估和可视化其结果。实际的评估发生在 Apache Beam 流水线 内部。
创建 TFMA 流水线所遵循的步骤是:
- 构建一个 TensorFlow 模型
- 在 TensorFlow 模型之上构建一个 TFMA 模型
- 在编排器中运行模型分析。本笔记本中的示例模型使用 Apache Beam 作为编排器。
def embedding_fairness_result(embedding, identity_term='gender'):
model_dir = os.path.join(BASE_DIR, 'train',
datetime.now().strftime('%Y%m%d-%H%M%S'))
print("Training classifier for " + embedding)
classifier = example_model.train_model(model_dir,
train_tf_file,
LABEL,
TEXT_FEATURE,
FEATURE_MAP,
embedding)
# Create a unique path to store the results for this embedding.
embedding_name = embedding.split('/')[-2]
eval_result_path = os.path.join(BASE_DIR, 'eval_result', embedding_name)
example_model.evaluate_model(classifier,
validate_tf_file,
eval_result_path,
identity_term,
LABEL,
FEATURE_MAP)
return tfma.load_eval_result(output_path=eval_result_path)
运行 TFMA 和公平性指标
公平性指标度量
公平性指标提供的一些度量包括:
- 负例率、假负例率 (FNR) 和真负例率 (TNR)
- 正例率、假正例率 (FPR) 和真正例率 (TPR)
- 准确率 (Accuracy)
- 精确率 (Precision) 和召回率 (Recall)
- 精确率-召回率曲线下面积 (Precision-Recall AUC)
- ROC 曲线下面积 (ROC AUC)
文本嵌入
TF-Hub 提供了多种 文本嵌入。这些嵌入将作为不同模型的特征列。本教程使用以下嵌入:
- random-nnlm-en-dim128:随机文本嵌入,这作为一个方便的基准。
- nnlm-en-dim128:一种基于 神经概率语言模型 的文本嵌入。
- universal-sentence-encoder:一种基于 通用句子编码器 (Universal Sentence Encoder) 的文本嵌入。
公平性指标结果
使用 embedding_fairness_result 流水线计算公平性指标,然后使用 widget_view.render_fairness_indicator 在公平性指标 UI 小部件中渲染上述所有嵌入的结果。
随机 NNLM
eval_result_random_nnlm = embedding_fairness_result('https://tfhub.dev/google/random-nnlm-en-dim128/1')
widget_view.render_fairness_indicator(eval_result=eval_result_random_nnlm)
NNLM
eval_result_nnlm = embedding_fairness_result('https://tfhub.dev/google/nnlm-en-dim128/1')
widget_view.render_fairness_indicator(eval_result=eval_result_nnlm)
通用句子编码器 (Universal Sentence Encoder)
eval_result_use = embedding_fairness_result('https://tfhub.dev/google/universal-sentence-encoder/2')
widget_view.render_fairness_indicator(eval_result=eval_result_use)
比较嵌入
您还可以使用公平性指标直接比较嵌入。例如,比较从 NNLM 和 USE 嵌入生成的模型。
widget_view.render_fairness_indicator(multi_eval_results={'nnlm': eval_result_nnlm, 'use': eval_result_use})
在 TensorFlow.org 上查看
在 Google Colab 中运行
在 GitHub 上查看
下载笔记本
查看 TF Hub 模型