Downloads · 30 days
15
9% of all-time downloads
wasabibish/similarity-code-ai-generated
similarity-code-ai-generated is a sentence similarity model from wasabibish. Use it when you need a score for how close two texts are. It is set up for sentence-transformers.
This is a sentence-transformers model finetuned from distilbert/distilbert-base-uncased-finetuned-sst-2-english. It maps sentences & paragraphs to a 768-dimensional dense vector space and can be used for semantic text…
Downloads · 30 days
15
9% of all-time downloads
All-time downloads
168
Public
Parameters
66.4M
265 MB on disk
Likes
0
Public
Click a slice to open those files.
.safetensors265 MB · 100%
From the Hugging Face model README
This is a sentence-transformers model finetuned from distilbert/distilbert-base-uncased-finetuned-sst-2-english. 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}) with Transformer model: DistilBertModel
(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("wasabibish/similarity-code-ai-generated")
# Run inference
sentences = [
'def move_zeroes(nums):\n count = 0\n for i in range(len(nums)):\n if nums[i] != 0:\n nums[count], nums[i]= nums[i], nums[count]\n count += 1\n for i in range(count, len(nums)):\n nums[i] =0\n\ninput = [int(x) for x in input("Enter integers separated by spaces: ").split()]\nmove_zeroes(input)\n\nprint(input)',
'def move_zeros_to_end(lst):\n zero_count = 0\n for i in range(len(lst)):\n if lst[i] != 0:\n lst[i], lst[zero_count] = lst[zero_count], lst[i]\n zero_count += 1\n\n# Test cases\nlst1 = [0, 1, 0, 3, 12]\nmove_zeros_to_end(lst1)\nprint(lst1) # Output: [1, 3, 12, 0, 0]\n\nlst2 = [0, 0, 1]\nmove_zeros_to_end(lst2)\nprint(lst2) # Output: [1, 0, 0]\n',
'using System;\nusing System.Collections.Generic;\n\nclass BracketChecker\n{\n private readonly Dictionary<char, char> bracketPairs = new Dictionary<char, char>\n {\n { \'(\', \')\' },\n { \'[\', \']\' },\n { \'{\', \'}\' }\n };\n\n public bool CheckBalancedBrackets(string input)\n {\n if (string.IsNullOrEmpty(input))\n {\n return true;\n }\n\n Stack<char> stack = new Stack<char>();\n\n foreach (char c in input)\n {\n if (bracketPairs.ContainsValue(c))\n {\n if (stack.Count == 0 || bracketPairs[stack.Peek()] != c)\n {\n return false;\n }\n stack.Pop();\n }\n else if (bracketPairs.ContainsKey(c))\n {\n stack.Push(c);\n }\n }\n\n return stack.Count == 0;\n }\n}\n\nclass Program\n{\n static void Main()\n {\n BracketChecker bracketChecker = new BracketChecker();\n\n string input1 = "(a+[b*c]-{d/e})";\n Console.WriteLine("Input: \\"{0}\\"", input1);\n Console.WriteLine("Output: {0}\\n", bracketChecker.CheckBalancedBrackets(input1));\n\n string input2 = "(a+[b*c)-{d/e}]";\n Console.WriteLine("Input: \\"{0}\\"", input2);\n Console.WriteLine("Output: {0}", bracketChecker.CheckBalancedBrackets(input2));\n }\n}\n',
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 768]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [3, 3]
<!--
### Direct Usage (Transformers)
<details><summary>Click to see the direct usage in Transformers</summary>
</details>
-->
<!--
### Downstream Usage (Sentence Transformers)
You can finetune this model on your own dataset.
<details><summary>Click to expand</summary>
</details>
-->
<!--
### Out-of-Scope Use
*List how the model may foreseeably be misused and address what users ought not to do with the model.*
-->
| Metric | Value |
|---|---|
| pearson_cosine | 0.9 |
| spearman_cosine | 0.9014 |
| pearson_manhattan | 0.862 |
| spearman_manhattan | 0.802 |
| pearson_euclidean | 0.8685 |
| spearman_euclidean | 0.8234 |
| pearson_dot | 0.8495 |
| spearman_dot | 0.8948 |
| pearson_max | 0.9 |
| spearman_max | 0.9014 |
| sentence1 | sentence2 | score | |
|---|---|---|---|
| type | string | string | float |
| details | <ul><li>min: 3 tokens</li><li>mean: 206.43 tokens</li><li>max: 512 tokens</li></ul> | <ul><li>min: 27 tokens</li><li>mean: 244.9 tokens</li><li>max: 512 tokens</li></ul> | <ul><li>min: 0.0</li><li>mean: 0.29</li><li>max: 0.9</li></ul> |
| sentence1 | sentence2 | score |
|---|---|---|
| <code>from django.views.generic import ListView<br><br>class PersonListView(ListView):<br> model = Person<br> template_name = 'person_list.html'<br><br> def get_queryset(self):<br> return Person.objects.filter(birthdate__year__lte=2005)</code> | <code>from myapp.models import Customer # Import the Customer model from your Django app<br><br>def get_customers_with_zip_code_starting_with_123():<br> customers = Customer.objects.filter(zip_code__startswith='123').values() # Query to filter customers with zip_code starting with '123'<br> return list(customers) # Return a list of dictionaries for matching records<br></code> | <code>0.4</code> |
| <code><div class="content-box"><br> <p>Welcome to our website!</p><br></div><br><style><br> .content-box {<br> margin: 20;<br> background-colour: #00G;<br> }<br></style></code> | <code>function createSentence(words, maxChars) {<br> if (words.length === 0 | |
| <code>AAAAAA</code> | <code>#include <atlstr.h><br>#include <vector><br><br>class KMP {<br>public:<br> std::vector<int> findPatternIndices(const CString& text, const CString& pattern) {<br> std::vector<int> indices;<br> if (pattern.IsEmpty() |
{
"loss_fct": "torch.nn.modules.loss.MSELoss"
}
| sentence1 | sentence2 | score | |
|---|---|---|---|
| type | string | string | float |
| details | <ul><li>min: 5 tokens</li><li>mean: 216.92 tokens</li><li>max: 512 tokens</li></ul> | <ul><li>min: 54 tokens</li><li>mean: 254.78 tokens</li><li>max: 512 tokens</li></ul> | <ul><li>min: 0.0</li><li>mean: 0.33</li><li>max: 0.9</li></ul> |
| sentence1 | sentence2 | score |
|---|---|---|
| <code>function stripHtmlTags(str) {<br> return str.replace(/<[^>]*>/g, '');<br>}<br><br>const input = '<p>Hello <em>World</em>!</p>';<br><br>const output = stripHtmlTags(input);<br><br>console.log(output);</code> | <code>function stripHtmlTags(input) {<br> if (!input) return '';<br><br> const tagRegex = /<[^>]*>/g;<br> return input.replace(tagRegex, '');<br>}<br></code> | <code>0.6</code> |
| <code><?php<br>function getTopThreeWords($text) {<br>// Remove punctuation and convert to lowercase<br>$words = str_word_count(strtolower(preg_replace('/[^\p{L}\p{N}\s]/u', ' ', $text)), 1);<br><br>// Count the frequency of each word<br>$wordFrequency = array_count_values($words);<br><br>// Sort the words by frequency in descending order<br>arsort($wordFrequency);<br><br>// Get the top three words<br>$topThreeWords = array_slice($wordFrequency, 0, 3, true);<br><br>// Format the output<br>$output = [];<br>foreach ($topThreeWords as $word => $count) {<br>$output[] = "('$word', $count)";<br>}<br><br>return '[' . implode(', ', $output) . ']';<br>}<br><br>// Example usage:<br>$inputText = "The quick brown fox jumps over the lazy dog. The dog was lazy!";<br>echo getTopThreeWords($inputText);<br>?></code> | <code><?php<br><br>function countTopWords($inputString) {<br> // Convert the input string to lowercase and remove punctuation<br> $cleanString = preg_replace("/[\W_]+/", " ", strtolower($inputString));<br><br> // Split the string into an array of words<br> $words = explode(" ", $cleanString);<br><br> // Count the frequency of each word<br> $wordCount = array_count_values($words);<br><br> // Sort the words by frequency in descending order<br> arsort($wordCount);<br><br> // Get the top three most common words<br> $topWords = array_slice($wordCount, 0, 3);<br><br> // Format the output as an array of tuples<br> $output = [];<br> foreach ($topWords as $word => $count) {<br> $output[] = [$word, $count];<br> }<br><br> return $output;<br>}<br><br>// Test the function with the example input<br>$inputString = "The quick brown fox jumps over the lazy dog. The dog was lazy!";<br>$output = countTopWords($inputString);<br>print_r($output);<br><br>?><br></code> | <code>0.3</code> |
| <code>AAAAAA</code> | <code>#include <atlstr.h><br>#include <vector><br><br>class KMP {<br>public:<br> std::vector<int> findPatternIndices(const CString& text, const CString& pattern) {<br> std::vector<int> indices;<br> if (pattern.IsEmpty() |
{
"loss_fct": "torch.nn.modules.loss.MSELoss"
}
eval_strategy: stepsweight_decay: 0.2max_steps: 100warmup_steps: 150overwrite_output_dir: Falsedo_predict: Falseeval_strategy: stepsprediction_loss_only: Trueper_device_train_batch_size: 8per_device_eval_batch_size: 8per_gpu_train_batch_size: Noneper_gpu_eval_batch_size: Nonegradient_accumulation_steps: 1eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 5e-05weight_decay: 0.2adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1.0num_train_epochs: 3.0max_steps: 100lr_scheduler_type: linearlr_scheduler_kwargs: {}warmup_ratio: 0.0warmup_steps: 150log_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: Falseuse_ipex: Falsebf16: Falsefp16: Falsefp16_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}deepspeed: Nonelabel_smoothing_factor: 0.0optim: adamw_torchoptim_args: Noneadafactor: Falsegroup_by_length: Falselength_column_name: lengthddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falsedataloader_pin_memory: Truedataloader_persistent_workers: Falseskip_memory_metrics: Trueuse_legacy_prediction_loop: Falsepush_to_hub: Falseresume_from_checkpoint: Nonehub_model_id: Nonehub_strategy: every_savehub_private_repo: Falsehub_always_push: Falsegradient_checkpointing: Falsegradient_checkpointing_kwargs: Noneinclude_inputs_for_metrics: Falseeval_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: Nonedispatch_batches: Nonesplit_batches: Noneinclude_tokens_per_second: Falseinclude_num_input_tokens_seen: Falseneftune_noise_alpha: Noneoptim_target_modules: Nonebatch_eval_metrics: Falseeval_on_start: Falseeval_use_gather_object: Falsebatch_sampler: batch_samplermulti_dataset_batch_sampler: proportional| Epoch | Step | loss | spearman_max |
|---|---|---|---|
| 0.5263 | 20 | 0.3765 | 0.5421 |
| 1.0526 | 40 | 0.1518 | 0.5774 |
| 1.5789 | 60 | 0.0501 | 0.8533 |
| 2.1053 | 80 | 0.0217 | 0.8900 |
| 2.6316 | 100 | 0.0168 | 0.9014 |
@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",
}
<!--
## Glossary
*Clearly define terms in order to be accessible across audiences.*
-->
<!--
## Model Card Authors
*Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
-->
<!--
## Model Card Contact
*Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
-->