We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
annoy.py conversion of cosine distance to cosine similarity is incorrect
in [this function](https://github.com/RaRe-Technologies/gensim/blob/f35faae7a7b0c3c8586fb61208560522e37e0e7e/gensim/similarities/annoy.py#L169) the code to calculate cosine similarity is incorrect

    def most_similar(self, vector, num_neighbors):
        """Find `num_neighbors` most similar items.

        Parameters
        ----------
        vector : numpy.array
            Vector for word/document.
        num_neighbors : int
            Number of most similar items

        Returns
        -------
        list of (str, float)
            List of most similar items in format [(`item`, `cosine_distance`), ... ]

        """
        ids, distances = self.index.get_nns_by_vector(
            vector, num_neighbors, include_distances=True)

        return [(self.labels[ids[i]], 1 - distances[i] / 2) for i in range(len(ids))]

according to annoy documentation `get_nns_by_vector` with `include_distances=True` will return the distances and not the square power of the distance (this was changed since aug 2016):

_`a.get_distance(i, j)` returns the distance between items i and j. NOTE: this used to return the squared distance, but has been changed as of Aug 2016._

[link](https://github.com/spotify/annoy#:~:text=a.get_distance(i%2C%20j)%20returns%20the%20distance%20between%20items%20i%20and%20j.%20NOTE%3A%20this%20used%20to%20return%20the%20squared%20distance%2C%20but%20has%20been%20changed%20as%20of%20Aug%202016.)

also:
Annoy uses Euclidean distance of normalized vectors for its angular distance, which for two vectors u,v is equal to sqrt(2(1-cos(u,v)))
[link](https://github.com/spotify/annoy#:~:text=Annoy%20uses%20Euclidean%20distance%20of%20normalized%20vectors%20for%20its%20angular%20distance%2C%20which%20for%20two%20vectors%20u%2Cv%20is%20equal%20to%20sqrt(2(1%2Dcos(u%2Cv))))

so this means that in order to calculate the cosine similarity correctly we should do this:
`
return [(self.labels[ids[i]], 1 - distances[i]^2 / 2) for i in range(len(ids))]
`

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `gensim/similarities/annoy.py`
Content:
```
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright (C) 2013 Radim Rehurek <me@radimrehurek.com>
5 # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
6 
7 """
8 This module integrates Spotify's `Annoy <https://github.com/spotify/annoy>`_ (Approximate Nearest Neighbors Oh Yeah)
9 library with Gensim's :class:`~gensim.models.word2vec.Word2Vec`, :class:`~gensim.models.doc2vec.Doc2Vec`,
10 :class:`~gensim.models.fasttext.FastText` and :class:`~gensim.models.keyedvectors.KeyedVectors` word embeddings.
11 
12 .. Important::
13     To use this module, you must have the ``annoy`` library installed.
14     To install it, run ``pip install annoy``.
15 
16 """
17 
18 # Avoid import collisions on py2: this module has the same name as the actual Annoy library.
19 from __future__ import absolute_import
20 
21 import os
22 
23 try:
24     import cPickle as _pickle
25 except ImportError:
26     import pickle as _pickle
27 
28 from gensim import utils
29 from gensim.models.doc2vec import Doc2Vec
30 from gensim.models.word2vec import Word2Vec
31 from gensim.models.fasttext import FastText
32 from gensim.models import KeyedVectors
33 
34 
35 _NOANNOY = ImportError("Annoy not installed. To use the Annoy indexer, please run `pip install annoy`.")
36 
37 
38 class AnnoyIndexer():
39     """This class allows the use of `Annoy <https://github.com/spotify/annoy>`_ for fast (approximate)
40     vector retrieval in `most_similar()` calls of
41     :class:`~gensim.models.word2vec.Word2Vec`, :class:`~gensim.models.doc2vec.Doc2Vec`,
42     :class:`~gensim.models.fasttext.FastText` and :class:`~gensim.models.keyedvectors.Word2VecKeyedVectors` models.
43 
44     """
45 
46     def __init__(self, model=None, num_trees=None):
47         """
48         Parameters
49         ----------
50         model : trained model, optional
51             Use vectors from this model as the source for the index.
52         num_trees : int, optional
53             Number of trees for Annoy indexer.
54 
55         Examples
56         --------
57         .. sourcecode:: pycon
58 
59             >>> from gensim.similarities.annoy import AnnoyIndexer
60             >>> from gensim.models import Word2Vec
61             >>>
62             >>> sentences = [['cute', 'cat', 'say', 'meow'], ['cute', 'dog', 'say', 'woof']]
63             >>> model = Word2Vec(sentences, min_count=1, seed=1)
64             >>>
65             >>> indexer = AnnoyIndexer(model, 2)
66             >>> model.most_similar("cat", topn=2, indexer=indexer)
67             [('cat', 1.0), ('dog', 0.32011348009109497)]
68 
69         """
70         self.index = None
71         self.labels = None
72         self.model = model
73         self.num_trees = num_trees
74 
75         if model and num_trees:
76             # Extract the KeyedVectors object from whatever model we were given.
77             if isinstance(self.model, Doc2Vec):
78                 kv = self.model.dv
79             elif isinstance(self.model, (Word2Vec, FastText)):
80                 kv = self.model.wv
81             elif isinstance(self.model, (KeyedVectors,)):
82                 kv = self.model
83             else:
84                 raise ValueError("Only a Word2Vec, Doc2Vec, FastText or KeyedVectors instance can be used")
85             self._build_from_model(kv.get_normed_vectors(), kv.index_to_key, kv.vector_size)
86 
87     def save(self, fname, protocol=utils.PICKLE_PROTOCOL):
88         """Save AnnoyIndexer instance to disk.
89 
90         Parameters
91         ----------
92         fname : str
93             Path to output. Save will produce 2 files:
94             `fname`: Annoy index itself.
95             `fname.dict`: Index metadata.
96         protocol : int, optional
97             Protocol for pickle.
98 
99         Notes
100         -----
101         This method saves **only the index**. The trained model isn't preserved.
102 
103         """
104         self.index.save(fname)
105         d = {'f': self.model.vector_size, 'num_trees': self.num_trees, 'labels': self.labels}
106         with utils.open(fname + '.dict', 'wb') as fout:
107             _pickle.dump(d, fout, protocol=protocol)
108 
109     def load(self, fname):
110         """Load an AnnoyIndexer instance from disk.
111 
112         Parameters
113         ----------
114         fname : str
115             The path as previously used by ``save()``.
116 
117         Examples
118         --------
119         .. sourcecode:: pycon
120 
121             >>> from gensim.similarities.index import AnnoyIndexer
122             >>> from gensim.models import Word2Vec
123             >>> from tempfile import mkstemp
124             >>>
125             >>> sentences = [['cute', 'cat', 'say', 'meow'], ['cute', 'dog', 'say', 'woof']]
126             >>> model = Word2Vec(sentences, min_count=1, seed=1, epochs=10)
127             >>>
128             >>> indexer = AnnoyIndexer(model, 2)
129             >>> _, temp_fn = mkstemp()
130             >>> indexer.save(temp_fn)
131             >>>
132             >>> new_indexer = AnnoyIndexer()
133             >>> new_indexer.load(temp_fn)
134             >>> new_indexer.model = model
135 
136         """
137         fname_dict = fname + '.dict'
138         if not (os.path.exists(fname) and os.path.exists(fname_dict)):
139             raise IOError(
140                 f"Can't find index files '{fname}' and '{fname_dict}' - unable to restore AnnoyIndexer state."
141             )
142         try:
143             from annoy import AnnoyIndex
144         except ImportError:
145             raise _NOANNOY
146 
147         with utils.open(fname_dict, 'rb') as f:
148             d = _pickle.loads(f.read())
149         self.num_trees = d['num_trees']
150         self.index = AnnoyIndex(d['f'], metric='angular')
151         self.index.load(fname)
152         self.labels = d['labels']
153 
154     def _build_from_model(self, vectors, labels, num_features):
155         try:
156             from annoy import AnnoyIndex
157         except ImportError:
158             raise _NOANNOY
159 
160         index = AnnoyIndex(num_features, metric='angular')
161 
162         for vector_num, vector in enumerate(vectors):
163             index.add_item(vector_num, vector)
164 
165         index.build(self.num_trees)
166         self.index = index
167         self.labels = labels
168 
169     def most_similar(self, vector, num_neighbors):
170         """Find `num_neighbors` most similar items.
171 
172         Parameters
173         ----------
174         vector : numpy.array
175             Vector for word/document.
176         num_neighbors : int
177             Number of most similar items
178 
179         Returns
180         -------
181         list of (str, float)
182             List of most similar items in format [(`item`, `cosine_distance`), ... ]
183 
184         """
185         ids, distances = self.index.get_nns_by_vector(
186             vector, num_neighbors, include_distances=True)
187 
188         return [(self.labels[ids[i]], 1 - distances[i] / 2) for i in range(len(ids))]
189
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/gensim/similarities/annoy.py b/gensim/similarities/annoy.py
--- a/gensim/similarities/annoy.py
+++ b/gensim/similarities/annoy.py
@@ -185,4 +185,4 @@
         ids, distances = self.index.get_nns_by_vector(
             vector, num_neighbors, include_distances=True)
 
-        return [(self.labels[ids[i]], 1 - distances[i] / 2) for i in range(len(ids))]
+        return [(self.labels[ids[i]], 1 - distances[i] ** 2 / 2) for i in range(len(ids))]

{"golden_diff": "diff --git a/gensim/similarities/annoy.py b/gensim/similarities/annoy.py\n--- a/gensim/similarities/annoy.py\n+++ b/gensim/similarities/annoy.py\n@@ -185,4 +185,4 @@\n         ids, distances = self.index.get_nns_by_vector(\n             vector, num_neighbors, include_distances=True)\n \n-        return [(self.labels[ids[i]], 1 - distances[i] / 2) for i in range(len(ids))]\n+        return [(self.labels[ids[i]], 1 - distances[i] ** 2 / 2) for i in range(len(ids))]\n", "issue": "annoy.py conversion of cosine distance to cosine similarity is incorrect\nin [this function](https://github.com/RaRe-Technologies/gensim/blob/f35faae7a7b0c3c8586fb61208560522e37e0e7e/gensim/similarities/annoy.py#L169) the code to calculate cosine similarity is incorrect\r\n\r\n    def most_similar(self, vector, num_neighbors):\r\n        \"\"\"Find `num_neighbors` most similar items.\r\n\r\n        Parameters\r\n        ----------\r\n        vector : numpy.array\r\n            Vector for word/document.\r\n        num_neighbors : int\r\n            Number of most similar items\r\n\r\n        Returns\r\n        -------\r\n        list of (str, float)\r\n            List of most similar items in format [(`item`, `cosine_distance`), ... ]\r\n\r\n        \"\"\"\r\n        ids, distances = self.index.get_nns_by_vector(\r\n            vector, num_neighbors, include_distances=True)\r\n\r\n        return [(self.labels[ids[i]], 1 - distances[i] / 2) for i in range(len(ids))]\r\n\r\naccording to annoy documentation `get_nns_by_vector` with `include_distances=True` will return the distances and not the square power of the distance (this was changed since aug 2016):\r\n\r\n_`a.get_distance(i, j)` returns the distance between items i and j. NOTE: this used to return the squared distance, but has been changed as of Aug 2016._\r\n\r\n[link](https://github.com/spotify/annoy#:~:text=a.get_distance(i%2C%20j)%20returns%20the%20distance%20between%20items%20i%20and%20j.%20NOTE%3A%20this%20used%20to%20return%20the%20squared%20distance%2C%20but%20has%20been%20changed%20as%20of%20Aug%202016.)\r\n\r\nalso:\r\nAnnoy uses Euclidean distance of normalized vectors for its angular distance, which for two vectors u,v is equal to sqrt(2(1-cos(u,v)))\r\n[link](https://github.com/spotify/annoy#:~:text=Annoy%20uses%20Euclidean%20distance%20of%20normalized%20vectors%20for%20its%20angular%20distance%2C%20which%20for%20two%20vectors%20u%2Cv%20is%20equal%20to%20sqrt(2(1%2Dcos(u%2Cv))))\r\n\r\nso this means that in order to calculate the cosine similarity correctly we should do this:\r\n`\r\nreturn [(self.labels[ids[i]], 1 - distances[i]^2 / 2) for i in range(len(ids))]\r\n`\n", "before_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013 Radim Rehurek <me@radimrehurek.com>\n# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html\n\n\"\"\"\nThis module integrates Spotify's `Annoy <https://github.com/spotify/annoy>`_ (Approximate Nearest Neighbors Oh Yeah)\nlibrary with Gensim's :class:`~gensim.models.word2vec.Word2Vec`, :class:`~gensim.models.doc2vec.Doc2Vec`,\n:class:`~gensim.models.fasttext.FastText` and :class:`~gensim.models.keyedvectors.KeyedVectors` word embeddings.\n\n.. Important::\n    To use this module, you must have the ``annoy`` library installed.\n    To install it, run ``pip install annoy``.\n\n\"\"\"\n\n# Avoid import collisions on py2: this module has the same name as the actual Annoy library.\nfrom __future__ import absolute_import\n\nimport os\n\ntry:\n    import cPickle as _pickle\nexcept ImportError:\n    import pickle as _pickle\n\nfrom gensim import utils\nfrom gensim.models.doc2vec import Doc2Vec\nfrom gensim.models.word2vec import Word2Vec\nfrom gensim.models.fasttext import FastText\nfrom gensim.models import KeyedVectors\n\n\n_NOANNOY = ImportError(\"Annoy not installed. To use the Annoy indexer, please run `pip install annoy`.\")\n\n\nclass AnnoyIndexer():\n    \"\"\"This class allows the use of `Annoy <https://github.com/spotify/annoy>`_ for fast (approximate)\n    vector retrieval in `most_similar()` calls of\n    :class:`~gensim.models.word2vec.Word2Vec`, :class:`~gensim.models.doc2vec.Doc2Vec`,\n    :class:`~gensim.models.fasttext.FastText` and :class:`~gensim.models.keyedvectors.Word2VecKeyedVectors` models.\n\n    \"\"\"\n\n    def __init__(self, model=None, num_trees=None):\n        \"\"\"\n        Parameters\n        ----------\n        model : trained model, optional\n            Use vectors from this model as the source for the index.\n        num_trees : int, optional\n            Number of trees for Annoy indexer.\n\n        Examples\n        --------\n        .. sourcecode:: pycon\n\n            >>> from gensim.similarities.annoy import AnnoyIndexer\n            >>> from gensim.models import Word2Vec\n            >>>\n            >>> sentences = [['cute', 'cat', 'say', 'meow'], ['cute', 'dog', 'say', 'woof']]\n            >>> model = Word2Vec(sentences, min_count=1, seed=1)\n            >>>\n            >>> indexer = AnnoyIndexer(model, 2)\n            >>> model.most_similar(\"cat\", topn=2, indexer=indexer)\n            [('cat', 1.0), ('dog', 0.32011348009109497)]\n\n        \"\"\"\n        self.index = None\n        self.labels = None\n        self.model = model\n        self.num_trees = num_trees\n\n        if model and num_trees:\n            # Extract the KeyedVectors object from whatever model we were given.\n            if isinstance(self.model, Doc2Vec):\n                kv = self.model.dv\n            elif isinstance(self.model, (Word2Vec, FastText)):\n                kv = self.model.wv\n            elif isinstance(self.model, (KeyedVectors,)):\n                kv = self.model\n            else:\n                raise ValueError(\"Only a Word2Vec, Doc2Vec, FastText or KeyedVectors instance can be used\")\n            self._build_from_model(kv.get_normed_vectors(), kv.index_to_key, kv.vector_size)\n\n    def save(self, fname, protocol=utils.PICKLE_PROTOCOL):\n        \"\"\"Save AnnoyIndexer instance to disk.\n\n        Parameters\n        ----------\n        fname : str\n            Path to output. Save will produce 2 files:\n            `fname`: Annoy index itself.\n            `fname.dict`: Index metadata.\n        protocol : int, optional\n            Protocol for pickle.\n\n        Notes\n        -----\n        This method saves **only the index**. The trained model isn't preserved.\n\n        \"\"\"\n        self.index.save(fname)\n        d = {'f': self.model.vector_size, 'num_trees': self.num_trees, 'labels': self.labels}\n        with utils.open(fname + '.dict', 'wb') as fout:\n            _pickle.dump(d, fout, protocol=protocol)\n\n    def load(self, fname):\n        \"\"\"Load an AnnoyIndexer instance from disk.\n\n        Parameters\n        ----------\n        fname : str\n            The path as previously used by ``save()``.\n\n        Examples\n        --------\n        .. sourcecode:: pycon\n\n            >>> from gensim.similarities.index import AnnoyIndexer\n            >>> from gensim.models import Word2Vec\n            >>> from tempfile import mkstemp\n            >>>\n            >>> sentences = [['cute', 'cat', 'say', 'meow'], ['cute', 'dog', 'say', 'woof']]\n            >>> model = Word2Vec(sentences, min_count=1, seed=1, epochs=10)\n            >>>\n            >>> indexer = AnnoyIndexer(model, 2)\n            >>> _, temp_fn = mkstemp()\n            >>> indexer.save(temp_fn)\n            >>>\n            >>> new_indexer = AnnoyIndexer()\n            >>> new_indexer.load(temp_fn)\n            >>> new_indexer.model = model\n\n        \"\"\"\n        fname_dict = fname + '.dict'\n        if not (os.path.exists(fname) and os.path.exists(fname_dict)):\n            raise IOError(\n                f\"Can't find index files '{fname}' and '{fname_dict}' - unable to restore AnnoyIndexer state.\"\n            )\n        try:\n            from annoy import AnnoyIndex\n        except ImportError:\n            raise _NOANNOY\n\n        with utils.open(fname_dict, 'rb') as f:\n            d = _pickle.loads(f.read())\n        self.num_trees = d['num_trees']\n        self.index = AnnoyIndex(d['f'], metric='angular')\n        self.index.load(fname)\n        self.labels = d['labels']\n\n    def _build_from_model(self, vectors, labels, num_features):\n        try:\n            from annoy import AnnoyIndex\n        except ImportError:\n            raise _NOANNOY\n\n        index = AnnoyIndex(num_features, metric='angular')\n\n        for vector_num, vector in enumerate(vectors):\n            index.add_item(vector_num, vector)\n\n        index.build(self.num_trees)\n        self.index = index\n        self.labels = labels\n\n    def most_similar(self, vector, num_neighbors):\n        \"\"\"Find `num_neighbors` most similar items.\n\n        Parameters\n        ----------\n        vector : numpy.array\n            Vector for word/document.\n        num_neighbors : int\n            Number of most similar items\n\n        Returns\n        -------\n        list of (str, float)\n            List of most similar items in format [(`item`, `cosine_distance`), ... ]\n\n        \"\"\"\n        ids, distances = self.index.get_nns_by_vector(\n            vector, num_neighbors, include_distances=True)\n\n        return [(self.labels[ids[i]], 1 - distances[i] / 2) for i in range(len(ids))]\n", "path": "gensim/similarities/annoy.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013 Radim Rehurek <me@radimrehurek.com>\n# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html\n\n\"\"\"\nThis module integrates Spotify's `Annoy <https://github.com/spotify/annoy>`_ (Approximate Nearest Neighbors Oh Yeah)\nlibrary with Gensim's :class:`~gensim.models.word2vec.Word2Vec`, :class:`~gensim.models.doc2vec.Doc2Vec`,\n:class:`~gensim.models.fasttext.FastText` and :class:`~gensim.models.keyedvectors.KeyedVectors` word embeddings.\n\n.. Important::\n    To use this module, you must have the ``annoy`` library installed.\n    To install it, run ``pip install annoy``.\n\n\"\"\"\n\n# Avoid import collisions on py2: this module has the same name as the actual Annoy library.\nfrom __future__ import absolute_import\n\nimport os\n\ntry:\n    import cPickle as _pickle\nexcept ImportError:\n    import pickle as _pickle\n\nfrom gensim import utils\nfrom gensim.models.doc2vec import Doc2Vec\nfrom gensim.models.word2vec import Word2Vec\nfrom gensim.models.fasttext import FastText\nfrom gensim.models import KeyedVectors\n\n\n_NOANNOY = ImportError(\"Annoy not installed. To use the Annoy indexer, please run `pip install annoy`.\")\n\n\nclass AnnoyIndexer():\n    \"\"\"This class allows the use of `Annoy <https://github.com/spotify/annoy>`_ for fast (approximate)\n    vector retrieval in `most_similar()` calls of\n    :class:`~gensim.models.word2vec.Word2Vec`, :class:`~gensim.models.doc2vec.Doc2Vec`,\n    :class:`~gensim.models.fasttext.FastText` and :class:`~gensim.models.keyedvectors.Word2VecKeyedVectors` models.\n\n    \"\"\"\n\n    def __init__(self, model=None, num_trees=None):\n        \"\"\"\n        Parameters\n        ----------\n        model : trained model, optional\n            Use vectors from this model as the source for the index.\n        num_trees : int, optional\n            Number of trees for Annoy indexer.\n\n        Examples\n        --------\n        .. sourcecode:: pycon\n\n            >>> from gensim.similarities.annoy import AnnoyIndexer\n            >>> from gensim.models import Word2Vec\n            >>>\n            >>> sentences = [['cute', 'cat', 'say', 'meow'], ['cute', 'dog', 'say', 'woof']]\n            >>> model = Word2Vec(sentences, min_count=1, seed=1)\n            >>>\n            >>> indexer = AnnoyIndexer(model, 2)\n            >>> model.most_similar(\"cat\", topn=2, indexer=indexer)\n            [('cat', 1.0), ('dog', 0.32011348009109497)]\n\n        \"\"\"\n        self.index = None\n        self.labels = None\n        self.model = model\n        self.num_trees = num_trees\n\n        if model and num_trees:\n            # Extract the KeyedVectors object from whatever model we were given.\n            if isinstance(self.model, Doc2Vec):\n                kv = self.model.dv\n            elif isinstance(self.model, (Word2Vec, FastText)):\n                kv = self.model.wv\n            elif isinstance(self.model, (KeyedVectors,)):\n                kv = self.model\n            else:\n                raise ValueError(\"Only a Word2Vec, Doc2Vec, FastText or KeyedVectors instance can be used\")\n            self._build_from_model(kv.get_normed_vectors(), kv.index_to_key, kv.vector_size)\n\n    def save(self, fname, protocol=utils.PICKLE_PROTOCOL):\n        \"\"\"Save AnnoyIndexer instance to disk.\n\n        Parameters\n        ----------\n        fname : str\n            Path to output. Save will produce 2 files:\n            `fname`: Annoy index itself.\n            `fname.dict`: Index metadata.\n        protocol : int, optional\n            Protocol for pickle.\n\n        Notes\n        -----\n        This method saves **only the index**. The trained model isn't preserved.\n\n        \"\"\"\n        self.index.save(fname)\n        d = {'f': self.model.vector_size, 'num_trees': self.num_trees, 'labels': self.labels}\n        with utils.open(fname + '.dict', 'wb') as fout:\n            _pickle.dump(d, fout, protocol=protocol)\n\n    def load(self, fname):\n        \"\"\"Load an AnnoyIndexer instance from disk.\n\n        Parameters\n        ----------\n        fname : str\n            The path as previously used by ``save()``.\n\n        Examples\n        --------\n        .. sourcecode:: pycon\n\n            >>> from gensim.similarities.index import AnnoyIndexer\n            >>> from gensim.models import Word2Vec\n            >>> from tempfile import mkstemp\n            >>>\n            >>> sentences = [['cute', 'cat', 'say', 'meow'], ['cute', 'dog', 'say', 'woof']]\n            >>> model = Word2Vec(sentences, min_count=1, seed=1, epochs=10)\n            >>>\n            >>> indexer = AnnoyIndexer(model, 2)\n            >>> _, temp_fn = mkstemp()\n            >>> indexer.save(temp_fn)\n            >>>\n            >>> new_indexer = AnnoyIndexer()\n            >>> new_indexer.load(temp_fn)\n            >>> new_indexer.model = model\n\n        \"\"\"\n        fname_dict = fname + '.dict'\n        if not (os.path.exists(fname) and os.path.exists(fname_dict)):\n            raise IOError(\n                f\"Can't find index files '{fname}' and '{fname_dict}' - unable to restore AnnoyIndexer state.\"\n            )\n        try:\n            from annoy import AnnoyIndex\n        except ImportError:\n            raise _NOANNOY\n\n        with utils.open(fname_dict, 'rb') as f:\n            d = _pickle.loads(f.read())\n        self.num_trees = d['num_trees']\n        self.index = AnnoyIndex(d['f'], metric='angular')\n        self.index.load(fname)\n        self.labels = d['labels']\n\n    def _build_from_model(self, vectors, labels, num_features):\n        try:\n            from annoy import AnnoyIndex\n        except ImportError:\n            raise _NOANNOY\n\n        index = AnnoyIndex(num_features, metric='angular')\n\n        for vector_num, vector in enumerate(vectors):\n            index.add_item(vector_num, vector)\n\n        index.build(self.num_trees)\n        self.index = index\n        self.labels = labels\n\n    def most_similar(self, vector, num_neighbors):\n        \"\"\"Find `num_neighbors` most similar items.\n\n        Parameters\n        ----------\n        vector : numpy.array\n            Vector for word/document.\n        num_neighbors : int\n            Number of most similar items\n\n        Returns\n        -------\n        list of (str, float)\n            List of most similar items in format [(`item`, `cosine_distance`), ... ]\n\n        \"\"\"\n        ids, distances = self.index.get_nns_by_vector(\n            vector, num_neighbors, include_distances=True)\n\n        return [(self.labels[ids[i]], 1 - distances[i] ** 2 / 2) for i in range(len(ids))]\n", "path": "gensim/similarities/annoy.py"}]}