sparknlp_jsl.annotator.re.relation_extraction_dl#

Module Contents#

Classes#

RelationExtractionDLModel

Extracts and classifies instances of relations between named entities.

class RelationExtractionDLModel(classname='com.johnsnowlabs.nlp.annotators.re.RelationExtractionDLModel', java_model=None)#

Bases: sparknlp_jsl.common.AnnotatorModelInternal, sparknlp_jsl.annotator.handle_exception_params.HandleExceptionParams

Extracts and classifies instances of relations between named entities.

In contrast with RelationExtractionModel, RelationExtractionDLModel is based on BERT. For pretrained models please see the NLP Models Hub.

Input Annotation types

Output Annotation type

CHUNK, DOCUMENT

CATEGORY

Parameters:
  • predictionThreshold – Minimal activation of the target unit to encode a new relation instance. Default is 0.5.

  • batchSize – Number of relations to process at once. Default is 10.

  • customLabels – List of custom labels to use.

Examples

>>> import sparknlp
>>> from sparknlp.base import *
>>> from sparknlp_jsl.common import *
>>> from sparknlp.annotator import *
>>> from sparknlp.training import *
>>> import sparknlp_jsl
>>> from sparknlp_jsl.base import *
>>> from sparknlp_jsl.annotator import *
>>> from pyspark.ml import Pipeline
>>> documentAssembler = DocumentAssembler() \
...   .setInputCol("text") \
...   .setOutputCol("document")
...
>>> tokenizer = Tokenizer() \
...   .setInputCols(["document"]) \
...   .setOutputCol("tokens")
...
>>> embedder = WordEmbeddingsModel \
...   .pretrained("embeddings_clinical", "en", "clinical/models") \
...   .setInputCols(["document", "tokens"]) \
...   .setOutputCol("embeddings")
...
>>> posTagger = PerceptronModel \
...   .pretrained("pos_clinical", "en", "clinical/models") \
...   .setInputCols(["document", "tokens"]) \
...   .setOutputCol("posTags")
...
>>> nerTagger = MedicalNerModel \
...   .pretrained("ner_events_clinical", "en", "clinical/models") \
...   .setInputCols(["document", "tokens", "embeddings"]) \
...   .setOutputCol("ner_tags")
...
>>> nerConverter = NerConverter() \
...   .setInputCols(["document", "tokens", "ner_tags"]) \
...   .setOutputCol("nerChunks")
...
>>> depencyParser = DependencyParserModel \
...   .pretrained("dependency_conllu", "en") \
...   .setInputCols(["document", "posTags", "tokens"]) \
...   .setOutputCol("dependencies")
...
>>> relationPairs = [
...   "direction-external_body_part_or_region",
...   "external_body_part_or_region-direction",
...   "direction-internal_organ_or_component",
...   "internal_organ_or_component-direction"
... ]
>>> re_ner_chunk_filter = RENerChunksFilter()\
...   .setInputCols(["ner_chunks", "dependencies"])\
...   .setOutputCol("re_ner_chunks")\
...   .setMaxSyntacticDistance(4)\
...   .setRelationPairs(["internal_organ_or_component-direction"])
...
>>> re_model = RelationExtractionDLModel.pretrained("redl_bodypart_direction_biobert", "en", "clinical/models") \
...     .setInputCols(["re_ner_chunks", "sentences"]) \
...     .setOutputCol("relations") \
...     .setPredictionThreshold(0.5)
...
>>> pipeline = Pipeline(stages=[
...     documentAssembler,
...     tokenizer,
...     embedder,
...     posTagger,
...     nerTagger,
...     nerConverter,
...     depencyParser,
...     re_ner_chunk_filter ,
...     re_model])
>>> model = pipeline.fit(trainData)
>>> data = spark.createDataFrame([["MRI demonstrated infarction in the upper brain stem , left cerebellum and  right basil ganglia"]]).toDF("text")
>>> result = pipeline.fit(data).transform(data)
...
>>> result.selectExpr("explode(relations) as relations")\
...  .select(
...    "relations.metadata.chunk1",
...    "relations.metadata.entity1",
...    "relations.metadata.chunk2",
...    "relations.metadata.entity2",
...    "relations.result"
...  )\
...  .where("result != 0")\
...  .show(truncate=False)
...
... # Show results
... result.selectExpr("explode(relations) as relations") \
...   .select(
...      "relations.metadata.chunk1",
...      "relations.metadata.entity1",
...      "relations.metadata.chunk2",
...      "relations.metadata.entity2",
...      "relations.result"
...   ).where("result != 0") \
...   .show(truncate=False)
+------+---------+-------------+---------------------------+------+
|chunk1|entity1  |chunk2       |entity2                    |result|
+------+---------+-------------+---------------------------+------+
|upper |Direction|brain stem   |Internal_organ_or_component|1     |
|left  |Direction|cerebellum   |Internal_organ_or_component|1     |
|right |Direction|basil ganglia|Internal_organ_or_component|1     |
+------+---------+-------------+---------------------------+------+
batchSize#
classes#
customLabels#
doExceptionHandling#
getter_attrs = []#
inputAnnotatorTypes#
inputCols#
lazyAnnotator#
name = RelationExtractionDLModel#
optionalInputAnnotatorTypes = []#
outputAnnotatorType#
outputCol#
predictionThreshold#
relationPairsCaseSensitive#
skipLPInputColsValidation = True#
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 (dict, optional) – Extra parameters to copy to the new instance

