Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
Paper • 1908.10084 • Published • 18
How to use michelerondinelli01/mnlp-hw1-biencoder with sentence-transformers:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("michelerondinelli01/mnlp-hw1-biencoder")
sentences = [
"how is the weather in atlanta georgia all year round",
"Southern and southeast areas of the state experience snow much less frequently than other parts of Georgia. The Georgia Piedmont, sometimes referred to as the Blue Ridge province, is somewhat cooler in winter than the coastal areas. The Southern areas of the Piedmont may receive snow every other year, while areas close to the foothills get snow a couple times a year averaging anywhere from a trace up 2\" of annual snowfall. The biggest winter threat to the northern piedmont is freezing rain which is rain that freezes on contact. The mountains of Georgia have the coolest climate and most frequent snowfall in the state, although snowfall is less than any other part of the Appalachian Mountains. The exception to this is the mountain areas of Fannin, Gilmer, Pickens, Union, White and Rabun Counties, and surrounding counties which average 3 to 8 inches of snow annually. Mountains, however, can average anywhere from 4-18 inches annually. Elevations over 4000 feet, can have some brutal winters with some storms blanketing the mountains with over a foot of snow. Heavy snow in the extreme northern counties is considered 5 inches (13 cm) or more of snow in a 12-hour period or 7 inches (18 cm) or more of snow in a 24-hour period\". Watches for heavy snow are issued when a 50 percent or greater chance of 2 inches (5.1 cm) or more of snow falling in a 12-hour period, or 4 inches (10 cm) or more in a 24-hour period is expected.The Deceptive Killers], Accessed December 11, 2007",
"National Lampoon's Christmas Vacation is a 1989 American Christmas comedy film directed by Jeremiah S. Chechik. It is the third installment in National Lampoon's Vacation film series, and was written by John Hughes, based on his short story in National Lampoon magazine, \"Christmas '59\". The film stars Chevy Chase, Beverly D'Angelo and Randy Quaid, with Juliette Lewis and Johnny Galecki as the Griswold children Audrey and Rusty, respectively.",
"The climate of Georgia is a humid subtropical climate with most of the state having short, mild winters and long, hot summers. The Atlantic Ocean on the east coast of Georgia and the hill country in the north impact the state's climate. Also, the Chattahoochee River divides Georgia into separate climatic regions with the mountain region to the northwest being cooler than the rest of the state, the average temperatures for that region in January and July being 39 °F (4 °C) and 78 °F (26 °C) respectively. Winter in Georgia is characterized by mild temperatures and little snowfall around the state, with the potential for snow and ice increasing in the northern parts of the state. Summer daytime temperatures in Georgia often exceed 95 °F (35 °C). The state experiences widespread precipitation. Tornadoes and tropical cyclones are common."
]
embeddings = model.encode(sentences)
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [4, 4]This is a sentence-transformers model finetuned from distilbert/distilbert-base-uncased. It maps sentences & paragraphs to a 768-dimensional dense vector space and can be used for retrieval.
SentenceTransformer(
(0): Transformer({'transformer_task': 'feature-extraction', 'modality_config': {'text': {'method': 'forward', 'method_output_name': 'last_hidden_state'}}, 'module_output_name': 'token_embeddings', 'architecture': 'DistilBertModel'})
(1): Pooling({'embedding_dimension': 768, 'pooling_mode': 'mean', '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("michelerondinelli01/mnlp-hw1-biencoder")
# Run inference
sentences = [
'what is the name that is given to a symbiotic relationship',
'Symbiosis can vary between mutualism, commensalism, and parasitism, though these grade into each other,. In mutualism, both organisms benefit. In commensalism, one benefits and the other is unaffected; in parasitism, one benefits and the other is harmed.',
'Some of these relationships are so close that we speak of the composite of two species as one unit; for example, we speak of the composite of algae and fungi as lichens.',
]
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.6165, 0.2146],
# [0.6165, 1.0000, 0.4963],
# [0.2146, 0.4963, 1.0000]])
dev-evalInformationRetrievalEvaluator| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.4825 |
| cosine_accuracy@3 | 0.6975 |
| cosine_accuracy@5 | 0.7712 |
| cosine_accuracy@10 | 0.8425 |
| cosine_precision@1 | 0.4825 |
| cosine_precision@3 | 0.2325 |
| cosine_precision@5 | 0.1542 |
| cosine_precision@10 | 0.0842 |
| cosine_recall@1 | 0.4825 |
| cosine_recall@3 | 0.6975 |
| cosine_recall@5 | 0.7712 |
| cosine_recall@10 | 0.8425 |
| cosine_ndcg@10 | 0.6642 |
| cosine_mrr@10 | 0.6068 |
| cosine_map@100 | 0.6116 |
sentence_0, sentence_1, and sentence_2| sentence_0 | sentence_1 | sentence_2 | |
|---|---|---|---|
| type | string | string | string |
| details |
|
|
|
| sentence_0 | sentence_1 | sentence_2 |
|---|---|---|
what are the predators of the praying mantis |
Mantises are preyed on by vertebrates such as frogs, lizards, and birds, and by invertebrates such as spiders, large species of hornets, and ants. Some hunting wasps, such as some species of Tachytes also paralyse some species of mantis to feed their young. Generally, mantises protect themselves by camouflage, most species being cryptically colored to resemble foliage or other backgrounds, both to avoid predators and to better snare their prey. Those that live on uniformly colored surfaces such as bare earth or tree bark are dorsoventrally flattened so as to eliminate shadows that might reveal their presence. The species from different families called flower mantises are aggressive mimics: they resemble flowers convincingly enough to attract prey that come to collect pollen and nectar. Some species in Africa and Australia are able to turn black after a molt towards the end of the dry season; at this time of year, bush fires occur and this coloration enables them to blend in with the fi... |
Gardeners who prefer to avoid pesticides may encourage mantises in the hope of controlling insect pests. However, mantises do not have key attributes of biological pest control agents; they do not specialize in a single pest insect, and do not multiply rapidly in response to an increase in such a prey species, but are general predators. They eat whatever they can catch, including both harmful and beneficial insects. They therefore have "negligible value" in biological control. |
what types of structures have the same function but do not share a common ancestry |
Convergent evolution is the independent evolution of similar features in species of different lineages. Convergent evolution creates analogous structures that have similar form or function but were not present in the last common ancestor of those groups. The cladistic term for the same phenomenon is homoplasy. The recurrent evolution of flight is a classic example, as flying insects, birds, pterosaurs, and bats have independently evolved the useful capacity of flight. Functionally similar features that have arisen through convergent evolution are analogous, whereas homologous structures or traits have a common origin but can have dissimilar functions. Bird, bat, and pterosaur wings are analogous structures, but their forelimbs are homologous, sharing an ancestral state despite serving different functions. |
Birds and bats have homologous limbs because they are both ultimately derived from terrestrial tetrapods, but their flight mechanisms are only analogous, so their wings are examples of functional convergence. The two groups have powered flight, evolved independently. Their wings differ substantially in construction. The bat wing is a membrane stretched across four extremely elongated fingers and the legs. The airfoil of the bird wing is made of feathers, strongly attached to the forearm (the ulna) and the highly fused bones of the wrist and hand (the carpometacarpus), with only tiny remnants of two fingers remaining, each anchoring a single feather. So, while the wings of bats and birds are functionally convergent, they are not anatomically convergent. Similarly, the extinct pterosaur also shows an independent evolution of vertebrate fore- and hindlimbs to wing. An even more distantly related group, the insects, have wings that evolved separately from different organs. |
where does the st. johns river begin and end |
Starting in Indian River County and meeting the Atlantic Ocean at Duval County, the St. Johns is Florida's primary commercial and recreational waterway. It flows north from its headwaters, originating in the direction of the Lake Wales Ridge, which is only slightly elevated at 30 feet (9.1 m) above sea level. Because of this low elevation drop, the river has a long backwater. It ebbs and flows with tides that pass through the barrier islands and up the channel. Uniquely, it shares the same regional terrain as the parallel Kissimmee River, although the Kissimmee flows south. |
All of Florida's abundant fresh water is the result of precipitation that returns to the atmosphere in a process called evapotranspiration that involves evaporation and transpiration of moisture from plants. As rains fall, most of the water is directed to lakes, streams, and rivers. However, a significant amount of fresh water is held underground but close to the surface in aquifers. A surficial aquifer consisting mostly of clay, shells, and sand is over a confining layer of denser materials. Wells are drilled in the surficial aquifer, which supplies better quality water in areas where the deepest aquifer has a high mineral content. Occasionally the confining layer is fractured to allow breaches of water to percolate down to recharge the layer below. The Floridan Aquifer, underneath the confining layer, underlies the entire state and portions of Georgia, Alabama, and South Carolina. It is particularly accessible in the northern part of Florida, serving as the fresh water source of metr... |
MultipleNegativesRankingLoss with these parameters:{
"scale": 20.0,
"similarity_fct": "cos_sim",
"gather_across_devices": false,
"directions": [
"query_to_doc"
],
"partition_mode": "joint",
"hardness_mode": null,
"hardness_strength": 0.0
}
per_device_train_batch_size: 32per_device_eval_batch_size: 32num_train_epochs: 4fp16: Truemulti_dataset_batch_sampler: round_robindo_predict: Falseprediction_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: 4max_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: Truebf16_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 | dev-eval_cosine_ndcg@10 |
|---|---|---|---|
| 0.6667 | 300 | - | 0.6099 |
| 1.0 | 450 | - | 0.6425 |
| 1.1111 | 500 | 0.5279 | - |
| 1.3333 | 600 | - | 0.6491 |
| 2.0 | 900 | - | 0.6593 |
| 2.2222 | 1000 | 0.1084 | - |
| 2.6667 | 1200 | - | 0.6669 |
| 3.0 | 1350 | - | 0.6659 |
| 3.3333 | 1500 | 0.0406 | 0.6662 |
| 4.0 | 1800 | - | 0.6642 |
@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{oord2019representationlearningcontrastivepredictive,
title={Representation Learning with Contrastive Predictive Coding},
author={Aaron van den Oord and Yazhe Li and Oriol Vinyals},
year={2019},
eprint={1807.03748},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/1807.03748},
}
Base model
distilbert/distilbert-base-uncased