Views
No views yet
pip install -q sentence-transformers1from sentence_transformers import SentenceTransformer
2from torch.nn import functional as F
3
4
5sentences = ["Mỗi hiệp bóng đá kéo dài bao lâu",
6 "Một trận đấu bóng đá thông thường có hai hiệp , mỗi hiệp 45 phút với khoảng thời gian 15 phút nghỉ giữa hai hiệp .",
7 "Cũng trong thập niên 1850 , các đội bóng nghiệp dư bắt đầu được thành lập và thường mỗi đội xây dựng cho riêng họ những luật chơi mới của môn bóng đá , trong đó đáng chú ý có câu lạc bộ Sheffield F.C .. Việc mỗi đội bóng có luật chơi khác nhau khiến việc điều hành mỗi trận đấu giữa họ diễn ra rất khó khăn ."]
8
9model = SentenceTransformer('thehosy/vi-roberta-base-qa-embedding')
10model.eval()
11
12embeddings = model.encode(sentences, convert_to_tensor=True)
13vecs = F.normalize(embeddings)
14sim_scores = F.cosine_similarity(vecs[:1], vecs[1:])
15print(sim_scores)
16
17# tensor([0.9971, 0.3511])1from transformers import AutoTokenizer, AutoModel
2import torch
3from torch.nn import functional as F
4
5
6#Mean Pooling - Take attention mask into account for correct averaging
7def mean_pooling(model_output, attention_mask):
8 token_embeddings = model_output.last_hidden_state
9 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
10 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
11
12
13sentences = ["Mỗi hiệp bóng đá kéo dài bao lâu",
14 "Một trận đấu bóng đá thông thường có hai hiệp , mỗi hiệp 45 phút với khoảng thời gian 15 phút nghỉ giữa hai hiệp .",
15 "Cũng trong thập niên 1850 , các đội bóng nghiệp dư bắt đầu được thành lập và thường mỗi đội xây dựng cho riêng họ những luật chơi mới của môn bóng đá , trong đó đáng chú ý có câu lạc bộ Sheffield F.C .. Việc mỗi đội bóng có luật chơi khác nhau khiến việc điều hành mỗi trận đấu giữa họ diễn ra rất khó khăn ."]
16
17# Load model from HuggingFace Hub
18tokenizer = AutoTokenizer.from_pretrained('thehosy/vi-roberta-base-qa-embedding')
19model = AutoModel.from_pretrained('thehosy/vi-roberta-base-qa-embedding')
20model.eval()
21
22# Tokenize sentences
23encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
24# Compute token embeddings
25with torch.no_grad():
26 model_output = model(**encoded_input)
27
28embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
29vecs = F.normalize(embeddings)
30sim_scores = F.cosine_similarity(vecs[:1], vecs[1:])
31print(sim_scores)
32
33# tensor([0.9971, 0.3511])torch.utils.data.dataloader.DataLoader of length 2621440 with parameters:{'batch_size': 32, 'sampler': None, 'batch_sampler': None, 'shuffle': true}Triplet lossSentenceTransformer(
(0): Transformer({'max_seq_length': 768, 'do_lower_case': False}) with Transformer model: RobertaModel
(1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False})
)