BERT可视化工具bertviz体验

BertViz是一款交互式工具,用于在Transformer模型中可视化注意力网络。它支持BERT、GPT2等模型,并可通过Python API在Jupyter或Colab中使用。BertViz提供多种视图帮助理解注意力机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bertviz简介

BertViz 是一种交互式工具,用于在Transformer语言模型(如 BERT、GPT2 或 T5)中可视化注意力网络。它可以通过支持大多数Huggingface 模型,可以简单地通过 Python API 在 Jupyter 或 Colab 笔记本中运行。BertViz 扩展了 Llion Jones的Tensor2Tensor 可视化工具,添加了多个视图,每个视图都为注意力机制提供了独特的视角。

具体计算原理:https://towardsdatascience.com/deconstructing-bert-part-2-visualizing-the-inner-workings-of-attention-60a16d86b5c1

安装命令

  • pip安装
pip install bertviz
  • 其他依赖安装
pip install jupyterlab
pip install ipywidgets

可视化例子

构建数据与模型
from bertviz import head_view, model_view
from transformers import BertTokenizer, BertModel
model_version = 'bert-base-uncased'
model = BertModel.from_pretrained(model_version, output_attentions=True)
tokenizer = BertTokenizer.from_pretrained(model_version)
sentence_a = "The cat sat on the mat"
sentence_b = "The cat lay on the rug"
inputs = tokenizer.encode_plus(sentence_a, sentence_b, return_tensors='pt')
input_ids = inputs['input_ids']
token_type_ids = inputs['token_type_ids']
attention = model(input_ids, token_type_ids=token_type_ids)[-1]
sentence_b_start = token_type_ids[0].tolist().index(1)
input_id_list = input_ids[0].tolist() # Batch index 0
tokens = tokenizer.convert_ids_to_tokens(input_id_list) 
Some weights of the model checkpoint at bert-base-uncased were not used when initializing BertModel: ['cls.seq_relationship.weight', 'cls.predictions.transform.LayerNorm.bias', 'cls.predictions.transform.dense.bias', 'cls.predictions.decoder.weight', 'cls.predictions.transform.dense.weight', 'cls.seq_relationship.bias', 'cls.predictions.bias', 'cls.predictions.transform.LayerNorm.weight']
- This IS expected if you are initializing BertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing BertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
注意力头可视化

注意力头视图可视化来自单个 Transformer 层的一个或多个头部的注意力。 每行显示从一个标记(左)到另一个标记(右)的注意力。 线重反映注意力值(范围从 0 到 1),而线条颜色标识注意力头。 选择多个头时(由顶部的彩色片状表示),相应的可视化彼此叠加。 具体解释可以查看博客

head_view(attention, tokens, sentence_b_start)

👉 将鼠标悬停在可视化左侧/右侧的任何标记上,以过滤来自/到该标记的注意力。

👉 双击顶部的任何彩色图块以过滤到相应的注意力头。

👉 单击任何彩色图块以切换选择相应的注意力头。

👉 单击图层下拉菜单以更改模型图层(零索引)。

模型视图

模型视图提供了整个模型中注意力的预览图。 每个单元格显示特定头部的注意力权重,按层(行)和头部(列)索引。 每个单元格中的线表示从一个标记(左)到另一个标记(右)的注意力,线重与注意力值成正比(范围从 0 到 1)。 具体解释可以查看博客
用法:

👉单击任何单元格以查看相关注意力头的注意力详细视图(或取消选择该单元格)。

👉 然后将鼠标悬停在详细视图左侧的任何标记上以过滤来自该标记的注意力。

model_view(attention, tokens, sentence_b_start)

神经元视图

神经元视图可视化用于计算注意力的中间表示(例如查询和关键向量)。在折叠视图(初始状态)中,线条显示了从每个标记(左)到每个其他标记(右)的注意力。在展开的视图中,该工具跟踪产生这些注意力权重的计算链。关于注意力机制的详细解释,请参考博客

用法:

👉 将鼠标悬停在可视化左侧的任何标记上,以过滤来自该标记的注意力。

