sparknlp.base.EmbeddingsFinisher

class sparknlp.base.EmbeddingsFinisher[source]

Bases: sparknlp.internal.AnnotatorTransformer

Extracts embeddings from Annotations into a more easily usable form.

This is useful for example:

  • WordEmbeddings,

  • Transformer based embeddings such as BertEmbeddings,

  • SentenceEmbeddings and

  • ChunkEmbeddings, etc.

By using EmbeddingsFinisher you can easily transform your embeddings into array of floats or vectors which are compatible with Spark ML functions such as LDA, K-mean, Random Forest classifier or any other functions that require a featureCol.

For more extended examples see the Spark NLP Workshop.

Input Annotation types

Output Annotation type

EMBEDDINGS

NONE

Parameters
inputCols

Names of input annotation columns containing embeddings

outputCols

Names of finished output columns

cleanAnnotations

Whether to remove all the existing annotation columns, by default False

outputAsVector

Whether to output the embeddings as Vectors instead of arrays, by default False

Examples

First extract embeddings.

>>> import sparknlp
>>> from sparknlp.base import *
>>> from sparknlp.annotator import *
>>> from pyspark.ml import Pipeline
>>> documentAssembler = DocumentAssembler() \
...    .setInputCol("text") \
...    .setOutputCol("document")
>>> tokenizer = Tokenizer() \
...    .setInputCols("document") \
...    .setOutputCol("token")
>>> normalizer = Normalizer() \
...    .setInputCols("token") \
...    .setOutputCol("normalized")
>>> stopwordsCleaner = StopWordsCleaner() \
...    .setInputCols("normalized") \
...    .setOutputCol("cleanTokens") \
...    .setCaseSensitive(False)
>>> gloveEmbeddings = WordEmbeddingsModel.pretrained() \
...    .setInputCols("document", "cleanTokens") \
...    .setOutputCol("embeddings") \
...    .setCaseSensitive(False)
>>> embeddingsFinisher = EmbeddingsFinisher() \
...    .setInputCols("embeddings") \
...    .setOutputCols("finished_sentence_embeddings") \
...    .setOutputAsVector(True) \
...    .setCleanAnnotations(False)
>>> data = spark.createDataFrame([["Spark NLP is an open-source text processing library."]]) \
...    .toDF("text")
>>> pipeline = Pipeline().setStages([
...    documentAssembler,
...    tokenizer,
...    normalizer,
...    stopwordsCleaner,
...    gloveEmbeddings,
...    embeddingsFinisher
... ]).fit(data)
>>> result = pipeline.transform(data)

Show results.

>>> resultWithSize = result.selectExpr("explode(finished_sentence_embeddings) as embeddings")
>>> resultWithSize.show(5, 80)
+--------------------------------------------------------------------------------+
|                                                                      embeddings|
+--------------------------------------------------------------------------------+
|[0.1619900017976761,0.045552998781204224,-0.03229299932718277,-0.685609996318...|
|[-0.42416998744010925,1.1378999948501587,-0.5717899799346924,-0.5078899860382...|
|[0.08621499687433243,-0.15772999823093414,-0.06067200005054474,0.395359992980...|
|[-0.4970499873161316,0.7164199948310852,0.40119001269340515,-0.05761000141501...|
|[-0.08170200139284134,0.7159299850463867,-0.20677000284194946,0.0295659992843...|
+--------------------------------------------------------------------------------+

Methods

__init__()

clear(param)

Clears a param from the param map if it has been explicitly set.

copy([extra])

Creates a copy of this instance with the same uid and some extra params.

explainParam(param)

Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.

explainParams()

Returns the documentation of all params with their optionally default values and user-supplied values.

extractParamMap([extra])

Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default param values < user-supplied values < extra.

getOrDefault(param)

Gets the value of a param in the user-supplied param map or its default value.

getParam(paramName)

Gets a param by its name.

getParamValue(paramName)

Gets the value of a parameter.

hasDefault(param)

Checks whether a param has a default value.

hasParam(paramName)

Tests whether this instance contains a param with a given (string) name.

isDefined(param)

Checks whether a param is explicitly set by user or has a default value.

isSet(param)

Checks whether a param is explicitly set by user.

load(path)

Reads an ML instance from the input path, a shortcut of read().load(path).

read()

Returns an MLReader instance for this class.

save(path)

Save this ML instance to the given path, a shortcut of 'write().save(path)'.

set(param, value)

Sets a parameter in the embedded param map.

setCleanAnnotations(value)

Sets whether to remove all the existing annotation columns, by default False.

setInputCols(*value)

Sets name of input annotation columns containing embeddings.

setOutputAsVector(value)

Sets whether to output the embeddings as Vectors instead of arrays, by default False.

setOutputCols(*value)

Sets names of finished output columns.

setParamValue(paramName)

Sets the value of a parameter.

setParams()

transform(dataset[, params])

Transforms the input dataset with optional parameters.

write()

Returns an MLWriter instance for this ML instance.

Attributes

cleanAnnotations

getter_attrs

inputCols

name

outputAsVector

outputCols

params

Returns all params ordered by name.

clear(param)

Clears a param from the param map if it has been explicitly set.

copy(extra=None)

Creates a copy of this instance with the same uid and some extra params. This implementation first calls Params.copy and then make a copy of the companion Java pipeline component with extra params. So both the Python wrapper and the Java pipeline component get copied.

Parameters

extra – Extra parameters to copy to the new instance

Returns

Copy of this instance

explainParam(param)

Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.

explainParams()

Returns the documentation of all params with their optionally default values and user-supplied values.

extractParamMap(extra=None)

Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default param values < user-supplied values < extra.

Parameters

extra – extra param values

Returns

merged param map

getOrDefault(param)

Gets the value of a param in the user-supplied param map or its default value. Raises an error if neither is set.

getParam(paramName)

Gets a param by its name.

getParamValue(paramName)

Gets the value of a parameter.

Parameters
paramNamestr

Name of the parameter

hasDefault(param)

Checks whether a param has a default value.

hasParam(paramName)

Tests whether this instance contains a param with a given (string) name.

isDefined(param)

Checks whether a param is explicitly set by user or has a default value.

isSet(param)

Checks whether a param is explicitly set by user.

classmethod load(path)

Reads an ML instance from the input path, a shortcut of read().load(path).

property params

Returns all params ordered by name. The default implementation uses dir() to get all attributes of type Param.

classmethod read()

Returns an MLReader instance for this class.

save(path)

Save this ML instance to the given path, a shortcut of ‘write().save(path)’.

set(param, value)

Sets a parameter in the embedded param map.

setCleanAnnotations(value)[source]

Sets whether to remove all the existing annotation columns, by default False.

Parameters
valuebool

Whether to remove all the existing annotation columns

setInputCols(*value)[source]

Sets name of input annotation columns containing embeddings.

Parameters
*valuestr

Input columns for the annotator

setOutputAsVector(value)[source]

Sets whether to output the embeddings as Vectors instead of arrays, by default False.

Parameters
valuebool

Whether to output the embeddings as Vectors instead of arrays

setOutputCols(*value)[source]

Sets names of finished output columns.

Parameters
*valueList[str]

Input columns for the annotator

setParamValue(paramName)

Sets the value of a parameter.

Parameters
paramNamestr

Name of the parameter

transform(dataset, params=None)

Transforms the input dataset with optional parameters.

Parameters
  • dataset – input dataset, which is an instance of pyspark.sql.DataFrame

  • params – an optional param map that overrides embedded params.

Returns

transformed dataset

New in version 1.3.0.

uid

A unique id for the object.

write()

Returns an MLWriter instance for this ML instance.