from sentence_transformers import SentenceTransformer, util
sentences = [
'какое состояние может определить тест с физической нагрузкой',
'Тест с физической нагрузкой разработан, чтобы выяснить, содержат ли одна или несколько коронарных артерий, питающих сердце, жировые отложения (бляшки), которые блокируют кровеносный сосуд на 70% или более. Для подтверждения результата часто требуется дополнительное тестирование. Результат испытаний.',
'Тест направлен на то, чтобы выяснить, не получает ли какой-либо участок сердечной мышцы достаточный кровоток во время тренировки. Он похож на тест с физической нагрузкой, фармакологический или химический стресс-тест. Он также известен при стресс-тесте таллием, сканировании перфузии миокарда или радионуклидном тесте.'
]
model = SentenceTransformer('DiTy/bi-encoder-russian-msmarco')
embeddings = model.encode(sentences)
results = util.semantic_search(embeddings[0], embeddings[1:])[0]
print(f"Sentence similarity: {results}")
# `Sentence similarity: [{'corpus_id': 0, 'score': 0.8545001149177551}, {'corpus_id': 1, 'score': 0.023047829046845436}]`
Usage (HuggingFace Transformers)
Without
sentence-transformers
, you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.
from transformers import AutoTokenizer, AutoModel
import torch
#Mean Pooling - Take attention mask into account for correct averagingdefmean_pooling(model_output, attention_mask):
token_embeddings = model_output[0] #First element of model_output contains all token embeddings
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
# Sentences we want sentence embeddings for
sentences = [
'красный плоский лишай вызван стрессом',
'В большинстве случаев причину появления красного плоского лишая невозможно. Это не вызвано стрессом, но иногда эмоциональный стресс усугубляет ситуацию. Известно, что это заболевание возникает после контакта с определенными химическими веществами, такими как те, которые используются для проявления цветных фотографий. У некоторых людей определенные лекарства вызывают красный плоский лишай. Эти препараты включают лекарства от высокого кровяного давления, болезней сердца, диабета, артрита и малярии, антибиотики, нестероидные противовоспалительные обезболивающие и т. Д.',
'К сожалению для работодателей, в разных штатах страны есть несколько дел, по которым суды установили, что стресс, вызванный работой, может быть основанием для увольнения с работы, если стресс достигает уровня серьезного состояния здоровья, которое вызывает они не могут выполнять свою работу.',
]
# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('DiTy/bi-encoder-russian-msmarco')
model = AutoModel.from_pretrained('DiTy/bi-encoder-russian-msmarco')
# Tokenize sentences
encoded_input = tokenizer(sentences, max_length=512, padding='max_length', truncation=True, return_tensors='pt')
# Compute token embeddingswith torch.no_grad():
model_output = model(**encoded_input)
# Perform pooling. In this case, mean pooling.
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
print("Sentence embeddings:")
print(sentence_embeddings)
Training
The model was trained with the parameters:
DataLoader
:
torch.utils.data.dataloader.DataLoader
of length 1989041 with parameters:
bi-encoder-russian-msmarco huggingface.co is an AI model on huggingface.co that provides bi-encoder-russian-msmarco's model effect (), which can be used instantly with this DiTy bi-encoder-russian-msmarco model. huggingface.co supports a free trial of the bi-encoder-russian-msmarco model, and also provides paid use of the bi-encoder-russian-msmarco. Support call bi-encoder-russian-msmarco model through api, including Node.js, Python, http.
bi-encoder-russian-msmarco huggingface.co is an online trial and call api platform, which integrates bi-encoder-russian-msmarco's modeling effects, including api services, and provides a free online trial of bi-encoder-russian-msmarco, you can try bi-encoder-russian-msmarco online for free by clicking the link below.
DiTy bi-encoder-russian-msmarco online free url in huggingface.co:
bi-encoder-russian-msmarco is an open source model from GitHub that offers a free installation service, and any user can find bi-encoder-russian-msmarco on GitHub to install. At the same time, huggingface.co provides the effect of bi-encoder-russian-msmarco install, users can directly use bi-encoder-russian-msmarco installed effect in huggingface.co for debugging and trial. It also supports api for free installation.
bi-encoder-russian-msmarco install url in huggingface.co: