sparknlp.annotator.GraphExtraction

class sparknlp.annotator.GraphExtraction(classname='com.johnsnowlabs.nlp.annotators.GraphExtraction', java_model=None)[source]

Bases: sparknlp.common.AnnotatorModel

Extracts a dependency graph between entities.

The GraphExtraction class takes e.g. extracted entities from a NerDLModel and creates a dependency tree which describes how the entities relate to each other. For that a triple store format is used. Nodes represent the entities and the edges represent the relations between those entities. The graph can then be used to find relevant relationships between words.

Both the DependencyParserModel and TypedDependencyParserModel need to be present in the pipeline. There are two ways to set them:

  1. Both Annotators are present in the pipeline already. The dependencies are taken implicitly from these two Annotators.

  2. Setting setMergeEntities() to True will download the default pretrained models for those two Annotators automatically. The specific models can also be set with setDependencyParserModel() and setTypedDependencyParserModel():

    >>> graph_extraction = GraphExtraction() \
    ...     .setInputCols(["document", "token", "ner"]) \
    ...     .setOutputCol("graph") \
    ...     .setRelationshipTypes(["prefer-LOC"]) \
    ...     .setMergeEntities(True)
    >>>     #.setDependencyParserModel(["dependency_conllu", "en",  "public/models"])
    >>>     #.setTypedDependencyParserModel(["dependency_typed_conllu", "en",  "public/models"])
    

Input Annotation types

Output Annotation type

DOCUMENT, TOKEN, NAMED_ENTITY

NODE

Parameters
relationshipTypes

Paths to find between a pair of token and entity

entityTypes

Paths to find between a pair of entities

explodeEntities

When set to true find paths between entities

rootTokens

Tokens to be consider as root to start traversing the paths. Use it along with explodeEntities

maxSentenceSize

Maximum sentence size that the annotator will process, by default 1000. Above this, the sentence is skipped

minSentenceSize

Minimum sentence size that the annotator will process, by default 2. Below this, the sentence is skipped.

mergeEntities

Merge same neighboring entities as a single token

includeEdges

Whether to include edges when building paths

delimiter

Delimiter symbol used for path output

posModel

Coordinates (name, lang, remoteLoc) to a pretrained POS model

dependencyParserModel

Coordinates (name, lang, remoteLoc) to a pretrained Dependency Parser model

typedDependencyParserModel

Coordinates (name, lang, remoteLoc) to a pretrained Typed Dependency Parser model

Examples

>>> import sparknlp
>>> from sparknlp.base import *
>>> from sparknlp.annotator import *
>>> from pyspark.ml import Pipeline
>>> documentAssembler = DocumentAssembler() \
...     .setInputCol("text") \
...     .setOutputCol("document")
>>> sentence = SentenceDetector() \
...     .setInputCols(["document"]) \
...     .setOutputCol("sentence")
>>> tokenizer = Tokenizer() \
...     .setInputCols(["sentence"]) \
...     .setOutputCol("token")
>>> embeddings = WordEmbeddingsModel.pretrained() \
...     .setInputCols(["sentence", "token"]) \
...     .setOutputCol("embeddings")
>>> nerTagger = NerDLModel.pretrained() \
...     .setInputCols(["sentence", "token", "embeddings"]) \
...     .setOutputCol("ner")
>>> posTagger = PerceptronModel.pretrained() \
...     .setInputCols(["sentence", "token"]) \
...     .setOutputCol("pos")
>>> dependencyParser = DependencyParserModel.pretrained() \
...     .setInputCols(["sentence", "pos", "token"]) \
...     .setOutputCol("dependency")
>>> typedDependencyParser = TypedDependencyParserModel.pretrained() \
...     .setInputCols(["dependency", "pos", "token"]) \
...     .setOutputCol("dependency_type")
>>> graph_extraction = GraphExtraction() \
...     .setInputCols(["document", "token", "ner"]) \
...     .setOutputCol("graph") \
...     .setRelationshipTypes(["prefer-LOC"])
>>> pipeline = Pipeline().setStages([
...     documentAssembler,
...     sentence,
...     tokenizer,
...     embeddings,
...     nerTagger,
...     posTagger,
...     dependencyParser,
...     typedDependencyParser,
...     graph_extraction
... ])
>>> data = spark.createDataFrame([["You and John prefer the morning flight through Denver"]]).toDF("text")
>>> result = pipeline.fit(data).transform(data)
>>> result.select("graph").show(truncate=False)
+-----------------------------------------------------------------------------------------------------------------+
|graph                                                                                                            |
+-----------------------------------------------------------------------------------------------------------------+
|[[node, 13, 18, prefer, [relationship -> prefer,LOC, path1 -> prefer,nsubj,morning,flat,flight,flat,Denver], []]]|
+-----------------------------------------------------------------------------------------------------------------+

Methods

__init__([classname, java_model])

Initialize this instance with a Java model object.

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.

getInputCols()

Gets current column names of input annotations.

getLazyAnnotator()

Gets whether Annotator should be evaluated lazily in a RecursivePipeline.

getOrDefault(param)

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

getOutputCol()

