spark-nlp 5.0.2__py2.py3-none-any.whl → 5.1.1__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of spark-nlp might be problematic. Click here for more details.

@@ -0,0 +1,225 @@
1
+ # Copyright 2017-2023 John Snow Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains classes for RoBertaForZeroShotClassification."""
15
+
16
+ from sparknlp.common import *
17
+
18
+
19
+ class RoBertaForZeroShotClassification(AnnotatorModel,
20
+ HasCaseSensitiveProperties,
21
+ HasBatchedAnnotate,
22
+ HasClassifierActivationProperties,
23
+ HasCandidateLabelsProperties,
24
+ HasEngine):
25
+ """RoBertaForZeroShotClassification using a `ModelForSequenceClassification` trained on NLI (natural language
26
+ inference) tasks. Equivalent of `RoBertaForSequenceClassification` models, but these models don't require a hardcoded
27
+ number of potential classes, they can be chosen at runtime. It usually means it's slower but it is much more
28
+ flexible.
29
+
30
+ Note that the model will loop through all provided labels. So the more labels you have, the
31
+ longer this process will take.
32
+
33
+ Any combination of sequences and labels can be passed and each combination will be posed as a premise/hypothesis
34
+ pair and passed to the pretrained model.
35
+
36
+ Pretrained models can be loaded with :meth:`.pretrained` of the companion
37
+ object:
38
+
39
+ >>> sequenceClassifier = RoBertaForZeroShotClassification.pretrained() \\
40
+ ... .setInputCols(["token", "document"]) \\
41
+ ... .setOutputCol("label")
42
+
43
+ The default model is ``"roberta_base_zero_shot_classifier_nli"``, if no name is
44
+ provided.
45
+
46
+ For available pretrained models please see the `Models Hub
47
+ <https://sparknlp.orgtask=Text+Classification>`__.
48
+
49
+ To see which models are compatible and how to import them see
50
+ `Import Transformers into Spark NLP 🚀
51
+ <https://github.com/JohnSnowLabs/spark-nlp/discussions/5669>`_.
52
+
53
+ ====================== ======================
54
+ Input Annotation types Output Annotation type
55
+ ====================== ======================
56
+ ``DOCUMENT, TOKEN`` ``CATEGORY``
57
+ ====================== ======================
58
+
59
+ Parameters
60
+ ----------
61
+ batchSize
62
+ Batch size. Large values allows faster processing but requires more
63
+ memory, by default 8
64
+ caseSensitive
65
+ Whether to ignore case in tokens for embeddings matching, by default
66
+ True
67
+ configProtoBytes
68
+ ConfigProto from tensorflow, serialized into byte array.
69
+ maxSentenceLength
70
+ Max sentence length to process, by default 128
71
+ coalesceSentences
72
+ Instead of 1 class per sentence (if inputCols is `sentence`) output 1
73
+ class per document by averaging probabilities in all sentences, by
74
+ default False
75
+ activation
76
+ Whether to calculate logits via Softmax or Sigmoid, by default
77
+ `"softmax"`.
78
+
79
+ Examples
80
+ --------
81
+ >>> import sparknlp
82
+ >>> from sparknlp.base import *
83
+ >>> from sparknlp.annotator import *
84
+ >>> from pyspark.ml import Pipeline
85
+ >>> documentAssembler = DocumentAssembler() \\
86
+ ... .setInputCol("text") \\
87
+ ... .setOutputCol("document")
88
+ >>> tokenizer = Tokenizer() \\
89
+ ... .setInputCols(["document"]) \\
90
+ ... .setOutputCol("token")
91
+ >>> sequenceClassifier = RoBertaForZeroShotClassification.pretrained() \\
92
+ ... .setInputCols(["token", "document"]) \\
93
+ ... .setOutputCol("label") \\
94
+ ... .setCaseSensitive(True)
95
+ >>> pipeline = Pipeline().setStages([
96
+ ... documentAssembler,
97
+ ... tokenizer,
98
+ ... sequenceClassifier
99
+ ... ])
100
+ >>> data = spark.createDataFrame([["I loved this movie when I was a child.", "It was pretty boring."]]).toDF("text")
101
+ >>> result = pipeline.fit(data).transform(data)
102
+ >>> result.select("label.result").show(truncate=False)
103
+ +------+
104
+ |result|
105
+ +------+
106
+ |[pos] |
107
+ |[neg] |
108
+ +------+
109
+ """
110
+ name = "RoBertaForZeroShotClassification"
111
+
112
+ inputAnnotatorTypes = [AnnotatorType.DOCUMENT, AnnotatorType.TOKEN]
113
+
114
+ outputAnnotatorType = AnnotatorType.CATEGORY
115
+
116
+ maxSentenceLength = Param(Params._dummy(),
117
+ "maxSentenceLength",
118
+ "Max sentence length to process",
119
+ typeConverter=TypeConverters.toInt)
120
+
121
+ configProtoBytes = Param(Params._dummy(),
122
+ "configProtoBytes",
123
+ "ConfigProto from tensorflow, serialized into byte array. Get with config_proto.SerializeToString()",
124
+ TypeConverters.toListInt)
125
+
126
+ coalesceSentences = Param(Params._dummy(), "coalesceSentences",
127
+ "Instead of 1 class per sentence (if inputCols is '''sentence''') output 1 class per document by averaging probabilities in all sentences.",
128
+ TypeConverters.toBoolean)
129
+
130
+ def getClasses(self):
131
+ """
132
+ Returns labels used to train this model
133
+ """
134
+ return self._call_java("getClasses")
135
+
136
+ def setConfigProtoBytes(self, b):
137
+ """Sets configProto from tensorflow, serialized into byte array.
138
+
139
+ Parameters
140
+ ----------
141
+ b : List[int]
142
+ ConfigProto from tensorflow, serialized into byte array
143
+ """
144
+ return self._set(configProtoBytes=b)
145
+
146
+ def setMaxSentenceLength(self, value):
147
+ """Sets max sentence length to process, by default 128.
148
+
149
+ Parameters
150
+ ----------
151
+ value : int
152
+ Max sentence length to process
153
+ """
154
+ return self._set(maxSentenceLength=value)
155
+
156
+ def setCoalesceSentences(self, value):
157
+ """Instead of 1 class per sentence (if inputCols is '''sentence''') output 1 class per document by averaging
158
+ probabilities in all sentences. Due to max sequence length limit in almost all transformer models such as RoBerta
159
+ (512 tokens), this parameter helps to feed all the sentences into the model and averaging all the probabilities
160
+ for the entire document instead of probabilities per sentence. (Default: true)
161
+
162
+ Parameters
163
+ ----------
164
+ value : bool
165
+ If the output of all sentences will be averaged to one output
166
+ """
167
+ return self._set(coalesceSentences=value)
168
+
169
+ @keyword_only
170
+ def __init__(self, classname="com.johnsnowlabs.nlp.annotators.classifier.dl.RoBertaForZeroShotClassification",
171
+ java_model=None):
172
+ super(RoBertaForZeroShotClassification, self).__init__(
173
+ classname=classname,
174
+ java_model=java_model
175
+ )
176
+ self._setDefault(
177
+ batchSize=8,
178
+ maxSentenceLength=128,
179
+ caseSensitive=True,
180
+ coalesceSentences=False,
181
+ activation="softmax"
182
+ )
183
+
184
+ @staticmethod
185
+ def loadSavedModel(folder, spark_session):
186
+ """Loads a locally saved model.
187
+
188
+ Parameters
189
+ ----------
190
+ folder : str
191
+ Folder of the saved model
192
+ spark_session : pyspark.sql.SparkSession
193
+ The current SparkSession
194
+
195
+ Returns
196
+ -------
197
+ RoBertaForZeroShotClassification
198
+ The restored model
199
+ """
200
+ from sparknlp.internal import _RoBertaForZeroShotClassification
201
+ jModel = _RoBertaForZeroShotClassification(folder, spark_session._jsparkSession)._java_obj
202
+ return RoBertaForZeroShotClassification(java_model=jModel)
203
+
204
+ @staticmethod
205
+ def pretrained(name="roberta_base_zero_shot_classifier_nli", lang="en", remote_loc=None):
206
+ """Downloads and loads a pretrained model.
207
+
208
+ Parameters
209
+ ----------
210
+ name : str, optional
211
+ Name of the pretrained model, by default
212
+ "roberta_base_zero_shot_classifier_nli"
213
+ lang : str, optional
214
+ Language of the pretrained model, by default "en"
215
+ remote_loc : str, optional
216
+ Optional remote address of the resource, by default None. Will use
217
+ Spark NLPs repositories otherwise.
218
+
219
+ Returns
220
+ -------
221
+ RoBertaForZeroShotClassification
222
+ The restored model
223
+ """
224
+ from sparknlp.pretrained import ResourceDownloader
225
+ return ResourceDownloader.downloadModel(RoBertaForZeroShotClassification, name, lang, remote_loc)
@@ -25,6 +25,7 @@ from sparknlp.annotator.embeddings.elmo_embeddings import *
25
25
  from sparknlp.annotator.embeddings.e5_embeddings import *
