We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
D2VTransformer raises if passed a Pandas series without index key 0
`D2VTransformer` raises if passed a Pandas series with an index that does not contain the key 0:

```python
import pandas as pd
from gensim.sklearn_api import D2VTransformer
from gensim.test.utils import common_texts

series = pd.Series(common_texts)
series.index += 1  # Increment the index so that it does not contain the key 0

transformer = D2VTransformer(min_count=1, size=5)
transformer.fit(series)
```

Output:

```python
﻿Traceback (most recent call last):
  File "main.py", line 9, in <module>
    transformer.fit(series)
  File "venv/lib/python3.7/site-packages/gensim/sklearn_api/d2vmodel.py", line 162, in fit
    if isinstance(X[0], doc2vec.TaggedDocument):
  File "venv/lib/python3.7/site-packages/pandas/core/series.py", line 868, in __getitem__
    result = self.index.get_value(self, key)
  File "venv/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 4375, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas/_libs/index.pyx", line 81, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 89, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 987, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 993, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 0
```

This occurs because the [`fit`](https://github.com/RaRe-Technologies/gensim/blob/4543646d3fe3496e11bc935e72cbf9b18504442e/gensim/sklearn_api/d2vmodel.py#L162) and [`transform`](https://github.com/RaRe-Technologies/gensim/blob/4543646d3fe3496e11bc935e72cbf9b18504442e/gensim/sklearn_api/d2vmodel.py#L198) methods of `D2VTransformer` require `__getitem__` on the passed iterable not to raise an exception for key 0.

Versions:

Darwin-18.6.0-x86_64-i386-64bit
Python 3.7.3 (default, Mar 27 2019, 09:23:15) [Clang 10.0.1 (clang-1001.0.46.3)]
NumPy 1.16.4
SciPy 1.3.0
gensim 3.8.0
FAST_VERSION 1

--- 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/sklearn_api/d2vmodel.py`
Content:
```
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright (C) 2011 Radim Rehurek <radimrehurek@seznam.cz>
5 # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
6 
7 """Scikit learn interface for :class:`~gensim.models.doc2vec.Doc2Vec`.
8 
9 Follows scikit-learn API conventions to facilitate using gensim along with scikit-learn.
10 
11 Examples
12 --------
13 .. sourcecode:: pycon
14 
15     >>> from gensim.test.utils import common_texts
16     >>> from gensim.sklearn_api import D2VTransformer
17     >>>
18     >>> model = D2VTransformer(min_count=1, size=5)
19     >>> docvecs = model.fit_transform(common_texts)  # represent `common_texts` as vectors
20 
21 """
22 import numpy as np
23 from six import string_types
24 from sklearn.base import TransformerMixin, BaseEstimator
25 from sklearn.exceptions import NotFittedError
26 
27 from gensim import models
28 from gensim.models import doc2vec
29 
30 
31 class D2VTransformer(TransformerMixin, BaseEstimator):
32     """Base Doc2Vec module, wraps :class:`~gensim.models.doc2vec.Doc2Vec`.
33 
34     This model based on `Quoc Le, Tomas Mikolov: "Distributed Representations of Sentences and Documents"
35     <https://cs.stanford.edu/~quocle/paragraph_vector.pdf>`_.
36 
37     """
38     def __init__(self, dm_mean=None, dm=1, dbow_words=0, dm_concat=0, dm_tag_count=1, docvecs=None,
39                  docvecs_mapfile=None, comment=None, trim_rule=None, size=100, alpha=0.025, window=5, min_count=5,
40                  max_vocab_size=None, sample=1e-3, seed=1, workers=3, min_alpha=0.0001, hs=0, negative=5, cbow_mean=1,
41                  hashfxn=hash, iter=5, sorted_vocab=1, batch_words=10000):
42         """
43 
44         Parameters
45         ----------
46 
47         dm_mean : int {1,0}, optional
48             If 0, use the sum of the context word vectors. If 1, use the mean. Only applies when `dm_concat=0`.
49         dm : int {1,0}, optional
50             Defines the training algorithm. If `dm=1` - distributed memory (PV-DM) is used.
51             Otherwise, distributed bag of words (PV-DBOW) is employed.
52         dbow_words : int {1,0}, optional
53             If set to 1 - trains word-vectors (in skip-gram fashion) simultaneous with DBOW
54             doc-vector training, If 0, only trains doc-vectors (faster).
55         dm_concat : int {1,0}, optional
56             If 1, use concatenation of context vectors rather than sum/average.
57             Note concatenation results in a much-larger model, as the input is no longer the size of one
58             (sampled or arithmetically combined) word vector, but the size of the tag(s) and all words
59             in the context strung together.
60         dm_tag_count : int, optional
61             Expected constant number of document tags per document, when using dm_concat mode.
62         docvecs : :class:`~gensim.models.keyedvectors.Doc2VecKeyedVectors`
63             A mapping from a string or int tag to its vector representation.
64             Either this or `docvecs_mapfile` **MUST** be supplied.
65         docvecs_mapfile : str, optional
66             Path to a file containing the docvecs mapping. If `docvecs` is None, this file will be used to create it.
67         comment : str, optional
68             A model descriptive comment, used for logging and debugging purposes.
69         trim_rule : function ((str, int, int) -> int), optional
70             Vocabulary trimming rule that accepts (word, count, min_count).
71             Specifies whether certain words should remain in the vocabulary (:attr:`gensim.utils.RULE_KEEP`),
72             be trimmed away (:attr:`gensim.utils.RULE_DISCARD`), or handled using the default
73             (:attr:`gensim.utils.RULE_DEFAULT`).
74             If None, then :func:`gensim.utils.keep_vocab_item` will be used.
75         size : int, optional
76             Dimensionality of the feature vectors.
77         alpha : float, optional
78             The initial learning rate.
79         window : int, optional
80             The maximum distance between the current and predicted word within a sentence.
81         min_count : int, optional
82             Ignores all words with total frequency lower than this.
83         max_vocab_size : int, optional
84             Limits the RAM during vocabulary building; if there are more unique
85             words than this, then prune the infrequent ones. Every 10 million word types need about 1GB of RAM.
86             Set to `None` for no limit.
87         sample : float, optional
88             The threshold for configuring which higher-frequency words are randomly downsampled,
89             useful range is (0, 1e-5).
90         seed : int, optional
91             Seed for the random number generator. Initial vectors for each word are seeded with a hash of
92             the concatenation of word + `str(seed)`.
93             Note that for a **fully deterministically-reproducible run**, you **must also limit the model to
94             a single worker thread (`workers=1`)**, to eliminate ordering jitter from OS thread scheduling.
95             In Python 3, reproducibility between interpreter launches also requires use of the `PYTHONHASHSEED`
96             environment variable to control hash randomization.
97         workers : int, optional
98             Use this many worker threads to train the model. Will yield a speedup when training with multicore machines.
99         min_alpha : float, optional
100             Learning rate will linearly drop to `min_alpha` as training progresses.
101         hs : int {1,0}, optional
102             If 1, hierarchical softmax will be used for model training. If set to 0, and `negative` is non-zero,
103             negative sampling will be used.
104         negative : int, optional
105             If > 0, negative sampling will be used, the int for negative specifies how many "noise words"
106             should be drawn (usually between 5-20). If set to 0, no negative sampling is used.
107         cbow_mean : int, optional
108             Same as `dm_mean`, **unused**.
109         hashfxn : function (object -> int), optional
110             A hashing function. Used to create an initial random reproducible vector by hashing the random seed.
111         iter : int, optional
112             Number of epochs to iterate through the corpus.
113         sorted_vocab : bool, optional
114             Whether the vocabulary should be sorted internally.
115         batch_words : int, optional
116             Number of words to be handled by each job.
117 
118         """
119         self.gensim_model = None
120         self.dm_mean = dm_mean
121         self.dm = dm
122         self.dbow_words = dbow_words
123         self.dm_concat = dm_concat
124         self.dm_tag_count = dm_tag_count
125         self.docvecs = docvecs
126         self.docvecs_mapfile = docvecs_mapfile
127         self.comment = comment
128         self.trim_rule = trim_rule
129 
130         # attributes associated with gensim.models.Word2Vec
131         self.size = size
132         self.alpha = alpha
133         self.window = window
134         self.min_count = min_count
135         self.max_vocab_size = max_vocab_size
136         self.sample = sample
137         self.seed = seed
138         self.workers = workers
139         self.min_alpha = min_alpha
140         self.hs = hs
141         self.negative = negative
142         self.cbow_mean = int(cbow_mean)
143         self.hashfxn = hashfxn
144         self.iter = iter
145         self.sorted_vocab = sorted_vocab
146         self.batch_words = batch_words
147 
148     def fit(self, X, y=None):
149         """Fit the model according to the given training data.
150 
151         Parameters
152         ----------
153         X : {iterable of :class:`~gensim.models.doc2vec.TaggedDocument`, iterable of list of str}
154             A collection of tagged documents used for training the model.
155 
156         Returns
157         -------
158         :class:`~gensim.sklearn_api.d2vmodel.D2VTransformer`
159             The trained model.
160 
161         """
162         if isinstance(X[0], doc2vec.TaggedDocument):
163             d2v_sentences = X
164         else:
165             d2v_sentences = [doc2vec.TaggedDocument(words, [i]) for i, words in enumerate(X)]
166         self.gensim_model = models.Doc2Vec(
167             documents=d2v_sentences, dm_mean=self.dm_mean, dm=self.dm,
168             dbow_words=self.dbow_words, dm_concat=self.dm_concat, dm_tag_count=self.dm_tag_count,
169             docvecs=self.docvecs, docvecs_mapfile=self.docvecs_mapfile, comment=self.comment,
170             trim_rule=self.trim_rule, vector_size=self.size, alpha=self.alpha, window=self.window,
171             min_count=self.min_count, max_vocab_size=self.max_vocab_size, sample=self.sample,
172             seed=self.seed, workers=self.workers, min_alpha=self.min_alpha, hs=self.hs,
173             negative=self.negative, cbow_mean=self.cbow_mean, hashfxn=self.hashfxn,
174             epochs=self.iter, sorted_vocab=self.sorted_vocab, batch_words=self.batch_words
175         )
176         return self
177 
178     def transform(self, docs):
179         """Infer the vector representations for the input documents.
180 
181         Parameters
182         ----------
183         docs : {iterable of list of str, list of str}
184             Input document or sequence of documents.
185 
186         Returns
187         -------
188         numpy.ndarray of shape [`len(docs)`, `size`]
189             The vector representation of the `docs`.
190 
191         """
192         if self.gensim_model is None:
193             raise NotFittedError(
194                 "This model has not been fitted yet. Call 'fit' with appropriate arguments before using this method."
195             )
196 
197         # The input as array of array
198         if isinstance(docs[0], string_types):
199             docs = [docs]
200         vectors = [self.gensim_model.infer_vector(doc) for doc in docs]
201         return np.reshape(np.array(vectors), (len(docs), self.gensim_model.vector_size))
202
```
--- 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/sklearn_api/d2vmodel.py b/gensim/sklearn_api/d2vmodel.py
--- a/gensim/sklearn_api/d2vmodel.py
+++ b/gensim/sklearn_api/d2vmodel.py
@@ -159,7 +159,7 @@
             The trained model.
 
         """
-        if isinstance(X[0], doc2vec.TaggedDocument):
+        if isinstance([i for i in X[:1]][0], doc2vec.TaggedDocument):
             d2v_sentences = X
         else:
             d2v_sentences = [doc2vec.TaggedDocument(words, [i]) for i, words in enumerate(X)]

{"golden_diff": "diff --git a/gensim/sklearn_api/d2vmodel.py b/gensim/sklearn_api/d2vmodel.py\n--- a/gensim/sklearn_api/d2vmodel.py\n+++ b/gensim/sklearn_api/d2vmodel.py\n@@ -159,7 +159,7 @@\n             The trained model.\n \n         \"\"\"\n-        if isinstance(X[0], doc2vec.TaggedDocument):\n+        if isinstance([i for i in X[:1]][0], doc2vec.TaggedDocument):\n             d2v_sentences = X\n         else:\n             d2v_sentences = [doc2vec.TaggedDocument(words, [i]) for i, words in enumerate(X)]\n", "issue": "D2VTransformer raises if passed a Pandas series without index key 0\n`D2VTransformer` raises if passed a Pandas series with an index that does not contain the key 0:\r\n\r\n```python\r\nimport pandas as pd\r\nfrom gensim.sklearn_api import D2VTransformer\r\nfrom gensim.test.utils import common_texts\r\n\r\nseries = pd.Series(common_texts)\r\nseries.index += 1  # Increment the index so that it does not contain the key 0\r\n\r\ntransformer = D2VTransformer(min_count=1, size=5)\r\ntransformer.fit(series)\r\n```\r\n\r\nOutput:\r\n\r\n```python\r\n\ufeffTraceback (most recent call last):\r\n  File \"main.py\", line 9, in <module>\r\n    transformer.fit(series)\r\n  File \"venv/lib/python3.7/site-packages/gensim/sklearn_api/d2vmodel.py\", line 162, in fit\r\n    if isinstance(X[0], doc2vec.TaggedDocument):\r\n  File \"venv/lib/python3.7/site-packages/pandas/core/series.py\", line 868, in __getitem__\r\n    result = self.index.get_value(self, key)\r\n  File \"venv/lib/python3.7/site-packages/pandas/core/indexes/base.py\", line 4375, in get_value\r\n    tz=getattr(series.dtype, 'tz', None))\r\n  File \"pandas/_libs/index.pyx\", line 81, in pandas._libs.index.IndexEngine.get_value\r\n  File \"pandas/_libs/index.pyx\", line 89, in pandas._libs.index.IndexEngine.get_value\r\n  File \"pandas/_libs/index.pyx\", line 132, in pandas._libs.index.IndexEngine.get_loc\r\n  File \"pandas/_libs/hashtable_class_helper.pxi\", line 987, in pandas._libs.hashtable.Int64HashTable.get_item\r\n  File \"pandas/_libs/hashtable_class_helper.pxi\", line 993, in pandas._libs.hashtable.Int64HashTable.get_item\r\nKeyError: 0\r\n```\r\n\r\nThis occurs because the [`fit`](https://github.com/RaRe-Technologies/gensim/blob/4543646d3fe3496e11bc935e72cbf9b18504442e/gensim/sklearn_api/d2vmodel.py#L162) and [`transform`](https://github.com/RaRe-Technologies/gensim/blob/4543646d3fe3496e11bc935e72cbf9b18504442e/gensim/sklearn_api/d2vmodel.py#L198) methods of `D2VTransformer` require `__getitem__` on the passed iterable not to raise an exception for key 0.\r\n\r\nVersions:\r\n\r\nDarwin-18.6.0-x86_64-i386-64bit\r\nPython 3.7.3 (default, Mar 27 2019, 09:23:15) [Clang 10.0.1 (clang-1001.0.46.3)]\r\nNumPy 1.16.4\r\nSciPy 1.3.0\r\ngensim 3.8.0\r\nFAST_VERSION 1\n", "before_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2011 Radim Rehurek <radimrehurek@seznam.cz>\n# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html\n\n\"\"\"Scikit learn interface for :class:`~gensim.models.doc2vec.Doc2Vec`.\n\nFollows scikit-learn API conventions to facilitate using gensim along with scikit-learn.\n\nExamples\n--------\n.. sourcecode:: pycon\n\n    >>> from gensim.test.utils import common_texts\n    >>> from gensim.sklearn_api import D2VTransformer\n    >>>\n    >>> model = D2VTransformer(min_count=1, size=5)\n    >>> docvecs = model.fit_transform(common_texts)  # represent `common_texts` as vectors\n\n\"\"\"\nimport numpy as np\nfrom six import string_types\nfrom sklearn.base import TransformerMixin, BaseEstimator\nfrom sklearn.exceptions import NotFittedError\n\nfrom gensim import models\nfrom gensim.models import doc2vec\n\n\nclass D2VTransformer(TransformerMixin, BaseEstimator):\n    \"\"\"Base Doc2Vec module, wraps :class:`~gensim.models.doc2vec.Doc2Vec`.\n\n    This model based on `Quoc Le, Tomas Mikolov: \"Distributed Representations of Sentences and Documents\"\n    <https://cs.stanford.edu/~quocle/paragraph_vector.pdf>`_.\n\n    \"\"\"\n    def __init__(self, dm_mean=None, dm=1, dbow_words=0, dm_concat=0, dm_tag_count=1, docvecs=None,\n                 docvecs_mapfile=None, comment=None, trim_rule=None, size=100, alpha=0.025, window=5, min_count=5,\n                 max_vocab_size=None, sample=1e-3, seed=1, workers=3, min_alpha=0.0001, hs=0, negative=5, cbow_mean=1,\n                 hashfxn=hash, iter=5, sorted_vocab=1, batch_words=10000):\n        \"\"\"\n\n        Parameters\n        ----------\n\n        dm_mean : int {1,0}, optional\n            If 0, use the sum of the context word vectors. If 1, use the mean. Only applies when `dm_concat=0`.\n        dm : int {1,0}, optional\n            Defines the training algorithm. If `dm=1` - distributed memory (PV-DM) is used.\n            Otherwise, distributed bag of words (PV-DBOW) is employed.\n        dbow_words : int {1,0}, optional\n            If set to 1 - trains word-vectors (in skip-gram fashion) simultaneous with DBOW\n            doc-vector training, If 0, only trains doc-vectors (faster).\n        dm_concat : int {1,0}, optional\n            If 1, use concatenation of context vectors rather than sum/average.\n            Note concatenation results in a much-larger model, as the input is no longer the size of one\n            (sampled or arithmetically combined) word vector, but the size of the tag(s) and all words\n            in the context strung together.\n        dm_tag_count : int, optional\n            Expected constant number of document tags per document, when using dm_concat mode.\n        docvecs : :class:`~gensim.models.keyedvectors.Doc2VecKeyedVectors`\n            A mapping from a string or int tag to its vector representation.\n            Either this or `docvecs_mapfile` **MUST** be supplied.\n        docvecs_mapfile : str, optional\n            Path to a file containing the docvecs mapping. If `docvecs` is None, this file will be used to create it.\n        comment : str, optional\n            A model descriptive comment, used for logging and debugging purposes.\n        trim_rule : function ((str, int, int) -> int), optional\n            Vocabulary trimming rule that accepts (word, count, min_count).\n            Specifies whether certain words should remain in the vocabulary (:attr:`gensim.utils.RULE_KEEP`),\n            be trimmed away (:attr:`gensim.utils.RULE_DISCARD`), or handled using the default\n            (:attr:`gensim.utils.RULE_DEFAULT`).\n            If None, then :func:`gensim.utils.keep_vocab_item` will be used.\n        size : int, optional\n            Dimensionality of the feature vectors.\n        alpha : float, optional\n            The initial learning rate.\n        window : int, optional\n            The maximum distance between the current and predicted word within a sentence.\n        min_count : int, optional\n            Ignores all words with total frequency lower than this.\n        max_vocab_size : int, optional\n            Limits the RAM during vocabulary building; if there are more unique\n            words than this, then prune the infrequent ones. Every 10 million word types need about 1GB of RAM.\n            Set to `None` for no limit.\n        sample : float, optional\n            The threshold for configuring which higher-frequency words are randomly downsampled,\n            useful range is (0, 1e-5).\n        seed : int, optional\n            Seed for the random number generator. Initial vectors for each word are seeded with a hash of\n            the concatenation of word + `str(seed)`.\n            Note that for a **fully deterministically-reproducible run**, you **must also limit the model to\n            a single worker thread (`workers=1`)**, to eliminate ordering jitter from OS thread scheduling.\n            In Python 3, reproducibility between interpreter launches also requires use of the `PYTHONHASHSEED`\n            environment variable to control hash randomization.\n        workers : int, optional\n            Use this many worker threads to train the model. Will yield a speedup when training with multicore machines.\n        min_alpha : float, optional\n            Learning rate will linearly drop to `min_alpha` as training progresses.\n        hs : int {1,0}, optional\n            If 1, hierarchical softmax will be used for model training. If set to 0, and `negative` is non-zero,\n            negative sampling will be used.\n        negative : int, optional\n            If > 0, negative sampling will be used, the int for negative specifies how many \"noise words\"\n            should be drawn (usually between 5-20). If set to 0, no negative sampling is used.\n        cbow_mean : int, optional\n            Same as `dm_mean`, **unused**.\n        hashfxn : function (object -> int), optional\n            A hashing function. Used to create an initial random reproducible vector by hashing the random seed.\n        iter : int, optional\n            Number of epochs to iterate through the corpus.\n        sorted_vocab : bool, optional\n            Whether the vocabulary should be sorted internally.\n        batch_words : int, optional\n            Number of words to be handled by each job.\n\n        \"\"\"\n        self.gensim_model = None\n        self.dm_mean = dm_mean\n        self.dm = dm\n        self.dbow_words = dbow_words\n        self.dm_concat = dm_concat\n        self.dm_tag_count = dm_tag_count\n        self.docvecs = docvecs\n        self.docvecs_mapfile = docvecs_mapfile\n        self.comment = comment\n        self.trim_rule = trim_rule\n\n        # attributes associated with gensim.models.Word2Vec\n        self.size = size\n        self.alpha = alpha\n        self.window = window\n        self.min_count = min_count\n        self.max_vocab_size = max_vocab_size\n        self.sample = sample\n        self.seed = seed\n        self.workers = workers\n        self.min_alpha = min_alpha\n        self.hs = hs\n        self.negative = negative\n        self.cbow_mean = int(cbow_mean)\n        self.hashfxn = hashfxn\n        self.iter = iter\n        self.sorted_vocab = sorted_vocab\n        self.batch_words = batch_words\n\n    def fit(self, X, y=None):\n        \"\"\"Fit the model according to the given training data.\n\n        Parameters\n        ----------\n        X : {iterable of :class:`~gensim.models.doc2vec.TaggedDocument`, iterable of list of str}\n            A collection of tagged documents used for training the model.\n\n        Returns\n        -------\n        :class:`~gensim.sklearn_api.d2vmodel.D2VTransformer`\n            The trained model.\n\n        \"\"\"\n        if isinstance(X[0], doc2vec.TaggedDocument):\n            d2v_sentences = X\n        else:\n            d2v_sentences = [doc2vec.TaggedDocument(words, [i]) for i, words in enumerate(X)]\n        self.gensim_model = models.Doc2Vec(\n            documents=d2v_sentences, dm_mean=self.dm_mean, dm=self.dm,\n            dbow_words=self.dbow_words, dm_concat=self.dm_concat, dm_tag_count=self.dm_tag_count,\n            docvecs=self.docvecs, docvecs_mapfile=self.docvecs_mapfile, comment=self.comment,\n            trim_rule=self.trim_rule, vector_size=self.size, alpha=self.alpha, window=self.window,\n            min_count=self.min_count, max_vocab_size=self.max_vocab_size, sample=self.sample,\n            seed=self.seed, workers=self.workers, min_alpha=self.min_alpha, hs=self.hs,\n            negative=self.negative, cbow_mean=self.cbow_mean, hashfxn=self.hashfxn,\n            epochs=self.iter, sorted_vocab=self.sorted_vocab, batch_words=self.batch_words\n        )\n        return self\n\n    def transform(self, docs):\n        \"\"\"Infer the vector representations for the input documents.\n\n        Parameters\n        ----------\n        docs : {iterable of list of str, list of str}\n            Input document or sequence of documents.\n\n        Returns\n        -------\n        numpy.ndarray of shape [`len(docs)`, `size`]\n            The vector representation of the `docs`.\n\n        \"\"\"\n        if self.gensim_model is None:\n            raise NotFittedError(\n                \"This model has not been fitted yet. Call 'fit' with appropriate arguments before using this method.\"\n            )\n\n        # The input as array of array\n        if isinstance(docs[0], string_types):\n            docs = [docs]\n        vectors = [self.gensim_model.infer_vector(doc) for doc in docs]\n        return np.reshape(np.array(vectors), (len(docs), self.gensim_model.vector_size))\n", "path": "gensim/sklearn_api/d2vmodel.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2011 Radim Rehurek <radimrehurek@seznam.cz>\n# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html\n\n\"\"\"Scikit learn interface for :class:`~gensim.models.doc2vec.Doc2Vec`.\n\nFollows scikit-learn API conventions to facilitate using gensim along with scikit-learn.\n\nExamples\n--------\n.. sourcecode:: pycon\n\n    >>> from gensim.test.utils import common_texts\n    >>> from gensim.sklearn_api import D2VTransformer\n    >>>\n    >>> model = D2VTransformer(min_count=1, size=5)\n    >>> docvecs = model.fit_transform(common_texts)  # represent `common_texts` as vectors\n\n\"\"\"\nimport numpy as np\nfrom six import string_types\nfrom sklearn.base import TransformerMixin, BaseEstimator\nfrom sklearn.exceptions import NotFittedError\n\nfrom gensim import models\nfrom gensim.models import doc2vec\n\n\nclass D2VTransformer(TransformerMixin, BaseEstimator):\n    \"\"\"Base Doc2Vec module, wraps :class:`~gensim.models.doc2vec.Doc2Vec`.\n\n    This model based on `Quoc Le, Tomas Mikolov: \"Distributed Representations of Sentences and Documents\"\n    <https://cs.stanford.edu/~quocle/paragraph_vector.pdf>`_.\n\n    \"\"\"\n    def __init__(self, dm_mean=None, dm=1, dbow_words=0, dm_concat=0, dm_tag_count=1, docvecs=None,\n                 docvecs_mapfile=None, comment=None, trim_rule=None, size=100, alpha=0.025, window=5, min_count=5,\n                 max_vocab_size=None, sample=1e-3, seed=1, workers=3, min_alpha=0.0001, hs=0, negative=5, cbow_mean=1,\n                 hashfxn=hash, iter=5, sorted_vocab=1, batch_words=10000):\n        \"\"\"\n\n        Parameters\n        ----------\n\n        dm_mean : int {1,0}, optional\n            If 0, use the sum of the context word vectors. If 1, use the mean. Only applies when `dm_concat=0`.\n        dm : int {1,0}, optional\n            Defines the training algorithm. If `dm=1` - distributed memory (PV-DM) is used.\n            Otherwise, distributed bag of words (PV-DBOW) is employed.\n        dbow_words : int {1,0}, optional\n            If set to 1 - trains word-vectors (in skip-gram fashion) simultaneous with DBOW\n            doc-vector training, If 0, only trains doc-vectors (faster).\n        dm_concat : int {1,0}, optional\n            If 1, use concatenation of context vectors rather than sum/average.\n            Note concatenation results in a much-larger model, as the input is no longer the size of one\n            (sampled or arithmetically combined) word vector, but the size of the tag(s) and all words\n            in the context strung together.\n        dm_tag_count : int, optional\n            Expected constant number of document tags per document, when using dm_concat mode.\n        docvecs : :class:`~gensim.models.keyedvectors.Doc2VecKeyedVectors`\n            A mapping from a string or int tag to its vector representation.\n            Either this or `docvecs_mapfile` **MUST** be supplied.\n        docvecs_mapfile : str, optional\n            Path to a file containing the docvecs mapping. If `docvecs` is None, this file will be used to create it.\n        comment : str, optional\n            A model descriptive comment, used for logging and debugging purposes.\n        trim_rule : function ((str, int, int) -> int), optional\n            Vocabulary trimming rule that accepts (word, count, min_count).\n            Specifies whether certain words should remain in the vocabulary (:attr:`gensim.utils.RULE_KEEP`),\n            be trimmed away (:attr:`gensim.utils.RULE_DISCARD`), or handled using the default\n            (:attr:`gensim.utils.RULE_DEFAULT`).\n            If None, then :func:`gensim.utils.keep_vocab_item` will be used.\n        size : int, optional\n            Dimensionality of the feature vectors.\n        alpha : float, optional\n            The initial learning rate.\n        window : int, optional\n            The maximum distance between the current and predicted word within a sentence.\n        min_count : int, optional\n            Ignores all words with total frequency lower than this.\n        max_vocab_size : int, optional\n            Limits the RAM during vocabulary building; if there are more unique\n            words than this, then prune the infrequent ones. Every 10 million word types need about 1GB of RAM.\n            Set to `None` for no limit.\n        sample : float, optional\n            The threshold for configuring which higher-frequency words are randomly downsampled,\n            useful range is (0, 1e-5).\n        seed : int, optional\n            Seed for the random number generator. Initial vectors for each word are seeded with a hash of\n            the concatenation of word + `str(seed)`.\n            Note that for a **fully deterministically-reproducible run**, you **must also limit the model to\n            a single worker thread (`workers=1`)**, to eliminate ordering jitter from OS thread scheduling.\n            In Python 3, reproducibility between interpreter launches also requires use of the `PYTHONHASHSEED`\n            environment variable to control hash randomization.\n        workers : int, optional\n            Use this many worker threads to train the model. Will yield a speedup when training with multicore machines.\n        min_alpha : float, optional\n            Learning rate will linearly drop to `min_alpha` as training progresses.\n        hs : int {1,0}, optional\n            If 1, hierarchical softmax will be used for model training. If set to 0, and `negative` is non-zero,\n            negative sampling will be used.\n        negative : int, optional\n            If > 0, negative sampling will be used, the int for negative specifies how many \"noise words\"\n            should be drawn (usually between 5-20). If set to 0, no negative sampling is used.\n        cbow_mean : int, optional\n            Same as `dm_mean`, **unused**.\n        hashfxn : function (object -> int), optional\n            A hashing function. Used to create an initial random reproducible vector by hashing the random seed.\n        iter : int, optional\n            Number of epochs to iterate through the corpus.\n        sorted_vocab : bool, optional\n            Whether the vocabulary should be sorted internally.\n        batch_words : int, optional\n            Number of words to be handled by each job.\n\n        \"\"\"\n        self.gensim_model = None\n        self.dm_mean = dm_mean\n        self.dm = dm\n        self.dbow_words = dbow_words\n        self.dm_concat = dm_concat\n        self.dm_tag_count = dm_tag_count\n        self.docvecs = docvecs\n        self.docvecs_mapfile = docvecs_mapfile\n        self.comment = comment\n        self.trim_rule = trim_rule\n\n        # attributes associated with gensim.models.Word2Vec\n        self.size = size\n        self.alpha = alpha\n        self.window = window\n        self.min_count = min_count\n        self.max_vocab_size = max_vocab_size\n        self.sample = sample\n        self.seed = seed\n        self.workers = workers\n        self.min_alpha = min_alpha\n        self.hs = hs\n        self.negative = negative\n        self.cbow_mean = int(cbow_mean)\n        self.hashfxn = hashfxn\n        self.iter = iter\n        self.sorted_vocab = sorted_vocab\n        self.batch_words = batch_words\n\n    def fit(self, X, y=None):\n        \"\"\"Fit the model according to the given training data.\n\n        Parameters\n        ----------\n        X : {iterable of :class:`~gensim.models.doc2vec.TaggedDocument`, iterable of list of str}\n            A collection of tagged documents used for training the model.\n\n        Returns\n        -------\n        :class:`~gensim.sklearn_api.d2vmodel.D2VTransformer`\n            The trained model.\n\n        \"\"\"\n        if isinstance([i for i in X[:1]][0], doc2vec.TaggedDocument):\n            d2v_sentences = X\n        else:\n            d2v_sentences = [doc2vec.TaggedDocument(words, [i]) for i, words in enumerate(X)]\n        self.gensim_model = models.Doc2Vec(\n            documents=d2v_sentences, dm_mean=self.dm_mean, dm=self.dm,\n            dbow_words=self.dbow_words, dm_concat=self.dm_concat, dm_tag_count=self.dm_tag_count,\n            docvecs=self.docvecs, docvecs_mapfile=self.docvecs_mapfile, comment=self.comment,\n            trim_rule=self.trim_rule, vector_size=self.size, alpha=self.alpha, window=self.window,\n            min_count=self.min_count, max_vocab_size=self.max_vocab_size, sample=self.sample,\n            seed=self.seed, workers=self.workers, min_alpha=self.min_alpha, hs=self.hs,\n            negative=self.negative, cbow_mean=self.cbow_mean, hashfxn=self.hashfxn,\n            epochs=self.iter, sorted_vocab=self.sorted_vocab, batch_words=self.batch_words\n        )\n        return self\n\n    def transform(self, docs):\n        \"\"\"Infer the vector representations for the input documents.\n\n        Parameters\n        ----------\n        docs : {iterable of list of str, list of str}\n            Input document or sequence of documents.\n\n        Returns\n        -------\n        numpy.ndarray of shape [`len(docs)`, `size`]\n            The vector representation of the `docs`.\n\n        \"\"\"\n        if self.gensim_model is None:\n            raise NotFittedError(\n                \"This model has not been fitted yet. Call 'fit' with appropriate arguments before using this method.\"\n            )\n\n        # The input as array of array\n        if isinstance(docs[0], string_types):\n            docs = [docs]\n        vectors = [self.gensim_model.infer_vector(doc) for doc in docs]\n        return np.reshape(np.array(vectors), (len(docs), self.gensim_model.vector_size))\n", "path": "gensim/sklearn_api/d2vmodel.py"}]}