Returns:

Copy of this instance

Return type:

JavaParams

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 (dict, optional) – extra param values

Returns:

merged param map

Return type:

dict

getClasses()#

Returns labels used during training.

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:

paramName (str) – Name of the parameter

getRelationTypePerPair()#

Return the list of entity pairs allowed for a given relation

hasDefault(param)#

Checks whether a param has a default value.

hasParam(paramName)#

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

inputColsValidation(value)#
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).

static loadSavedModel(folder, spark_session)#

Load a pre-trained RelationExtractionDLModel.

Parameters:
  • folder (str) – Folder containing the pre-trained model.

  • spark_session (SparkSession) – SparkSession.

Returns:

The pre-trained RelationExtractionDLModel.

Return type:

RelationExtractionDLModel

static pretrained(name='redl_ade_biobert', lang='en', remote_loc='clinical/models')#

Download a pre-trained RelationExtractionDLModel.

Parameters:
  • name (str) – Name of the pre-trained model, by default “redl_ade_biobert”

  • lang (str) – Language of the pre-trained model, by default “en”

  • remote_loc (str) – Remote location of the pre-trained model. If None, use the open-source location. Other values are “clinical/models”, “finance/models”, or “legal/models”.

Returns:

A pre-trained RelationExtractionDLModel.

Return type:

RelationExtractionDLModel

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.

setBatchSize(value: int)#

Sets number of relations to process at once

Parameters:

value (int) – Number of relations to process at once

setCaseSensitive(value: bool)#

Sets case sensitivity.

Parameters:

value (bool) – True if case sensitive, False otherwise

setCustomLabels(labels: dict)#

Sets custom relation labels

Parameters:

labels (dict[str, str]) – Dictionary which maps old to new labels

setDoExceptionHandling(value: bool)#

If True, exceptions are handled. If exception causing data is passed to the model, a error annotation is emitted which has the exception message. Processing continues with the next one. This comes with a performance penalty.

Parameters:

value (bool) – If True, exceptions are handled.

setForceInputTypeValidation(etfm)#
setInputCols(*value)#

Sets column names of input annotations.

Parameters:

*value (List[str]) – Input columns for the annotator

setLazyAnnotator(value)#

Sets whether Annotator should be evaluated lazily in a RecursivePipeline.

Parameters:

value (bool) – Whether Annotator should be evaluated lazily in a RecursivePipeline

setOutputCol(value)#

Sets output column name of annotations.

Parameters:

value (str) – Name of output column

setParamValue(paramName)#

Sets the value of a parameter.

Parameters:

paramName (str) – Name of the parameter

setParams()#
setPredictionThreshold(threshold: float)#

Sets minimal activation of the target unit to encode a new relation instance. Default is 0.5.

Parameters:

threshold (float) – Minimal activation of the target unit to encode a new relation instance. Default is 0.5.

setRelationPairsCaseSensitive(value: bool)#

Sets the case sensitivity of relation pairs :param value: whether relation pairs are case sensitive :type value: bool

setRelationTypePerPair(relationTypePairs)#

Set the list of entity pairs allowed for a given relation

Parameters:

relationTypePairs (dict[str, list[str]]) –

transform(dataset, params=None)#

Transforms the input dataset with optional parameters.

New in version 1.3.0.

Parameters:
  • dataset (pyspark.sql.DataFrame) – input dataset

  • params (dict, optional) – an optional param map that overrides embedded params.

Returns:

transformed dataset

Return type:

pyspark.sql.DataFrame

write()#

Returns an MLWriter instance for this ML instance.