🚀 roberta-zwnj-wnli-mean-tokens
句子嵌入模型
本项目借助 roberta-zwnj-wnli-mean-tokens
模型实现句子嵌入功能,可用于特征提取、句子相似度计算等任务,为自然语言处理相关应用提供有力支持。
🚀 快速开始
📦 安装指南
若要使用该模型,你需要安装 sentence-transformers 库,可通过以下命令进行安装:
pip install -U sentence-transformers
💻 使用示例
基础用法(使用 sentence-transformers 库)
from sentence_transformers import SentenceTransformer
sentences = [
'اولین حکمران شهر بابل کی بود؟',
'در فصل زمستان چه اتفاقی افتاد؟',
'میراث کوروش'
]
model = SentenceTransformer('m3hrdadfi/roberta-zwnj-wnli-mean-tokens')
embeddings = model.encode(sentences)
print(embeddings)
高级用法(不使用 sentence-transformers 库)
不使用 sentence-transformers 库时,你需要先将输入数据传入 Transformer 模型,然后对上下文词嵌入应用合适的池化操作。
from transformers import AutoTokenizer, AutoModel
import torch
def max_pooling(model_output, attention_mask):
token_embeddings = model_output[0]
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
token_embeddings[input_mask_expanded == 0] = -1e9
return torch.mean(token_embeddings, 1)[0]
sentences = [
'اولین حکمران شهر بابل کی بود؟',
'در فصل زمستان چه اتفاقی افتاد؟',
'میراث کوروش'
]
tokenizer = AutoTokenizer.from_pretrained('m3hrdadfi/roberta-zwnj-wnli-mean-tokens')
model = AutoModel.from_pretrained('m3hrdadfi/roberta-zwnj-wnli-mean-tokens')
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
with torch.no_grad():
model_output = model(**encoded_input)
sentence_embeddings = max_pooling(model_output, encoded_input['attention_mask'])
print("Sentence embeddings:")
print(sentence_embeddings)
问题反馈
如果你在使用过程中遇到问题,可从 这里 提交 GitHub issue。