26
26
  from sparknlp.annotator.embeddings.instructor_embeddings import *
27
27
  from sparknlp.annotator.embeddings.longformer_embeddings import *
28
+ from sparknlp.annotator.embeddings.mpnet_embeddings import *
28
29
  from sparknlp.annotator.embeddings.roberta_embeddings import *
29
30
  from sparknlp.annotator.embeddings.roberta_sentence_embeddings import *
30
31
  from sparknlp.annotator.embeddings.sentence_embeddings import *
@@ -344,3 +344,9 @@ class Doc2VecModel(AnnotatorModel, HasStorageRef, HasEmbeddingsProperties):
344
344
  from sparknlp.pretrained import ResourceDownloader
345
345
  return ResourceDownloader.downloadModel(Doc2VecModel, name, lang, remote_loc)
346
346
 
347
+ def getVectors(self):
348
+ """
349
+ Returns the vector representation of the words as a dataframe
350
+ with two fields, word and vector.
351
+ """
352
+ return self._call_java("getVectors")
@@ -0,0 +1,190 @@
1
+ # Copyright 2017-2022 John Snow Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains classes for E5Embeddings."""
15
+
16
+ from sparknlp.common import *
17
+
18
+
19
+ class MPNetEmbeddings(AnnotatorModel,
20
+ HasEmbeddingsProperties,
21
+ HasCaseSensitiveProperties,
22
+ HasStorageRef,
23
+ HasBatchedAnnotate,
24
+ HasMaxSentenceLengthLimit):
25
+ """Sentence embeddings using MPNet.
26
+
27
+ MPNet adopts a novel pre-training method, named masked and permuted language modeling,
28
+ to inherit the advantages of masked language modeling and permuted language modeling for
29
+ natural language understanding.
30
+
31
+ Pretrained models can be loaded with :meth:`.pretrained` of the companion
32
+ object:
33
+
34
+ >>> embeddings = MPNetEmbeddings.pretrained() \\
35
+ ... .setInputCols(["document"]) \\
36
+ ... .setOutputCol("mpnet_embeddings")
37
+
38
+
39
+ The default model is ``"all_mpnet_base_v2"``, if no name is provided.
40
+
41
+ For available pretrained models please see the
42
+ `Models Hub <https://sparknlp.org/models?q=MPNet>`__.
43
+
44
+
45
+ ====================== ======================
46
+ Input Annotation types Output Annotation type
47
+ ====================== ======================
48
+ ``DOCUMENT`` ``SENTENCE_EMBEDDINGS``
49
+ ====================== ======================
50
+
51
+ Parameters
52
+ ----------
53
+ batchSize
54
+ Size of every batch , by default 8
55
+ dimension
56
+ Number of embedding dimensions, by default 768
57
+ caseSensitive
58
+ Whether to ignore case in tokens for embeddings matching, by default False
59
+ maxSentenceLength
60
+ Max sentence length to process, by default 512
61
+ configProtoBytes
62
+ ConfigProto from tensorflow, serialized into byte array.
63
+
64
+ References
65
+ ----------
66
+ `MPNet: Masked and Permuted Pre-training for Language Understanding <https://arxiv.org/pdf/2004.09297>`__
67
+
68
+ https://github.com/microsoft/MPNet
69
+
70
+ **Paper abstract**
71
+
72
+ *BERT adopts masked language modeling (MLM) for pre-training and is one of the most successful pre-training models.
73
+ Since BERT neglects dependency among predicted tokens, XLNet introduces permuted language modeling (PLM) for
74
+ pre-training to address this problem. However, XLNet does not leverage the full position information of a sentence
75
+ and thus suffers from position discrepancy between pre-training and fine-tuning. In this paper, we propose MPNet,
76
+ a novel pre-training method that inherits the advantages of BERT and XLNet and avoids their limitations. MPNet
77
+ leverages the dependency among predicted tokens through permuted language modeling (vs. MLM in BERT), and takes
78
+ auxiliary position information as input to make the model see a full sentence and thus reducing the position
79
+ discrepancy (vs. PLM in XLNet). We pre-train MPNet on a large-scale dataset (over 160GB text corpora) and fine-tune
80
+ on a variety of down-streaming tasks (GLUE, SQuAD, etc). Experimental results show that MPNet outperforms MLM and
81
+ PLM by a large margin, and achieves better results on these tasks compared with previous state-of-the-art
82
+ pre-trained methods (e.g., BERT, XLNet, RoBERTa) under the same model setting.*
83
+
84
+ Examples
85
+ --------
86
+ >>> import sparknlp
87
+ >>> from sparknlp.base import *
88
+ >>> from sparknlp.annotator import *
89
+ >>> from pyspark.ml import Pipeline
90
+ >>> documentAssembler = DocumentAssembler() \\
91
+ ... .setInputCol("text") \\
92
+ ... .setOutputCol("document")
93
+ >>> embeddings = MPNetEmbeddings.pretrained() \\
94
+ ... .setInputCols(["document"]) \\
95
+ ... .setOutputCol("mpnet_embeddings")
96
+ >>> embeddingsFinisher = EmbeddingsFinisher() \\
97
+ ... .setInputCols(["mpnet_embeddings"]) \\
98
+ ... .setOutputCols("finished_embeddings") \\
99
+ ... .setOutputAsVector(True)
100
+ >>> pipeline = Pipeline().setStages([
101
+ ... documentAssembler,
102
+ ... embeddings,
103
+ ... embeddingsFinisher
104
+ ... ])
105
+ >>> data = spark.createDataFrame([["This is an example sentence", "Each sentence is converted"]]).toDF("text")
106
+ >>> result = pipeline.fit(data).transform(data)
107
+ >>> result.selectExpr("explode(finished_embeddings) as result").show(5, 80)
108
+ +--------------------------------------------------------------------------------+
109
+ | result|
110
+ +--------------------------------------------------------------------------------+
111
+ |[[0.022502584, -0.078291744, -0.023030775, -0.0051000593, -0.080340415, 0.039...|
112
+ |[[0.041702367, 0.0010974605, -0.015534201, 0.07092203, -0.0017729357, 0.04661...|
113
+ +--------------------------------------------------------------------------------+
114
+ """
115
+
116
+ name = "MPNetEmbeddings"
117
+
118
+ inputAnnotatorTypes = [AnnotatorType.DOCUMENT]
119
+
120
+ outputAnnotatorType = AnnotatorType.SENTENCE_EMBEDDINGS
121
+ configProtoBytes = Param(Params._dummy(),
122
+ "configProtoBytes",
123
+ "ConfigProto from tensorflow, serialized into byte array. Get with config_proto.SerializeToString()",
124
+ TypeConverters.toListInt)
125
+
126
+
127
+ def setConfigProtoBytes(self, b):
128
+ """Sets configProto from tensorflow, serialized into byte array.
129
+
130
+ Parameters
131
+ ----------
132
+ b : List[int]
133
+ ConfigProto from tensorflow, serialized into byte array
134
+ """
135
+ return self._set(configProtoBytes=b)
136
+
137
+ @keyword_only
138
+ def __init__(self, classname="com.johnsnowlabs.nlp.embeddings.MPNetEmbeddings", java_model=None):
139
+ super(MPNetEmbeddings, self).__init__(
140
+ classname=classname,
141
+ java_model=java_model
142
+ )
143
+ self._setDefault(
144
+ dimension=768,
145
+ batchSize=8,
146
+ maxSentenceLength=512,
147
+ caseSensitive=False,
148
+ )
149
+
150
+ @staticmethod
151
+ def loadSavedModel(folder, spark_session):
152
+ """Loads a locally saved model.
153
+
154
+ Parameters
155
+ ----------
156
+ folder : str
157
+ Folder of the saved model
158
+ spark_session : pyspark.sql.SparkSession
159
+ The current SparkSession
160
+
161
+ Returns
162
+ -------
163
+ MPNetEmbeddings
164
+ The restored model
165
+ """
166
+ from sparknlp.internal import _MPNetLoader
167
+ jModel = _MPNetLoader(folder, spark_session._jsparkSession)._java_obj
168
+ return MPNetEmbeddings(java_model=jModel)
169
+
170
+ @staticmethod
171
+ def pretrained(name="all_mpnet_base_v2", lang="en", remote_loc=None):
172
+ """Downloads and loads a pretrained model.
173
+
174
+ Parameters
175
+ ----------
176
+ name : str, optional
177
+ Name of the pretrained model, by default "all_mpnet_base_v2"
178
+ lang : str, optional
179
+ Language of the pretrained model, by default "en"
180
+ remote_loc : str, optional
181
+ Optional remote address of the resource, by default None. Will use
182
+ Spark NLPs repositories otherwise.
183
+
184
+ Returns
185
+ -------
186
+ MPNetEmbeddings
187
+ The restored model
188
+ """
189
+ from sparknlp.pretrained import ResourceDownloader
190
+ return ResourceDownloader.downloadModel(MPNetEmbeddings, name, lang, remote_loc)
@@ -345,3 +345,9 @@ class Word2VecModel(AnnotatorModel, HasStorageRef, HasEmbeddingsProperties):
345
345
  from sparknlp.pretrained import ResourceDownloader
346
346
  return ResourceDownloader.downloadModel(Word2VecModel, name, lang, remote_loc)
347
347
 
348
+ def getVectors(self):
349
+ """
350
+ Returns the vector representation of the words as a dataframe
351
+ with two fields, word and vector.
352
+ """
353
+ return self._call_java("getVectors")
@@ -0,0 +1,16 @@
1
+ # Copyright 2017-2023 John Snow Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module of annotators for openai integration."""
15
+ from sparknlp.annotator.openai.openai_completion import *
16
+ from sparknlp.annotator.openai.openai_embeddings import *