Gets output column name of annotations.

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.

setDelimiter(value)

Sets delimiter symbol used for path output.

setDependencyParserModel(value)

Sets Coordinates (name, lang, remoteLoc) to a pretrained Dependency Parser model.

setEntityTypes(value)

Sets paths to find between a pair of entities.

setExplodeEntities(value)

Sets whether to find paths between entities.

setIncludeEdges(value)

Sets whether to include edges when building paths.

setInputCols(*value)

Sets column names of input annotations.

setLazyAnnotator(value)

Sets whether Annotator should be evaluated lazily in a RecursivePipeline.

setMaxSentenceSize(value)

Sets Maximum sentence size that the annotator will process, by default 1000.

setMergeEntities(value)

Sets whether to merge same neighboring entities as a single token.

setMergeEntitiesIOBFormat(value)

Sets IOB format to apply when merging entities.

setMinSentenceSize(value)

Sets Minimum sentence size that the annotator will process, by default 2.

setOutputCol(value)

Sets output column name of annotations.

setParamValue(paramName)

Sets the value of a parameter.

setParams()

setPosModel(value)

Sets Coordinates (name, lang, remoteLoc) to a pretrained POS model.

setRelationshipTypes(value)

Sets paths to find between a pair of token and entity.

setRootTokens(value)

Sets tokens to be considered as the root to start traversing the paths.

setTypedDependencyParserModel(value)

Sets Coordinates (name, lang, remoteLoc) to a pretrained Typed Dependency Parser model.

transform(dataset[, params])

Transforms the input dataset with optional parameters.

write()

Returns an MLWriter instance for this ML instance.

Attributes

delimiter

dependencyParserModel

entityTypes

explodeEntities

getter_attrs

includeEdges

inputCols

lazyAnnotator

maxSentenceSize

mergeEntities

mergeEntitiesIOBFormat

minSentenceSize

name

outputCol

params

Returns all params ordered by name.

posModel

relationshipTypes

rootTokens

typedDependencyParserModel

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

getInputCols()

Gets current column names of input annotations.

getLazyAnnotator()

Gets whether Annotator should be evaluated lazily in a RecursivePipeline.

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.

getOutputCol()

Gets output column name of annotations.

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.

setDelimiter(value)[source]

Sets delimiter symbol used for path output.

Parameters
valuestr

Delimiter symbol used for path output

setDependencyParserModel(value)[source]

Sets Coordinates (name, lang, remoteLoc) to a pretrained Dependency Parser model.

Parameters
valueList[str]

Coordinates (name, lang, remoteLoc) to a pretrained Dependency Parser model

setEntityTypes(value)[source]

Sets paths to find between a pair of entities.

Parameters
valueList[str]

Paths to find between a pair of entities

setExplodeEntities(value)[source]

Sets whether to find paths between entities.

Parameters
valuebool

Whether to find paths between entities.

setIncludeEdges(value)[source]

Sets whether to include edges when building paths.

Parameters
valuebool

Whether to include edges when building paths

setInputCols(*value)

Sets column names of input annotations.

Parameters
*valuestr

Input columns for the annotator

setLazyAnnotator(value)

Sets whether Annotator should be evaluated lazily in a RecursivePipeline.

Parameters
valuebool

Whether Annotator should be evaluated lazily in a RecursivePipeline

setMaxSentenceSize(value)[source]

Sets Maximum sentence size that the annotator will process, by default 1000.

Above this, the sentence is skipped.

Parameters
valueint

Maximum sentence size that the annotator will process

setMergeEntities(value)[source]

Sets whether to merge same neighboring entities as a single token.

Parameters
valuebool

Whether to merge same neighboring entities as a single token.

setMergeEntitiesIOBFormat(value)[source]

Sets IOB format to apply when merging entities.

Parameters
valuestr

IOB format to apply when merging entities. Values IOB or IOB2

setMinSentenceSize(value)[source]

Sets Minimum sentence size that the annotator will process, by default 2.

Below this, the sentence is skipped.

Parameters
valueint

Minimum sentence size that the annotator will process

setOutputCol(value)

Sets output column name of annotations.

Parameters
valuestr

Name of output column

setParamValue(paramName)

Sets the value of a parameter.

Parameters
paramNamestr

Name of the parameter

setPosModel(value)[source]

Sets Coordinates (name, lang, remoteLoc) to a pretrained POS model.

Parameters
valueList[str]

Coordinates (name, lang, remoteLoc) to a pretrained POS model

setRelationshipTypes(value)[source]

Sets paths to find between a pair of token and entity.

Parameters
valueList[str]

Paths to find between a pair of token and entity

setRootTokens(value)[source]

Sets tokens to be considered as the root to start traversing the paths.

Use it along with explodeEntities.

Parameters
valueList[str]

Sets Tokens to be consider as root to start traversing the paths.

setTypedDependencyParserModel(value)[source]

Sets Coordinates (name, lang, remoteLoc) to a pretrained Typed Dependency Parser model.

Parameters
valueList[str]

Coordinates (name, lang, remoteLoc) to a pretrained Typed Dependency Parser model

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.