👉然后单击悬停时显示的加号图标。这暴露了用于计算注意力权重的查询向量、关键向量和其他中间表示。每个色带代表一个神经元值,其中颜色强度表示幅度,色调表示符号(蓝色=正,橙色=负)。

👉 进入展开视图后,将鼠标悬停在左侧的任何其他标记上以查看相关的注意力计算。

👉 单击图层或头部下拉菜单以更改模型图层或头部(零索引)。

from bertviz.transformers_neuron_view import BertModel, BertTokenizer
from bertviz.neuron_view import show

model_type = 'bert'
model_version = 'bert-base-uncased'
model = BertModel.from_pretrained(model_version, output_attentions=True)
tokenizer = BertTokenizer.from_pretrained(model_version, do_lower_case=True)
show(model, model_type, tokenizer, sentence_a, sentence_b, layer=4, head=3)

### BERT模型可视化工具和图表展示 #### 工具介绍 目前存在多种针对BERT模型的可视化工具,能够帮助研究者更好地理解和调试模型的行为。其中一种常用的在线交互式工具是由Hugging Face提供的ExBert[^4]。该工具允许用户通过可视化的形式探索BERT在处理特定文本时的关注机制(Attention Mechanism),并能动态调整输入以观察不同层之间的注意力分布变化。 另外,在实际项目开发过程中,如果需要更深入地了解模型内部结构以及训练过程,则可以利用TensorBoard配合PyTorch Lightning或者Transformers库来记录日志并生成相应的图形表示[^2]。例如,在进行IMDB电影评论情感分类任务时,可以通过配置合适的回调函数将损失曲线、准确率等指标绘制成时间序列图谱以便监控整个流程进展状况。 #### 图表类型 以下是几种常见的用于解释BERT工作原理及其性能表现的数据呈现方式: 1. **注意力热力图(Heatmap)** 这种类型的图表主要用于揭示各个子词(token)之间相互作用强度大小关系。每一行代表一个查询向量(Query Vector),列则对应于键向量(Key Vectors);颜色深浅反映两者乘积经过Softmax操作后的概率值高低程度。借助此类图像可以帮助识别哪些部分对于最终预测结果贡献较大。 2. **嵌入空间投影(Embedding Space Projection)** 使用t-SNE或UMAP算法降维后得到二维平面上点群布局情况,从而直观看出相似样本聚集趋势特征。这种方法特别适合评估语义相近度较高的词语是否被正确编码到接近区域之中[^5]。 3. **梯度累积路径(Gradient Flow Analysis)** 当面对复杂深层架构可能出现梯度消失等问题时,绘制各隐藏单元相对于目标变量偏导数绝对值得走势有助于诊断潜在瓶颈所在位置,并据此采取相应措施改善收敛特性。 ```python import matplotlib.pyplot as plt from sklearn.manifold import TSNE import numpy as np def plot_embedding(embeddings, labels): tsne_model = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000) new_values = tsne_model.fit_transform(embeddings) x_coords = [] y_coords = [] for value in new_values: x_coords.append(value[0]) y_coords.append(value[1]) plt.figure(figsize=(16, 16)) for i in range(len(x_coords)): plt.text(x_coords[i], y_coords[i], labels[i], fontsize=12) plt.xlim(min(x_coords)-abs((max(x_coords)-min(x_coords))/10), max(x_coords)+abs((max(x_coords)-min(x_coords))/10)) plt.ylim(min(y_coords)-abs((max(y_coords)-min(y_coords))/10), max(y_coords)+abs((max(y_coords)-min(y_coords))/10)) plt.show() ``` 此代码片段定义了一个简单的函数`plot_embedding()`,它可以接受一组高维embedding vectors 和对应的label作为输入参数,并运用t-Distributed Stochastic Neighbor Embedding (t-SNE) 技术将其转换成易于理解的形式展现出来。 #### 小结 综上所述,无论是为了教学目的还是科研需求,恰当选用不同的可视化手段都能够极大地促进人们对像BERT这样的大型语言模型的理解水平提升。同时也要注意合理设置超参选项以获得最佳效果。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值