🚀 NaSE (新闻适配句子编码器)
NaSE 是一个新闻适配的句子编码器,它基于预训练的大规模多语言句子编码器 LaBSE 进行领域专业化调整。该模型能够输出捕获文本语义信息的向量,可用于句子相似度计算、信息检索或聚类等任务。
🚀 快速开始
本模型可用于获取给定文本的句子嵌入。以下是在 PyTorch 和 TensorFlow 中使用该模型的示例代码。
💻 使用示例
基础用法
from transformers import BertModel, BertTokenizerFast
tokenizer = BertTokenizerFast.from_pretrained('aiana94/NaSE')
model = BertModel.from_pretrained('aiana94/NaSE')
sentences = ["This is an example sentence", "Dies ist auch ein Beispielsatz in einer anderen Sprache."]
encoded_input = tokenizer(sentences, return_tensors='pt', padding=True)
with torch.no_grad():
output = model(**encoded_input)
sentence_embeddings = output.pooler_output
高级用法
from transformers import TFBertModel, BertTokenizerFast
tokenizer = BertTokenizerFast.from_pretrained('aiana94/NaSE')
model = TFBertModel.from_pretrained('aiana94/NaSE')
sentences = ["This is an example sentence", "Dies ist auch ein Beispielsatz in einer anderen Sprache."]
encoded_input = tokenizer(sentences, return_tensors='tf', padding=True)
with torch.no_grad():
output = model(**encoded_input)
sentence_embeddings = output.pooler_output
对于句子之间的相似度计算,建议在计算相似度之前进行 L2 归一化:
import torch
import torch.nn.functional as F
def cos_sim(a: torch.Tensor, b: torch.Tensor):
a_norm = F.normalize(a, p=2, dim=1)
b_norm = F.normalize(b, p=2, dim=1)
return torch.mm(a_norm, b_norm.transpose(0, 1))
📚 详细文档
✨ 主要特性
NaSE 是一个领域适配的多语言句子编码器,它从 LaBSE 初始化而来,并使用两个多语言语料库 Polynews 和 PolyNewsParallel 进行新闻领域的专业化调整。该模型有两个预训练目标:去噪自编码和序列到序列机器翻译。
📦 安装指南
暂未提供安装步骤相关内容。
🔧 技术细节
训练数据
NaSE 使用两个多语言数据集进行领域适配:Polynews 和并行的 PolyNewsParallel。
在为模型训练采样时,使用以下过程来平滑每种语言的分布:
- 分别从 PolyNews 和 PolyNewsParallel 中仅采样至少包含 100 篇文本的语言和语言对;
- 通过从修改后的分布 p(L) ~ |L| * alpha 中采样语言 L 的文本,其中 |L| 是示例数量,使用平滑率 alpha = 0.3(即对低资源语言进行上采样,对高资源语言进行下采样)。
训练过程
使用多语言句子编码器 LaBSE 的预训练权重初始化 NaSE。有关预训练过程的更多详细信息,请参考其 模型卡片 或相应的 论文。
使用两个目标将多语言句子编码器适配到新闻领域:
- 去噪自编码(DAE):从通过添加离散噪声获得的损坏版本中重建原始输入句子(详情请参阅 TSDAE);
- 机器翻译(MT):从源语言输入句子生成目标语言翻译(即源语言构成目标语言中目标句子 x 的“损坏”,需要进行“重建”)。
NaSE 按顺序进行训练,首先进行重建训练,然后进行翻译训练,即在并行数据上继续训练通过 DAE 目标获得的 NaSE 编码器以进行翻译。
训练超参数
- 训练模式:fp16 混合精度
- 训练步数:100k(每个目标 50K),每 5K 步进行一次验证
- 学习率:3e-5
- 优化器:AdamW
完整的训练脚本可在 训练代码 中获取。
技术规格
该模型在 1 个 40GB NVIDIA A100 GPU 上进行了总共 100k 步的预训练。
📄 许可证
本模型使用 Apache-2.0 许可证。
引用
BibTeX:
@misc{iana2024news,
title={News Without Borders: Domain Adaptation of Multilingual Sentence Embeddings for Cross-lingual News Recommendation},
author={Andreea Iana and Fabian David Schmidt and Goran Glavaš and Heiko Paulheim},
year={2024},
eprint={2406.12634},
archivePrefix={arXiv},
url={https://arxiv.org/abs/2406.12634}
}
信息表格