Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Paper • 1908.10084 • Published • 16
How to use along26/mpnet-base-manglish-triplet with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("along26/mpnet-base-manglish-triplet")
sentences = [
"Why have critics called for a thorough investigation of Najib Razak's involvement in the 1MDB scandal, despite his repeated denials of wrongdoing?",
"Untuk melakukan analisis diskriminasi linear, kita perlu mengira vektor min untuk setiap kelas, matriks kovarians, dan songsangan matriks kovarians.\n\nPurata vektor untuk setiap kelas:\nKelas 0: μ0 = ( (1+2+3+4)/4 , (6+5+7+10)/4 ) = (2.5, 7)\nKelas 1: μ1 = ( (3+4+5+6)/4 , (2+3+1+3)/4 ) = (4.5, 2.25)\n\nMatriks kovarians:\nPertama, kita mengira matriks sisihan untuk setiap kelas:\nKelas 0:\n[\n(1-2.5, 6-7),\n(2-2.5, 5-7),\n(3-2.5, 7-7),\n(4-2.5, 10-7)\n]\n=>\n[\n(-1.5, -1),\n(-0.5, -2),\n(0.5, 0),\n(1.5, 3)\n]\n\nKelas 1:\n[\n(3-4.5, 2-2.25),\n(4-4.5, 3-2.25),\n(5-4.5, 1-2.25),\n(6-4.5, 3-2.25)\n]\n=>\n[\n(-1.5, -0.25),\n(-0.5, 0.75),\n(0.5, -1.25),\n(1.5, 0.75)\n]\n\nSekarang, kita mengira matriks kovarians untuk setiap kelas:\nCov0 = (1/(4-1)) * (Σ (sisihan0 * sisihan0.T))\nCov1 = (1/(4-1)) * (Σ (sisihan1 * sisihan1.T))\n\nCov0 =\n[\n(1/3) * ((-1.5)^2 + (-0.5)^2 + (0.5)^2 + (1.5)^2), (1/3) * ((-1.5)*(-1) + (-0.5)*(-2) + (0.5)*(0) + (1.5)*(3)),\n(1/3) * ((-1)*(-1.5) + (-2)*(-0.5) + (0)*(0.5) + (3)*(1.5)), (1/3) * ((-1)^2 + (-2)^2 + (0)^2 + (3)^2)\n]\n=>\n[\n(1.5, 1.5),\n(1.5, 3)\n]\n\nCov1 =\n[\n(1/3) * ((-1.5)^2 + (-0.5)^2 + (0.5)^2 + (1.5)^2), (1/3) * ((-1.5)*(-0.25) + (-0.5)*(0.75) + (0.5)*(-1.25) + (1.5)*(0.75)),\n(1/3) * ((-0.25)*(-1.5) + (0.75)*(-0.5) + (-1.25)*(0.5) + (0.75)*(1.5)), (1/3) * ((-0.25)^2 + (0.75)^2 + (-1.25)^2 + (0.75)^2)\n]\n=>\n[\n(1.5, 0.5),\n(0.5, 1)\n]\n\nSekarang, kita mengira matriks kovarians terkumpul:\nCov_pooled = (1/2) * (Cov0 + Cov1)\n=>\n[\n(1/2) * (1.5 + 1.5), (1/2) * (1.5 + 0.5),\n(1/2) * (1.5 + 0.5), (1/2) * (3 + 1)\n]\n=>\n[\n(1.5, 1),\n(1, 2)\n]\n\nSekarang, kita mengira songsangan matriks kovarians terkumpul:\nCov_pooled_inv =\n[\n(2, -1),\n(-1, 1.5)\n]\n\nSekarang, kita boleh mengira pekali persamaan sempadan:\na = (μ1 - μ0) * Cov_pooled_inv\n=>\n[\n(4.5 - 2.5, 2.25 - 7)\n]\n*\n[\n(2, -1),\n(-1, 1.5)\n]\n=>\n[\n(2, -4.75)\n]\n*\n[\n(2, -1),\n(-1, 1.5)\n]\n=>\n(2*2 + (-4.75)*(-1), 2*(-1) + (-4.75)*1.5)\n=>\n(4 + 4.75, -2 - 7.125)\n=>\n(8.75, -9.125)\n\nb = -0.5 * (μ1 * Cov_pooled_inv * μ1.T - μ0 * Cov_pooled_inv * μ0.T)\n=>\n-0.5 * (\n(4.5*2 + 2.25*(-1))*(4.5) + (2.5*2 + 7*(-1))*(2.5)\n)\n=>\n-0.5 * (\n(9 - 2.25)*4.5 + (5 - 7)*2.5\n)\n=>\n-0.5 * (\n(6.75)*4.5 + (-2)*2.5\n)\n=>\n-0.5 * (\n30.375 - 5\n)\n=>\n-0.5 * 25.375\n=>\n-12.6875\n\nJadi, persamaan sempadan ialah:\n8.75x1 - 9.125x2 - 12.6875 = 0",
"Mengapa pengkritik meminta siasatan menyeluruh terhadap penglibatan Najib Razak dalam skandal 1MDB, walaupun beliau berulang kali menafikan kesalahan?",
"How have plants evolved to adapt to different environmental conditions such as high altitude, arctic regions, deserts, and wetlands?"
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from microsoft/mpnet-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': 'MPNetModel'})
(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})
)
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("along26/mpnet-base-manglish-triplet")
# Run inference
sentences = [
'A string of length 10 m and mass 0.01 kg is fixed at both ends. The wave function of the string is given as y(x,t) = 2sin(3x - 4t) where x and y are in meters and t is in seconds. \n\nWhat is the tension in the string?',
'Seutas tali panjang 10 m dan berjisim 0.01 kg diikat pada kedua-dua hujungnya. Fungsi gelombang rentetan diberikan sebagai y(x,t) = 2sin(3x - 4t) dengan x dan y dalam meter dan t dalam saat.\n\nApakah ketegangan dalam tali?',
"How has Najib Razak's handling of the economy been criticized, and what impact has this had on his political standing?",
]
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.7525, 0.9936],
# [-0.7525, 1.0000, -0.7687],
# [ 0.9936, -0.7687, 1.0000]])
manglish-dev and manglish-testTripletEvaluator| Metric | manglish-dev | manglish-test |
|---|---|---|
| cosine_accuracy | 0.0 | 0.0 |
anchor, positive, and negative| anchor | positive | negative | |
|---|---|---|---|
| type | string | string | string |
| details |
|
|
|
| anchor | positive | negative |
|---|---|---|
Consider a graph with 8 vertices and 12 edges. Determine if the graph contains a perfect matching. If it does, provide one example of a perfect matching. If it does not, explain why a perfect matching is not possible. |
Pertimbangkan graf dengan 8 bucu dan 12 tepi. Tentukan sama ada graf mengandungi padanan sempurna. Jika ya, berikan satu contoh padanan yang sempurna. Jika tidak, jelaskan mengapa padanan yang sempurna tidak dapat dilakukan. |
The 1MDB scandal and the corruption charges against former Malaysian Prime Minister Najib Razak offer several important lessons for Malaysia and other countries: |
What is the probability of flipping a fair coin three times and getting exactly two heads in a row? |
Apakah kebarangkalian membalikkan syiling saksama tiga kali dan mendapat tepat dua kepala berturut-turut? |
Why is corruption so rampant in Malaysia, with politicians and government officials often caught engaging in unethical practices? |
Why have there been allegations of corruption and mismanagement in Malaysia's state-owned enterprises, and what measures have been taken to address these issues? |
Mengapa terdapat tuduhan rasuah dan salah urus dalam perusahaan milik kerajaan Malaysia, dan apakah langkah-langkah yang telah diambil untuk menangani isu-isu ini? |
What is the pKa value of acetic acid, and how does it affect its acid strength when compared to other organic acids such as citric acid or benzoic acid? Provide an explanation for your answer using acid-base reaction principles in organic chemistry. |
TripletLoss with these parameters:{
"distance_metric": "TripletDistanceMetric.EUCLIDEAN",
"triplet_margin": 5
}
anchor, positive, and negative| anchor | positive | negative | |
|---|---|---|---|
| type | string | string | string |
| details |
|
|
|
| anchor | positive | negative |
|---|---|---|
In a set of 50 data points, the mean is 70 and the standard deviation is 10. If an outlier is defined as any data point that is more than three standard deviations away from the mean, how many outliers are there in the data set? |
Dalam set 50 titik data, min ialah 70 dan sisihan piawai ialah 10. Jika outlier ditakrifkan sebagai mana-mana titik data yang jauh lebih daripada tiga sisihan piawai daripada min, berapakah jumlah outlier yang terdapat dalam set data? |
There is still a shortage of affordable housing for the lower and middle-income groups in Malaysia due to several factors, including rapid urbanization, population growth, and rising housing prices. According to the World Bank, Malaysia's urbanization rate reached 76% in 2019, and the country's population is expected to grow to 36 million by 2040, putting pressure on the housing market. |
Why have some analysts argued that the corruption charges against Najib Razak represent a broader problem of endemic corruption in Malaysian politics, and what steps can be taken to address this issue? |
Mengapa beberapa penganalisis berhujah bahawa tuduhan rasuah terhadap Najib Razak mewakili masalah rasuah endemik yang lebih luas dalam politik Malaysia, dan apakah langkah yang boleh diambil untuk menangani isu ini? |
What is the current understanding of the large-scale structure of the universe, and what evidence supports this model? |
How has Malaysia's political landscape changed since the 2018 general election, which saw the ouster of Najib Razak and his UMNO-led coalition, and what challenges does the new government face in combating corruption? |
Bagaimanakah landskap politik Malaysia berubah sejak pilihan raya umum 2018, yang menyaksikan penyingkiran Najib Razak dan gabungan pimpinan UMNOnya, dan apakah cabaran yang dihadapi kerajaan baharu dalam memerangi rasuah? |
Snell's Law states that the ratio of the sine of the angle of incidence to the sine of the angle of refraction is equal to the ratio of the refractive indices of the two media. Mathematically, it can be written as: |
TripletLoss with these parameters:{
"distance_metric": "TripletDistanceMetric.EUCLIDEAN",
"triplet_margin": 5
}
eval_strategy: stepsper_device_train_batch_size: 4gradient_accumulation_steps: 4warmup_ratio: 0.1fp16: Truedataloader_pin_memory: Falseoverwrite_output_dir: Falsedo_predict: Falseeval_strategy: stepsprediction_loss_only: Trueper_device_train_batch_size: 4per_device_eval_batch_size: 8per_gpu_train_batch_size: Noneper_gpu_eval_batch_size: Nonegradient_accumulation_steps: 4eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 5e-05weight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1.0num_train_epochs: 3max_steps: -1lr_scheduler_type: linearlr_scheduler_kwargs: {}warmup_ratio: 0.1warmup_steps: 0log_level: passivelog_level_replica: warninglog_on_each_node: Truelogging_nan_inf_filter: Truesave_safetensors: Truesave_on_each_node: Falsesave_only_model: Falserestore_callback_states_from_checkpoint: Falseno_cuda: Falseuse_cpu: Falseuse_mps_device: Falseseed: 42data_seed: Nonejit_mode_eval: Falsebf16: Falsefp16: Truefp16_opt_level: O1half_precision_backend: autobf16_full_eval: Falsefp16_full_eval: Falsetf32: Nonelocal_rank: 0ddp_backend: Nonetpu_num_cores: Nonetpu_metrics_debug: Falsedebug: []dataloader_drop_last: Falsedataloader_num_workers: 0dataloader_prefetch_factor: Nonepast_index: -1disable_tqdm: Falseremove_unused_columns: Truelabel_names: Noneload_best_model_at_end: Falseignore_data_skip: Falsefsdp: []fsdp_min_num_params: 0fsdp_config: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}fsdp_transformer_layer_cls_to_wrap: Noneaccelerator_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: Noneadafactor: Falsegroup_by_length: Falselength_column_name: lengthproject: huggingfacetrackio_space_id: trackioddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falsedataloader_pin_memory: Falsedataloader_persistent_workers: Falseskip_memory_metrics: Trueuse_legacy_prediction_loop: Falsepush_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_inputs_for_metrics: Falseinclude_for_metrics: []eval_do_concat_batches: Truefp16_backend: autopush_to_hub_model_id: Nonepush_to_hub_organization: Nonemp_parameters: auto_find_batch_size: Falsefull_determinism: Falsetorchdynamo: Noneray_scope: lastddp_timeout: 1800torch_compile: Falsetorch_compile_backend: Nonetorch_compile_mode: Noneinclude_tokens_per_second: Falseinclude_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: Trueprompts: Nonebatch_sampler: batch_samplermulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}| Epoch | Step | Training Loss | Validation Loss | manglish-dev_cosine_accuracy | manglish-test_cosine_accuracy |
|---|---|---|---|---|---|
| -1 | -1 | - | - | 0.1400 | - |
| 0.08 | 50 | 1.6398 | - | - | - |
| 0.16 | 100 | 0.0828 | - | - | - |
| 0.24 | 150 | 0.0358 | - | - | - |
| 0.32 | 200 | 0.0113 | 0.0 | 0.0 | - |
| 0.4 | 250 | 0.0167 | - | - | - |
| 0.48 | 300 | 0.0 | - | - | - |
| 0.56 | 350 | 0.0 | - | - | - |
| 0.64 | 400 | 0.0 | 0.0 | 0.0 | - |
| 0.72 | 450 | 0.0 | - | - | - |
| 0.8 | 500 | 0.0 | - | - | - |
| 0.88 | 550 | 0.0007 | - | - | - |
| 0.96 | 600 | 0.0699 | 0.0074 | 0.0 | - |
| 1.04 | 650 | 0.0231 | - | - | - |
| 1.12 | 700 | 0.0158 | - | - | - |
| 1.2 | 750 | 0.0107 | - | - | - |
| 1.28 | 800 | 0.0039 | 0.0 | 0.0 | - |
| 1.3600 | 850 | 0.0 | - | - | - |
| 1.44 | 900 | 0.0 | - | - | - |
| 1.52 | 950 | 0.0114 | - | - | - |
| 1.6 | 1000 | 0.0115 | 0.0 | 0.0 | - |
| 1.6800 | 1050 | 0.0 | - | - | - |
| 1.76 | 1100 | 0.0025 | - | - | - |
| 1.8400 | 1150 | 0.0042 | - | - | - |
| 1.92 | 1200 | 0.0012 | 0.0 | 0.0 | - |
| 2.0 | 1250 | 0.0 | - | - | - |
| 2.08 | 1300 | 0.0 | - | - | - |
| 2.16 | 1350 | 0.0 | - | - | - |
| 2.24 | 1400 | 0.0064 | 0.0 | 0.0 | - |
| 2.32 | 1450 | 0.0 | - | - | - |
| 2.4 | 1500 | 0.0 | - | - | - |
| 2.48 | 1550 | 0.0 | - | - | - |
| 2.56 | 1600 | 0.0 | 0.0 | 0.0 | - |
| 2.64 | 1650 | 0.0 | - | - | - |
| 2.7200 | 1700 | 0.0089 | - | - | - |
| 2.8 | 1750 | 0.0 | - | - | - |
| 2.88 | 1800 | 0.0 | 0.0 | 0.0 | - |
| 2.96 | 1850 | 0.0 | - | - | - |
| -1 | -1 | - | - | - | 0.0000 |
@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{hermans2017defense,
title={In Defense of the Triplet Loss for Person Re-Identification},
author={Alexander Hermans and Lucas Beyer and Bastian Leibe},
year={2017},
eprint={1703.07737},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
Base model
microsoft/mpnet-base