├── .github └── workflows │ └── python-publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── examples ├── __init__.py ├── english │ ├── __init__.py │ └── sick │ │ ├── __init__.py │ │ ├── data │ │ └── SICK_test_annotated.txt │ │ └── run_experiment.py └── evaluation.py ├── requirements.txt ├── setup.cfg ├── setup.py └── simplests ├── __init__.py ├── algo ├── __init__.py ├── cls.py ├── labse.py ├── sbert.py ├── sif.py ├── use.py ├── wmd.py └── word_avg.py ├── model_args.py └── util.py /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Upload Python Package 10 | 11 | on: 12 | release: 13 | types: [published] 14 | 15 | permissions: 16 | contents: read 17 | 18 | jobs: 19 | deploy: 20 | 21 | runs-on: ubuntu-latest 22 | 23 | steps: 24 | - uses: actions/checkout@v4 25 | - name: Set up Python 26 | uses: actions/setup-python@v3 27 | with: 28 | python-version: '3.x' 29 | - name: Install dependencies 30 | run: | 31 | python -m pip install --upgrade pip 32 | pip install build 33 | - name: Build package 34 | run: python -m build 35 | - name: Publish package 36 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 37 | with: 38 | user: __token__ 39 | password: ${{ secrets.PYPI_API_TOKEN }} 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 2 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 3 | 4 | # User-specific stuff 5 | .idea 6 | .ipynb_checkpoints 7 | 8 | 9 | .idea/**/workspace.xml 10 | .idea/**/tasks.xml 11 | .idea/**/usage.statistics.xml 12 | .idea/**/dictionaries 13 | .idea/**/shelf 14 | 15 | # Generated files 16 | .idea/**/contentModel.xml 17 | 18 | # Sensitive or high-churn files 19 | .idea/**/dataSources/ 20 | .idea/**/dataSources.ids 21 | .idea/**/dataSources.local.xml 22 | .idea/**/sqlDataSources.xml 23 | .idea/**/dynamic.xml 24 | .idea/**/uiDesigner.xml 25 | .idea/**/dbnavigator.xml 26 | 27 | # Gradle 28 | .idea/**/gradle.xml 29 | .idea/**/libraries 30 | 31 | # Gradle and Maven with auto-import 32 | # When using Gradle or Maven with auto-import, you should exclude module files, 33 | # since they will be recreated, and may cause churn. Uncomment if using 34 | # auto-import. 35 | # .idea/modules.xml 36 | # .idea/*.iml 37 | # .idea/modules 38 | 39 | # CMake 40 | cmake-build-*/ 41 | 42 | # Mongo Explorer plugin 43 | .idea/**/mongoSettings.xml 44 | 45 | # File-based project format 46 | *.iws 47 | 48 | # IntelliJ 49 | out/ 50 | 51 | # mpeltonen/sbt-idea plugin 52 | .idea_modules/ 53 | 54 | # JIRA plugin 55 | atlassian-ide-plugin.xml 56 | 57 | # Cursive Clojure plugin 58 | .idea/replstate.xml 59 | 60 | # Crashlytics plugin (for Android Studio and IntelliJ) 61 | com_crashlytics_export_strings.xml 62 | crashlytics.properties 63 | crashlytics-build.properties 64 | fabric.properties 65 | 66 | # Editor-based Rest Client 67 | .idea/httpRequests 68 | 69 | # Android studio 3.1+ serialized cache file 70 | .idea/caches/build_file_checksums.ser 71 | 72 | #check points 73 | .ipynb_checkpoints/.idea 74 | .ipynb_checkpoints 75 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Downloads](https://pepy.tech/badge/simplests)](https://pepy.tech/project/simplests) 2 | 3 | # Simple Sentence Similarity 4 | We provide a collection of simple unsupervised semantic textual similarity methods to calculate semantic similarity between two sentences. 5 | 6 | ### References 7 | If you find this code useful in your research, please consider citing: 8 | 9 | ``` 10 | @inproceedings{ranasinghe-etal-2019-enhancing, 11 | title = "Enhancing Unsupervised Sentence Similarity Methods with Deep Contextualised Word Representations", 12 | author = "Ranasinghe, Tharindu and 13 | Orasan, Constantin and 14 | Mitkov, Ruslan", 15 | booktitle = "Proceedings of the International Conference on Recent Advances in Natural Language Processing (RANLP 2019)", 16 | month = sep, 17 | year = "2019", 18 | address = "Varna, Bulgaria", 19 | publisher = "INCOMA Ltd.", 20 | url = "https://www.aclweb.org/anthology/R19-1115", 21 | doi = "10.26615/978-954-452-056-4_115", 22 | pages = "994--1003", 23 | abstract = "Calculating Semantic Textual Similarity (STS) plays a significant role in many applications such as question answering, document summarisation, information retrieval and information extraction. All modern state of the art STS methods rely on word embeddings one way or another. The recently introduced contextualised word embeddings have proved more effective than standard word embeddings in many natural language processing tasks. This paper evaluates the impact of several contextualised word embeddings on unsupervised STS methods and compares it with the existing supervised/unsupervised STS methods for different datasets in different languages and different domains", 24 | } 25 | } 26 | ``` 27 | -------------------------------------------------------------------------------- /examples/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TharinduDR/Simple-Sentence-Similarity/f3298fe472eb58eb3d698123781f9f719e451143/examples/__init__.py -------------------------------------------------------------------------------- /examples/english/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TharinduDR/Simple-Sentence-Similarity/f3298fe472eb58eb3d698123781f9f719e451143/examples/english/__init__.py -------------------------------------------------------------------------------- /examples/english/sick/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TharinduDR/Simple-Sentence-Similarity/f3298fe472eb58eb3d698123781f9f719e451143/examples/english/sick/__init__.py -------------------------------------------------------------------------------- /examples/english/sick/run_experiment.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | from examples.evaluation import pearson_corr, spearman_corr, rmse 4 | from simplests.algo.cls import TransformerCLSSTSMethod 5 | from simplests.algo.labse import LaBSESTSMethod 6 | from simplests.algo.sbert import SentenceTransformerSTSMethod 7 | from simplests.algo.sif import WordEmbeddingSIFSTSMethod 8 | from simplests.algo.use import UniversalSentenceEncoderSTSMethod 9 | from simplests.algo.wmd import WordMoversDistanceSTSMethod 10 | from simplests.algo.word_avg import WordEmbeddingAverageSTSMethod 11 | from simplests.model_args import WordEmbeddingSTSArgs, SentenceEmbeddingSTSArgs 12 | 13 | sick_test = pd.read_csv("examples/english/sick/data/SICK_test_annotated.txt", sep="\t") 14 | 15 | to_predit = [] 16 | sims = [] 17 | 18 | sick_test = sick_test.reset_index() # make sure indexes pair with number of rows 19 | for index, row in sick_test.iterrows(): 20 | to_predit.append([row['sentence_A'], row['sentence_B']]) 21 | sims.append(row['relatedness_score']) 22 | 23 | model_args = WordEmbeddingSTSArgs() 24 | model_args.embedding_models = [["word", "glove"]] 25 | model_args.language = "en" 26 | model_args.remove_stopwords = True 27 | 28 | # model = WordEmbeddingAverageSTSMethod(model_args=model_args) 29 | model = WordEmbeddingSIFSTSMethod(model_args=model_args) 30 | 31 | pred_sims = model.predict(to_predit) 32 | print("Pearson correlation ", pearson_corr(sims, pred_sims)) 33 | print("Spearman correlation ", spearman_corr(sims, pred_sims)) 34 | print("RMSE ", rmse(sims, pred_sims)) 35 | 36 | # ------------------------------------------------------------------------- 37 | model = WordMoversDistanceSTSMethod(model_args=model_args) 38 | 39 | pred_sims = model.predict(to_predit) 40 | print("Pearson correlation ", pearson_corr(sims, pred_sims)) 41 | print("Spearman correlation ", spearman_corr(sims, pred_sims)) 42 | print("RMSE ", rmse(sims, pred_sims)) 43 | 44 | # 45 | # # ----------------------------------------------------------------------- 46 | # 47 | # sentence_model_args = SentenceEmbeddingSTSArgs() 48 | # sentence_model_args.embedding_model = "https://tfhub.dev/google/universal-sentence-encoder-multilingual-large/3" 49 | # sentence_model_args.language = "en" 50 | # 51 | # 52 | # # model = WordEmbeddingAverageSTSMethod(model_args=model_args) 53 | # model = UniversalSentenceEncoderSTSMethod(model_args=sentence_model_args) 54 | # 55 | # pred_sims = model.predict(to_predit) 56 | # print("Pearson correlation ", pearson_corr(sims, pred_sims)) 57 | # print("Spearman correlation ", spearman_corr(sims, pred_sims)) 58 | # print("RMSE ", rmse(sims, pred_sims)) 59 | # 60 | # # ----------------------------------------------------------------------- 61 | # # labse_model_args = SentenceEmbeddingSTSArgs() 62 | # # labse_model_args.embedding_model = "https://tfhub.dev/google/LaBSE/2" 63 | # # labse_model_args.language = "en" 64 | # # 65 | # # 66 | # # model = WordEmbeddingAverageSTSMethod(model_args=model_args) 67 | # # model = LaBSESTSMethod(model_args=labse_model_args) 68 | # # 69 | # # pred_sims = model.predict(to_predit) 70 | # # print("Pearson correlation ", pearson_corr(sims, pred_sims)) 71 | # # print("Spearman correlation ", spearman_corr(sims, pred_sims)) 72 | # # print("RMSE ", rmse(sims, pred_sims)) 73 | # 74 | # # ----------------------------------------------------------------------- 75 | # sbert_model_args = SentenceEmbeddingSTSArgs() 76 | # sbert_model_args.embedding_model = "distiluse-base-multilingual-cased" 77 | # sbert_model_args.language = "en" 78 | # 79 | # 80 | # # model = WordEmbeddingAverageSTSMethod(model_args=model_args) 81 | # model = SentenceTransformerSTSMethod(model_args=sbert_model_args) 82 | # 83 | # pred_sims = model.predict(to_predit) 84 | # print("Pearson correlation ", pearson_corr(sims, pred_sims)) 85 | # print("Spearman correlation ", spearman_corr(sims, pred_sims)) 86 | # print("RMSE ", rmse(sims, pred_sims)) 87 | # 88 | # # ----------------------------------------------------------------------- 89 | # cls_model_args = SentenceEmbeddingSTSArgs() 90 | # cls_model_args.embedding_model = "bert-base-multilingual-cased" 91 | # cls_model_args.language = "en" 92 | # 93 | # 94 | # # model = WordEmbeddingAverageSTSMethod(model_args=model_args) 95 | # model = TransformerCLSSTSMethod(model_args=cls_model_args) 96 | # 97 | # pred_sims = model.predict(to_predit) 98 | # print("Pearson correlation ", pearson_corr(sims, pred_sims)) 99 | # print("Spearman correlation ", spearman_corr(sims, pred_sims)) 100 | # print("RMSE ", rmse(sims, pred_sims)) 101 | 102 | 103 | -------------------------------------------------------------------------------- /examples/evaluation.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.stats import pearsonr, spearmanr 3 | 4 | 5 | def pearson_corr(preds, labels): 6 | return pearsonr(preds, labels)[0] 7 | 8 | 9 | def spearman_corr(preds, labels): 10 | return spearmanr(preds, labels)[0] 11 | 12 | 13 | def rmse(preds, labels): 14 | return np.sqrt(((np.asarray(preds, dtype=np.float32) - np.asarray(labels, dtype=np.float32)) ** 2).mean()) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pandas 2 | numpy 3 | flair 4 | tqdm 5 | pyemd 6 | stop_words 7 | tensorflow_text 8 | tensorflow_hub 9 | sentence_transformers -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | license_file = LICENSE 4 | 5 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setup( 7 | name="simplests", 8 | version="2.3.0", 9 | author="Tharindu Ranasinghe", 10 | author_email="rhtdranasinghe@gmail.com", 11 | description="Unsupervised models for Semantic Textual Similarity", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/TharinduDR/Simple-Sentence-Similarity", 15 | packages=find_packages(exclude=("examples", )), 16 | classifiers=[ 17 | "Intended Audience :: Science/Research", 18 | "License :: OSI Approved :: Apache Software License", 19 | "Programming Language :: Python :: 3", 20 | "Topic :: Scientific/Engineering :: Artificial Intelligence", 21 | ], 22 | python_requires=">=3.6", 23 | install_requires=[ 24 | "pandas", 25 | "numpy", 26 | "flair", 27 | "tqdm", 28 | "pyemd", 29 | "stop_words", 30 | "tensorflow_text", 31 | "tensorflow_hub", 32 | "sentence_transformers" 33 | ], 34 | ) 35 | -------------------------------------------------------------------------------- /simplests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TharinduDR/Simple-Sentence-Similarity/f3298fe472eb58eb3d698123781f9f719e451143/simplests/__init__.py -------------------------------------------------------------------------------- /simplests/algo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TharinduDR/Simple-Sentence-Similarity/f3298fe472eb58eb3d698123781f9f719e451143/simplests/algo/__init__.py -------------------------------------------------------------------------------- /simplests/algo/cls.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from flair.data import Sentence 4 | from flair.embeddings import TransformerDocumentEmbeddings 5 | from numpy import dot 6 | from numpy.linalg import norm 7 | from tqdm import tqdm 8 | 9 | from simplests.model_args import SentenceEmbeddingSTSArgs 10 | from simplests.util import batch 11 | 12 | logging.basicConfig(level=logging.INFO) 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | class TransformerCLSSTSMethod: 17 | def __init__(self, model_args: SentenceEmbeddingSTSArgs): 18 | self.model_args = model_args 19 | logging.info("Loading models ") 20 | self.embedding_model = TransformerDocumentEmbeddings(model_args.embedding_model) 21 | 22 | def predict(self, to_predict, batch_size=32): 23 | sims = [] 24 | 25 | sentences_1 = list(zip(*to_predict))[0] 26 | sentences_2 = list(zip(*to_predict))[1] 27 | 28 | processed_sentences_1 = [] 29 | processed_sentences_2 = [] 30 | 31 | for sentence_1, sentence_2 in zip(sentences_1, sentences_2): 32 | processed_sentences_1.append(Sentence(sentence_1)) 33 | processed_sentences_2.append(Sentence(sentence_2)) 34 | 35 | for x in tqdm(batch(processed_sentences_1 + processed_sentences_2, batch_size), 36 | total=int(len(processed_sentences_1 + processed_sentences_2) / batch_size) + ( 37 | len(processed_sentences_1 + processed_sentences_2) % batch_size > 0), 38 | desc="Embedding sentences "): 39 | self.embedding_model.embed(x) 40 | 41 | for embed_sentence_1, embed_sentence_2 in tqdm(zip(processed_sentences_1, processed_sentences_2), 42 | total=len(processed_sentences_1), 43 | desc="Calculating similarity "): 44 | embedding1 = embed_sentence_1.embedding.data.tolist() 45 | embedding2 = embed_sentence_2.embedding.data.tolist() 46 | 47 | cos_sim = dot(embedding1, embedding2) / (norm(embedding1) * norm(embedding2)) 48 | sims.append(cos_sim) 49 | 50 | return sims 51 | -------------------------------------------------------------------------------- /simplests/algo/labse.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import numpy as np 4 | import tensorflow_hub as hub 5 | import tensorflow_text as text 6 | import tensorflow as tf 7 | from tqdm import tqdm 8 | 9 | from simplests.model_args import SentenceEmbeddingSTSArgs 10 | from simplests.util import batch 11 | 12 | logging.basicConfig(level=logging.INFO) 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | def normalization(embeds): 17 | norms = np.linalg.norm(embeds, 2, axis=1, keepdims=True) 18 | return embeds/norms 19 | 20 | 21 | class LaBSESTSMethod: 22 | def __init__(self, model_args: SentenceEmbeddingSTSArgs): 23 | 24 | self.model_args = model_args 25 | logging.info("Loading models ") 26 | self.preprocessor = hub.KerasLayer( 27 | "https://tfhub.dev/google/universal-sentence-encoder-cmlm/multilingual-preprocess/2") 28 | self.encoder = hub.KerasLayer(model_args.embedding_model) 29 | 30 | def predict(self, to_predict, batch_size=32): 31 | sims = [] 32 | 33 | sentences_1 = list(zip(*to_predict))[0] 34 | sentences_2 = list(zip(*to_predict))[1] 35 | 36 | embeddings_1 = [] 37 | embeddings_2 = [] 38 | 39 | for x in tqdm(batch(sentences_1, batch_size), total=int(len(sentences_1) / batch_size) + ( 40 | len(sentences_1) % batch_size > 0), desc="Embedding list 1 "): 41 | temp_sentences = tf.constant(x) 42 | temp_embeds = self.encoder(self.preprocessor(temp_sentences))["default"] 43 | temp_embeds = normalization(temp_embeds) 44 | for embedding in temp_embeds: 45 | embeddings_1.append(embedding.numpy()) 46 | 47 | for x in tqdm(batch(sentences_2, batch_size), total=int(len(sentences_2) / batch_size) + ( 48 | len(sentences_2) % batch_size > 0), desc="Embedding list 2 "): 49 | temp_sentences = tf.constant(x) 50 | temp_embeds = self.encoder(self.preprocessor(temp_sentences))["default"] 51 | temp_embeds = normalization(temp_embeds) 52 | for embedding in temp_embeds: 53 | embeddings_2.append(embedding.numpy()) 54 | 55 | for embedding_1, embedding_2 in tqdm(zip(embeddings_1, embeddings_2), total=len(embeddings_1), desc="Calculating similarity "): 56 | sim = np.inner(embedding_1, embedding_2) 57 | sims.append(sim) 58 | 59 | return sims 60 | -------------------------------------------------------------------------------- /simplests/algo/sbert.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import numpy as np 4 | from numpy.linalg import norm 5 | from sentence_transformers import SentenceTransformer 6 | from tqdm import tqdm 7 | 8 | from simplests.model_args import SentenceEmbeddingSTSArgs 9 | 10 | logging.basicConfig(level=logging.INFO) 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | class SentenceTransformerSTSMethod: 15 | def __init__(self, model_args: SentenceEmbeddingSTSArgs): 16 | self.model_args = model_args 17 | logging.info("Loading models ") 18 | self.model = SentenceTransformer(model_args.embedding_model) 19 | 20 | def predict(self, to_predict, batch_size=32): 21 | sims = [] 22 | 23 | sentences_1 = list(zip(*to_predict))[0] 24 | sentences_2 = list(zip(*to_predict))[1] 25 | 26 | embeddings_1 = self.model.encode(sentences_1, batch_size=batch_size, show_progress_bar=True) 27 | embeddings_2 = self.model.encode(sentences_2, batch_size=batch_size, show_progress_bar=True) 28 | 29 | for embedding_1, embedding_2 in tqdm(zip(embeddings_1, embeddings_2), total=len(embeddings_1), desc="Calculating similarity "): 30 | cos_sim = np.dot(embedding_1, embedding_2) / ( 31 | norm(embedding_1) * norm(embedding_2)) 32 | sims.append(cos_sim) 33 | 34 | return sims 35 | -------------------------------------------------------------------------------- /simplests/algo/sif.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import numpy as np 4 | from flair.data import Sentence 5 | from flair.embeddings import StackedEmbeddings, WordEmbeddings, CharacterEmbeddings, TransformerWordEmbeddings, \ 6 | FastTextEmbeddings 7 | from numpy import dot 8 | from numpy.linalg import norm 9 | from tqdm import tqdm 10 | from sklearn.decomposition import TruncatedSVD 11 | 12 | from simplests.model_args import WordEmbeddingSTSArgs 13 | from simplests.util import batch 14 | from stop_words import get_stop_words 15 | 16 | logging.basicConfig(level=logging.INFO) 17 | logger = logging.getLogger(__name__) 18 | 19 | 20 | def _remove_first_principal_component(X): 21 | svd = TruncatedSVD(n_components=1, n_iter=7, random_state=0) 22 | svd.fit(X) 23 | pc = svd.components_ 24 | XX = X - X.dot(pc.transpose()) * pc 25 | return XX 26 | 27 | 28 | class WordEmbeddingSIFSTSMethod: 29 | def __init__(self, model_args: WordEmbeddingSTSArgs): 30 | 31 | self.model_args = model_args 32 | logging.info("Loading models ") 33 | 34 | embedding_models = [] 35 | for model_type, model_name in self.model_args.embedding_models: 36 | if model_type == "word": 37 | embedding_models.append(WordEmbeddings(model_name)) 38 | elif model_type == "fasttext": 39 | embedding_models.append(FastTextEmbeddings(model_name)) 40 | elif model_type == "char": 41 | embedding_models.append(CharacterEmbeddings(model_name)) 42 | elif model_type == "transformer": 43 | embedding_models.append(TransformerWordEmbeddings(model_name)) 44 | 45 | if len(embedding_models) > 1: 46 | self.embedding_model = StackedEmbeddings(embedding_models) 47 | elif len(embedding_models) == 1: 48 | self.embedding_model = embedding_models[0] 49 | else: 50 | raise ValueError( 51 | "Please specify at least one embedding model" 52 | ) 53 | if model_args.remove_stopwords: 54 | try: 55 | self.stop_words = get_stop_words(self.model_args.language) 56 | except KeyError as e: 57 | logging.warning("Stop words are not supported for {}. Please refer https://github.com/Alir3z4/python-stop-words to see supported languages.".format(model_args.language)) 58 | logging.warning("Setting model_args.remove_stopwords to False") 59 | self.model_args.remove_stopwords = False 60 | 61 | def predict(self, to_predict, batch_size=32): 62 | 63 | sims = [] 64 | embeddings = [] 65 | 66 | sentences_1 = list(zip(*to_predict))[0] 67 | sentences_2 = list(zip(*to_predict))[1] 68 | 69 | processed_sentences_1 = [] 70 | processed_sentences_2 = [] 71 | 72 | for sentence_1, sentence_2 in zip(sentences_1, sentences_2): 73 | processed_sentences_1.append(Sentence(sentence_1)) 74 | processed_sentences_2.append(Sentence(sentence_2)) 75 | 76 | for x in tqdm(batch(processed_sentences_1 + processed_sentences_2, batch_size), 77 | total=int(len(processed_sentences_1 + processed_sentences_2) / batch_size) + ( 78 | len(processed_sentences_1 + processed_sentences_2) % batch_size > 0), desc="Embedding sentences "): 79 | self.embedding_model.embed(x) 80 | 81 | for embed_sentence_1, embed_sentence_2 in tqdm(zip(processed_sentences_1, processed_sentences_2), total=len(processed_sentences_1), desc="Preparing embeddings"): 82 | 83 | if self.model_args.remove_stopwords: 84 | embedding1 = np.average([np.array(token1.embedding.data.tolist()) for token1 in embed_sentence_1 if token1.text not in self.stop_words], axis=0) 85 | embedding2 = np.average([np.array(token2.embedding.data.tolist()) for token2 in embed_sentence_2 if token2.text not in self.stop_words], axis=0) 86 | 87 | else: 88 | embedding1 = np.average([np.array(token1.embedding.data.tolist()) for token1 in embed_sentence_1], axis=0) 89 | embedding2 = np.average([np.array(token2.embedding.data.tolist()) for token2 in embed_sentence_2], axis=0) 90 | 91 | embeddings.append(embedding1) 92 | embeddings.append(embedding2) 93 | 94 | logging.info("Removing first principle component") 95 | processed_embeddings = _remove_first_principal_component(np.array(embeddings)) 96 | processed_embeddings_1 = processed_embeddings[1::2] 97 | processed_embeddings_2 = processed_embeddings[0::2] 98 | 99 | for processed_embedding_1, processed_embeddings_2 in tqdm(zip(processed_embeddings_1, processed_embeddings_2), total=len(processed_sentences_1), desc="Calculating similarity "): 100 | cos_sim = dot(processed_embedding_1, processed_embeddings_2) / (norm(processed_embedding_1) * norm(processed_embeddings_2)) 101 | sims.append(cos_sim) 102 | 103 | return sims 104 | -------------------------------------------------------------------------------- /simplests/algo/use.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import numpy as np 4 | import tensorflow_hub as hub 5 | from tqdm import tqdm 6 | 7 | from simplests.model_args import SentenceEmbeddingSTSArgs 8 | from simplests.util import batch 9 | 10 | logging.basicConfig(level=logging.INFO) 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | class UniversalSentenceEncoderSTSMethod: 15 | def __init__(self, model_args: SentenceEmbeddingSTSArgs): 16 | 17 | self.model_args = model_args 18 | logging.info("Loading models ") 19 | self.model = hub.load(self.model_args.embedding_model) 20 | 21 | def predict(self, to_predict, batch_size=32): 22 | sims = [] 23 | 24 | sentences_1 = list(zip(*to_predict))[0] 25 | sentences_2 = list(zip(*to_predict))[1] 26 | 27 | embeddings_1 = [] 28 | embeddings_2 = [] 29 | 30 | for x in tqdm(batch(sentences_1, batch_size), total=int(len(sentences_1) / batch_size) + ( 31 | len(sentences_1) % batch_size > 0), desc="Embedding list 1 "): 32 | temp = self.model(x) 33 | for embedding in temp: 34 | embeddings_1.append(embedding.numpy()) 35 | 36 | for x in tqdm(batch(sentences_2, batch_size), total=int(len(sentences_2) / batch_size) + ( 37 | len(sentences_2) % batch_size > 0), desc="Embedding list 2 "): 38 | temp = self.model(x) 39 | for embedding in temp: 40 | embeddings_2.append(embedding.numpy()) 41 | 42 | for embedding_1, embedding_2 in tqdm(zip(embeddings_1, embeddings_2), total=len(embeddings_1), desc="Calculating similarity "): 43 | sim = np.inner(embedding_1, embedding_2) 44 | sims.append(sim) 45 | 46 | return sims 47 | -------------------------------------------------------------------------------- /simplests/algo/wmd.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import numpy as np 4 | from flair.data import Sentence 5 | from flair.embeddings import StackedEmbeddings, WordEmbeddings, CharacterEmbeddings, TransformerWordEmbeddings, \ 6 | FastTextEmbeddings 7 | from numpy import dot 8 | from numpy.linalg import norm 9 | from tqdm import tqdm 10 | import math 11 | 12 | from simplests.model_args import WordEmbeddingSTSArgs 13 | from simplests.util import batch 14 | from stop_words import get_stop_words 15 | from gensim.corpora.dictionary import Dictionary 16 | 17 | try: 18 | from pyemd import emd 19 | 20 | PYEMD_EXT = True 21 | except ImportError: 22 | PYEMD_EXT = False 23 | 24 | logging.basicConfig(level=logging.INFO) 25 | logger = logging.getLogger(__name__) 26 | 27 | gensim_logger = logging.getLogger('gensim') 28 | gensim_logger.setLevel(logging.WARN) 29 | 30 | 31 | class WordMoversDistanceSTSMethod: 32 | def __init__(self, model_args: WordEmbeddingSTSArgs): 33 | 34 | if not PYEMD_EXT: 35 | raise ImportError("Please install pyemd Python package to compute WMD.") 36 | 37 | self.model_args = model_args 38 | logging.info("Loading models ") 39 | 40 | embedding_models = [] 41 | for model_type, model_name in self.model_args.embedding_models: 42 | if model_type == "word": 43 | embedding_models.append(WordEmbeddings(model_name)) 44 | elif model_type == "fasttext": 45 | embedding_models.append(FastTextEmbeddings(model_name)) 46 | elif model_type == "char": 47 | embedding_models.append(CharacterEmbeddings(model_name)) 48 | elif model_type == "transformer": 49 | embedding_models.append(TransformerWordEmbeddings(model_name)) 50 | 51 | if len(embedding_models) > 1: 52 | self.embedding_model = StackedEmbeddings(embedding_models) 53 | elif len(embedding_models) == 1: 54 | self.embedding_model = embedding_models[0] 55 | else: 56 | raise ValueError( 57 | "Please specify at least one embedding model" 58 | ) 59 | if model_args.remove_stopwords: 60 | try: 61 | self.stop_words = get_stop_words(self.model_args.language) 62 | except KeyError as e: 63 | logging.warning("Stop words are not supported for {}. Please refer https://github.com/Alir3z4/python-stop-words to see supported languages.".format(model_args.language)) 64 | logging.warning("Setting model_args.remove_stopwords to False") 65 | self.model_args.remove_stopwords = False 66 | 67 | def predict(self, to_predict, batch_size=32): 68 | 69 | sims = [] 70 | 71 | sentences_1 = list(zip(*to_predict))[0] 72 | sentences_2 = list(zip(*to_predict))[1] 73 | 74 | processed_sentences_1 = [] 75 | processed_sentences_2 = [] 76 | 77 | for sentence_1, sentence_2 in zip(sentences_1, sentences_2): 78 | processed_sentences_1.append(Sentence(sentence_1)) 79 | processed_sentences_2.append(Sentence(sentence_2)) 80 | 81 | for x in tqdm(batch(processed_sentences_1 + processed_sentences_2, batch_size), 82 | total=int(len(processed_sentences_1 + processed_sentences_2) / batch_size) + ( 83 | len(processed_sentences_1 + processed_sentences_2) % batch_size > 0), desc="Embedding sentences "): 84 | self.embedding_model.embed(x) 85 | 86 | for embed_sentence_1, embed_sentence_2 in tqdm(zip(processed_sentences_1, processed_sentences_2), total=len(processed_sentences_1), desc="Calculating similarity "): 87 | 88 | sim = self.wmdistance(embed_sentence_1, embed_sentence_2) 89 | sims.append(sim) 90 | 91 | return sims 92 | 93 | def wmdistance(self, sentence1, sentence2): 94 | """ 95 | Compute the Word Mover's Distance between two documents. When using this 96 | code, please consider citing the following papers: 97 | .. Ofir Pele and Michael Werman, "A linear time histogram metric for improved SIFT matching". 98 | .. Ofir Pele and Michael Werman, "Fast and robust earth mover's distances". 99 | .. Matt Kusner et al. "From Word Embeddings To Document Distances". 100 | Note that if one of the documents have no words that exist in the vocab, `float('inf')` (i.e. infinity) will be returned. 101 | This method only works if `pyemd` is installed (can be installed via pip, but requires a C compiler). 102 | """ 103 | 104 | # Remove out-of-vocabulary words. 105 | 106 | if not self.model_args.remove_stopwords: 107 | document1 = [token.text for token in sentence1] 108 | document2 = [token.text for token in sentence2] 109 | 110 | else: 111 | document1 = [token.text for token in sentence1 if token.text not in self.stop_words] 112 | document2 = [token.text for token in sentence2 if token.text not in self.stop_words] 113 | 114 | dictionary = Dictionary(documents=[document1, document2]) 115 | 116 | len_pre_oov1 = len(document1) 117 | len_pre_oov2 = len(document2) 118 | 119 | diff1 = len_pre_oov1 - len(document1) 120 | diff2 = len_pre_oov2 - len(document2) 121 | if diff1 > 0 or diff2 > 0: 122 | logger.info('Removed %d and %d OOV words from document 1 and 2 (respectively).', diff1, diff2) 123 | 124 | if len(document1) == 0 or len(document2) == 0: 125 | logger.warning( 126 | "At least one of the documents had no words that were in the vocabulary." 127 | "Aborting (returning inf)." 128 | ) 129 | return float('inf') 130 | 131 | full_list = document1 + document2 132 | vocab_len = len(full_list) 133 | 134 | if len(set(full_list)) == 1: 135 | # Both documents are composed by a single unique token 136 | return 0.0 137 | 138 | # # Compute distance matrix. 139 | distance_matrix = np.zeros((vocab_len, vocab_len), dtype=np.double) 140 | 141 | for i, token1 in enumerate(document1): 142 | for j, token2 in enumerate(document2): 143 | # print("first sentence", sentence_1[i].text) 144 | # print("second sentence", sentence_2[j].text) 145 | distance_matrix[i, (len(document1) + j)] = np.sqrt(np.sum((np.array( 146 | sentence1[i].embedding.data.tolist()) - np.array(sentence2[j].embedding.data.tolist())) ** 2)) 147 | 148 | if np.sum(distance_matrix) == 0.0: 149 | logger.warning('The distance matrix is all zeros. Aborting (returning inf).') 150 | return float('inf') 151 | 152 | def nbow(document): 153 | d = np.zeros(vocab_len, dtype=np.double) 154 | nbow = dictionary.doc2bow(document) # Word frequencies. 155 | doc_len = len(document) 156 | for idx, freq in nbow: 157 | d[idx] = freq / float(doc_len) # Normalized word frequencies. 158 | return d 159 | 160 | # Compute nBOW representation of documents. 161 | d1 = nbow(document1) 162 | d2 = nbow(document2) 163 | 164 | # Compute WMD. 165 | distance = emd(d1, d2, distance_matrix) 166 | return -distance 167 | -------------------------------------------------------------------------------- /simplests/algo/word_avg.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import numpy as np 4 | from flair.data import Sentence 5 | from flair.embeddings import StackedEmbeddings, WordEmbeddings, CharacterEmbeddings, TransformerWordEmbeddings, \ 6 | FastTextEmbeddings 7 | from numpy import dot 8 | from numpy.linalg import norm 9 | from tqdm import tqdm 10 | 11 | from simplests.model_args import WordEmbeddingSTSArgs 12 | from simplests.util import batch 13 | from stop_words import get_stop_words 14 | 15 | logging.basicConfig(level=logging.INFO) 16 | logger = logging.getLogger(__name__) 17 | 18 | 19 | class WordEmbeddingAverageSTSMethod: 20 | def __init__(self, model_args: WordEmbeddingSTSArgs): 21 | 22 | self.model_args = model_args 23 | logging.info("Loading models ") 24 | 25 | embedding_models = [] 26 | for model_type, model_name in self.model_args.embedding_models: 27 | if model_type == "word": 28 | embedding_models.append(WordEmbeddings(model_name)) 29 | elif model_type == "fasttext": 30 | embedding_models.append(FastTextEmbeddings(model_name)) 31 | elif model_type == "char": 32 | embedding_models.append(CharacterEmbeddings(model_name)) 33 | elif model_type == "transformer": 34 | embedding_models.append(TransformerWordEmbeddings(model_name)) 35 | 36 | if len(embedding_models) > 1: 37 | self.embedding_model = StackedEmbeddings(embedding_models) 38 | elif len(embedding_models) == 1: 39 | self.embedding_model = embedding_models[0] 40 | else: 41 | raise ValueError( 42 | "Please specify at least one embedding model" 43 | ) 44 | if model_args.remove_stopwords: 45 | try: 46 | self.stop_words = get_stop_words(self.model_args.language) 47 | except KeyError as e: 48 | logging.warning("Stop words are not supported for {}. Please refer https://github.com/Alir3z4/python-stop-words to see supported languages.".format(model_args.language)) 49 | logging.warning("Setting model_args.remove_stopwords to False") 50 | self.model_args.remove_stopwords = False 51 | 52 | def predict(self, to_predict, batch_size=32): 53 | 54 | sims = [] 55 | 56 | sentences_1 = list(zip(*to_predict))[0] 57 | sentences_2 = list(zip(*to_predict))[1] 58 | 59 | processed_sentences_1 = [] 60 | processed_sentences_2 = [] 61 | 62 | for sentence_1, sentence_2 in zip(sentences_1, sentences_2): 63 | processed_sentences_1.append(Sentence(sentence_1)) 64 | processed_sentences_2.append(Sentence(sentence_2)) 65 | 66 | for x in tqdm(batch(processed_sentences_1 + processed_sentences_2, batch_size), 67 | total=int(len(processed_sentences_1 + processed_sentences_2) / batch_size) + ( 68 | len(processed_sentences_1 + processed_sentences_2) % batch_size > 0), desc="Embedding sentences "): 69 | self.embedding_model.embed(x) 70 | 71 | for embed_sentence_1, embed_sentence_2 in tqdm(zip(processed_sentences_1, processed_sentences_2), total=len(processed_sentences_1), desc="Calculating similarity "): 72 | 73 | if self.model_args.remove_stopwords: 74 | embedding1 = np.average([np.array(token1.embedding.data.tolist()) for token1 in embed_sentence_1 if token1.text not in self.stop_words], axis=0) 75 | embedding2 = np.average([np.array(token2.embedding.data.tolist()) for token2 in embed_sentence_2 if token2.text not in self.stop_words], axis=0) 76 | 77 | else: 78 | embedding1 = np.average([np.array(token1.embedding.data.tolist()) for token1 in embed_sentence_1], axis=0) 79 | embedding2 = np.average([np.array(token2.embedding.data.tolist()) for token2 in embed_sentence_2], axis=0) 80 | 81 | cos_sim = dot(embedding1, embedding2) / (norm(embedding1) * norm(embedding2)) 82 | sims.append(cos_sim) 83 | 84 | return sims 85 | -------------------------------------------------------------------------------- /simplests/model_args.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass, field 2 | 3 | 4 | @dataclass 5 | class SimpleSTSArgs: 6 | distance_matrix: str = "cosine" 7 | 8 | 9 | @dataclass 10 | class WordEmbeddingSTSArgs(SimpleSTSArgs): 11 | embedding_models: list = field(default_factory=list) 12 | remove_stopwords: bool = False 13 | language: str = "en" 14 | 15 | 16 | @dataclass 17 | class SentenceEmbeddingSTSArgs(SimpleSTSArgs): 18 | embedding_model: str = "" 19 | language: str = "en" 20 | 21 | -------------------------------------------------------------------------------- /simplests/util.py: -------------------------------------------------------------------------------- 1 | 2 | def batch(iterable, n=1): 3 | l = len(iterable) 4 | for ndx in range(0, l, n): 5 | yield iterable[ndx:min(ndx + n, l)] 6 | --------------------------------------------------------------------------------