Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Paper • 1908.10084 • Published • 15
How to use ghost-beard-9942/multilingual-e5-base-custom-finetune with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("ghost-beard-9942/multilingual-e5-base-custom-finetune")
sentences = [
"query: Classic Curry Powder Mild 100g",
"passage: Products for personal hygiene, body care, grooming, and feminine/infant care — not household cleaning. Shampoo, Conditioner, Duschgel, Seife, Handseife, Körperlotion, Bodylotion. Zahnpasta, Zahnbürste, Mundwasser, Zahnseide. Deo, Deodorant, Antitranspirant, Parfüm, Rasierer, Rasiercreme, Aftershave. Tampons, Binden, Menstruationstasse, Windeln, Babyfeuchttücher, Babycreme. Sonnencreme, Lippenpflege, Gesichtscreme, Akne-Gel, Kondome. shampooing, gel douche, dentifrice, déodorant, champú, gel de ducha, pasta de dientes.",
"passage: Liquid fats, vinegars, and ready-made salad dressings used in cooking or as condiments. Olivenöl, Rapsöl, Sonnenblumenöl, Kokosöl, Sesamöl, Leinöl, Trüffelöl, Walnussöl. Apfelessig, Balsamico, Weinessig, Reisessig, Weißweinessig. Salatdressing, Caesar Dressing, Vinaigrette, Joghurt-Dressing. huile d'olive, vinaigre, vinaigrette, aceite de oliva, vinagre, aliño.",
"passage: Dry seasonings, herbs, spice blends, and stock products used to flavour cooking — not sauces or fresh herbs. Salz, Pfeffer, Paprikapulver, Chilipulver, Kreuzkümmel, Kurkuma, Curry, Zimt, Muskat, Koriander. Oregano, Basilikum, Thymian, Rosmarin, Lorbeer, Majoran, getrocknete Kräuter, Kräutermischungen. Gemüsebrühe, Hühnerbrühe, Rinderbrühe, Bouillon, Suppenwürze, Maggi, Knorr. épices, herbes séchées, bouillon, condiments, especias, hierbas, caldo."
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from intfloat/multilingual-e5-base. It maps sentences & paragraphs to a 768-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, text classification, clustering, and more.
SentenceTransformer(
(0): Transformer({'max_seq_length': 512, 'do_lower_case': False, 'architecture': 'XLMRobertaModel'})
(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, 'include_prompt': True})
(2): Normalize()
)
First install the Sentence Transformers library:
pip install -U sentence-transformers
Then you can load this model and run inference.
from sentence_transformers import SentenceTransformer
# Download from the 🤗 Hub
model = SentenceTransformer("ghost-beard-9942/multilingual-e5-base-custom-finetune")
# Run inference
sentences = [
'query: Lidl Toffees de mantequilla Original 200g',
'passage: Packaged snacks, confectionery, and nuts intended for casual eating between meals. Schokolade, Gummibären, Chips, Kekse, Cracker, Popcorn, Brezel, Nachos. Erdnüsse, Mandeln, Cashews, Walnüsse, Pistazien, Studentenfutter, Nussmischungen. Riegel, Proteinriegel, Müsliriegel, Bonbons, Lollipops, Lakritze, Marshmallow. chocolat, biscuits, bonbons, noix, chips, chocolate, dulces, frutos secos.',
'passage: Non-food and uncategorised products that do not belong to any food or personal care category. Tiernahrung: Katzenfutter, Hundefutter, Vogelfutter, Tiersnacks, Aquariumbedarf. Haushaltsgegenstände: Batterien, Glühbirnen, Kerzen, Streichhölzer, Kleber, Klebeband. Bürobedarf: Stifte, Notizbücher, Druckerpapier. Blumen, Pflanzen, Erde, Dünger. Spielzeug, Zeitschriften, Bücher, Geschenkpapier. This category is a last resort — only use when no other category fits.',
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 768]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[ 1.0000, 0.7387, 0.0476],
# [ 0.7387, 1.0000, -0.0439],
# [ 0.0476, -0.0439, 1.0000]])
classification-evalInformationRetrievalEvaluator| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.9991 |
| cosine_accuracy@3 | 1.0 |
| cosine_accuracy@5 | 1.0 |
| cosine_precision@1 | 0.9991 |
| cosine_precision@3 | 0.3333 |
| cosine_precision@5 | 0.2 |
| cosine_precision@10 | 0.1 |
| cosine_recall@1 | 0.9991 |
| cosine_recall@3 | 1.0 |
| cosine_recall@5 | 1.0 |
| cosine_recall@10 | 1.0 |
| cosine_ndcg@5 | 0.9997 |
| cosine_ndcg@10 | 0.9997 |
| cosine_mrr@5 | 0.9996 |
| cosine_mrr@10 | 0.9996 |
| cosine_map@100 | 0.9996 |
sentence_0 and sentence_1| sentence_0 | sentence_1 | |
|---|---|---|
| type | string | string |
| details |
|
|
| sentence_0 | sentence_1 |
|---|---|
query: Traditional poulet Everyday Original |
passage: Animal protein products — fresh, chilled, smoked, or cured — including deli meats and processed meat substitutes. Hähnchenbrust, Rindfleisch, Schweinefleisch, Hackfleisch, Lammfleisch. Lachs, Thunfisch, Kabeljau, Garnelen, Muscheln, Fischfilet, Räucherlachs. Wurst, Salami, Schinken, Mortadella, Aufschnitt, Leberwurst, veganer Aufschnitt, Tofu-Wurst. viande, poulet, poisson, jambon, saucisson, carne, pollo, pescado, jamón. Excludes canned fish/meat (→ canned preserved foods) and frozen (→ frozen foods). |
query: Quality Erdbeermarmelade Extra 450g Deluxe |
passage: Condiments, spreads, and dips used to flavour or accompany food — not cooking oils or loose spices. Senf, Ketchup, Mayonnaise, Remoulade, BBQ-Sauce, Sriracha, Tabasco, Sojasauce, Teriyaki. Pesto, Tapenade, Hummus, Baba Ganoush, Tzatziki, Guacamole. Marmelade, Konfitüre, Honig, Erdnussbutter, Mandelmus, Nutella, Aufstrich. sauce, confiture, moutarde, mayonnaise, salsa, mermelada, crema de cacahuete. |
query: Classic Seitenbacher Müsli Verwöhnmischung 750g Deluxe |
passage: Dry staple carbohydrates and legumes requiring cooking: grains, pasta, rice, pulses, and breakfast cereals. Spaghetti, Penne, Fusilli, Nudeln, Reis, Basmatireis, Wildreis, Risotto-Reis. Haferflocken, Müsli, Granola, Cornflakes, Quinoa, Couscous, Bulgur, Polenta, Grieß. Linsen, Kichererbsen, Kidneybohnen, Erbsen, Sojabohnen (trocken). pâtes, riz, céréales, légumineuses, pasta, arroz, legumbres, cereales. |
MultipleNegativesRankingLoss with these parameters:{
"scale": 20.0,
"similarity_fct": "cos_sim",
"gather_across_devices": false
}
eval_strategy: stepsper_device_train_batch_size: 32per_device_eval_batch_size: 32num_train_epochs: 1multi_dataset_batch_sampler: round_robindo_predict: Falseeval_strategy: stepsprediction_loss_only: Trueper_device_train_batch_size: 32per_device_eval_batch_size: 32gradient_accumulation_steps: 1eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 5e-05weight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1num_train_epochs: 1max_steps: -1lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_ratio: Nonewarmup_steps: 0log_level: passivelog_level_replica: warninglog_on_each_node: Truelogging_nan_inf_filter: Trueenable_jit_checkpoint: Falsesave_on_each_node: Falsesave_only_model: Falserestore_callback_states_from_checkpoint: Falseuse_cpu: Falseseed: 42data_seed: Nonebf16: Falsefp16: Falsebf16_full_eval: Falsefp16_full_eval: Falsetf32: Nonelocal_rank: -1ddp_backend: Nonedebug: []dataloader_drop_last: Falsedataloader_num_workers: 0dataloader_prefetch_factor: Nonedisable_tqdm: Falseremove_unused_columns: Truelabel_names: Noneload_best_model_at_end: Falseignore_data_skip: Falsefsdp: []fsdp_config: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}accelerator_config: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}parallelism_config: Nonedeepspeed: Nonelabel_smoothing_factor: 0.0optim: adamw_torch_fusedoptim_args: Nonegroup_by_length: Falselength_column_name: lengthproject: huggingfacetrackio_space_id: trackioddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falsedataloader_pin_memory: Truedataloader_persistent_workers: Falseskip_memory_metrics: Truepush_to_hub: Falseresume_from_checkpoint: Nonehub_model_id: Nonehub_strategy: every_savehub_private_repo: Nonehub_always_push: Falsehub_revision: Nonegradient_checkpointing: Falsegradient_checkpointing_kwargs: Noneinclude_for_metrics: []eval_do_concat_batches: Trueauto_find_batch_size: Falsefull_determinism: Falseddp_timeout: 1800torch_compile: Falsetorch_compile_backend: Nonetorch_compile_mode: Noneinclude_num_input_tokens_seen: noneftune_noise_alpha: Noneoptim_target_modules: Nonebatch_eval_metrics: Falseeval_on_start: Falseuse_liger_kernel: Falseliger_kernel_config: Noneeval_use_gather_object: Falseaverage_tokens_across_devices: Trueuse_cache: Falseprompts: Nonebatch_sampler: batch_samplermulti_dataset_batch_sampler: round_robinrouter_mapping: {}learning_rate_mapping: {}| Epoch | Step | Training Loss | classification-eval_cosine_ndcg@10 |
|---|---|---|---|
| 0.1365 | 200 | - | 0.9554 |
| 0.2730 | 400 | - | 0.9913 |
| 0.3413 | 500 | 2.1584 | - |
| 0.4096 | 600 | - | 0.9977 |
| 0.5461 | 800 | - | 0.9987 |
| 0.6826 | 1000 | 1.5900 | 0.9993 |
| 0.8191 | 1200 | - | 0.9997 |
@inproceedings{reimers-2019-sentence-bert,
title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
author = "Reimers, Nils and Gurevych, Iryna",
booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
month = "11",
year = "2019",
publisher = "Association for Computational Linguistics",
url = "https://arxiv.org/abs/1908.10084",
}
@misc{henderson2017efficient,
title={Efficient Natural Language Response Suggestion for Smart Reply},
author={Matthew Henderson and Rami Al-Rfou and Brian Strope and Yun-hsuan Sung and Laszlo Lukacs and Ruiqi Guo and Sanjiv Kumar and Balint Miklos and Ray Kurzweil},
year={2017},
eprint={1705.00652},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
Base model
intfloat/multilingual-e5-base