![]() |
![]() |
![]() |
![]() |
![]() |
在本教程中,您将学习如何使用 公平性指标 评估来自 TF Hub 的嵌入。此笔记本使用 民事评论数据集。
设置
安装所需的库。
!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
数据集
在本笔记本中,您将使用 民事评论数据集,该数据集包含大约 200 万条由 民事评论平台 在 2017 年公开发布的公开评论,用于持续研究。这项工作由 Jigsaw 赞助,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 和公平性指标
公平性指标指标
公平性指标提供的一些指标包括
文本嵌入
TF-Hub 提供了多个 文本嵌入。这些嵌入将作为不同模型的特征列。本教程使用以下嵌入
- random-nnlm-en-dim128: 随机文本嵌入,这是一种方便的基线。
- nnlm-en-dim128: 基于 神经概率语言模型 的文本嵌入。
- 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)
通用句子编码器
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})