sparknlp_jsl.annotator.re.zero_shot_relation_extraction
#
Module Contents#
Classes#
ZeroShotRelationExtractionModel implements zero shot binary relations extraction by utilizing BERT transformer |
- class ZeroShotRelationExtractionModel(classname='com.johnsnowlabs.nlp.annotators.re.ZeroShotRelationExtractionModel', java_model=None)#
Bases:
sparknlp_jsl.annotator.classification.medical_bert_for_sequence_classification.MedicalBertForSequenceClassification
,sparknlp_jsl.common.HasEngine
ZeroShotRelationExtractionModel implements zero shot binary relations extraction by utilizing BERT transformer models trained on the NLI (Natural Language Inference) task. The model inputs consists of documents/sentences and paired NER chunks, usually obtained by RENerChunksFilter. The definitions of relations which are extracted is given by a dictionary structures, specifying a set of statements regarding the relationship of named entities. These statements are automatically appended to each document in the dataset and the NLI model is used to determine whether a particular relationship between entities.
Input Annotation types
Output Annotation type
CHUNK, DOCUMENT
CATEGORY
- Parameters:
relationalCategories –
A dictionary with definitions of relational categories. The keys of dictionary are the relation labels and the values are lists of hypothesis templates. For example:
>>> {"CURE": [ >>> "{TREATMENT, DRUG} cures {PROBLEM}." >>> ], >>> "IMPROVE": [ >>> "{TREATMENT} improves {PROBLEM}.", >>> "{TREATMENT} cures {PROBLEM}." >>> ]}
predictionThreshold – Minimal confidence score to encode a relation (Default: 0.5f)
multiLabel – Whether or not a pair of entities can be categorized by multiple relations (Default: False)
Examples
>>> documentAssembler = DocumentAssembler() >>> documenter = sparknlp.DocumentAssembler() ... .setInputCol("text") ... .setOutputCol("document") >>> tokenizer = sparknlp.annotators.Tokenizer() ... .setInputCols(["document"]) ... .setOutputCol("tokens") >>> sentencer = sparknlp.annotators.SentenceDetector() ... .setInputCols(["document"]) ... .setOutputCol("sentences") >>> words_embedder = sparknlp.annotators.WordEmbeddingsModel() ... .pretrained("embeddings_clinical", "en", "clinical/models") ... .setInputCols(["sentences", "tokens"]) ... .setOutputCol("embeddings") >>> pos_tagger = sparknlp.annotators.PerceptronModel() ... .pretrained("pos_clinical", "en", "clinical/models") ... .setInputCols(["sentences", "tokens"]) ... .setOutputCol("pos_tags") >>> ner_tagger = MedicalNerModel() ... .pretrained("ner_clinical", "en", "clinical/models") ... .setInputCols(["sentences", "tokens", "embeddings"]) ... .setOutputCol("ner_tags") >>> ner_converter = sparknlp.annotators.NerConverter() ... .setInputCols(["sentences", "tokens", "ner_tags"]) ... .setOutputCol("ner_chunks") >>> dependency_parser = sparknlp.annotators.DependencyParserModel() ... .pretrained("dependency_conllu", "en") ... .setInputCols(["document", "pos_tags", "tokens"]) ... .setOutputCol("dependencies") >>> re_ner_chunk_filter = RENerChunksFilter() ... .setRelationPairs(["problem-test","problem-treatment"]) ... .setMaxSyntacticDistance(4) ... .setDocLevelRelations(False) ... .setInputCols(["ner_chunks", "dependencies"]) ... .setOutputCol("re_ner_chunks") >>> re_model = ZeroShotRelationExtractionModel ... .load("/tmp/spark_sbert_zero_shot") ... .setRelationalCategories({ ... "CURE": ["{TREATMENT} cures {PROBLEM}."], ... "IMPROVE": ["{TREATMENT} improves {PROBLEM}.", "{TREATMENT} cures {PROBLEM}."], ... "REVEAL": ["{TEST} reveals {PROBLEM}."]}) ... .setMultiLabel(False) ... .setInputCols(["re_ner_chunks", "sentences"]) ... .setOutputCol("relations") >>> data = spark.createDataFrame( ... [["Paracetamol can alleviate headache or sickness. An MRI test can be used to find cancer."]] ... ).toDF("text") >>> results = sparknlp.base.Pipeline() ... .setStages([documenter, tokenizer, sentencer, words_embedder, pos_tagger, ner_tagger, ner_converter, ... dependency_parser, re_ner_chunk_filter, re_model]) ... .fit(data) ... .transform(data) >>> results ... .selectExpr("explode(relations) as relation") ... .selectExpr("relation.result", "relation.metadata.confidence") ... .show(truncate=False) +-------+----------+ |result |confidence| +-------+----------+ |REVEAL |0.9760039 | |IMPROVE|0.98819494| |IMPROVE|0.9929625 | +-------+----------+
- caseSensitive#
- coalesceSentences#
- configProtoBytes#
- getter_attrs = []#
- inputAnnotatorTypes#
- inputCols#
- lazyAnnotator#
- maxSentenceLength#
- multiLabel#
- name = 'MedicalBertForSequenceClassification'#
- negativeRelationships#
- optionalInputAnnotatorTypes = []#
- outputAnnotatorType = 'category'#
- outputCol#
- predictionThreshold#
- skipLPInputColsValidation = True#
- uid = ''#
- clear(param: pyspark.ml.param.Param) None #
Clears a param from the param map if it has been explicitly set.
- copy(extra: pyspark.ml._typing.ParamMap | None = None) JP #
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: str | Param) str #
Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.
- explainParams() str #
Returns the documentation of all params with their optionally default values and user-supplied values.
- extractParamMap(extra: pyspark.ml._typing.ParamMap | None = None) pyspark.ml._typing.ParamMap #
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
- getCaseSensitive()#
Gets whether to ignore case in tokens for embeddings matching.
- Returns:
Whether to ignore case in tokens for embeddings matching
- Return type:
bool
- getClasses()#
Returns the list of entities which are recognized
- getInputCols()#
Gets current column names of input annotations.
- getLazyAnnotator()#
Gets whether Annotator should be evaluated lazily in a RecursivePipeline.
- getOrDefault(param: str) Any #
- getOrDefault(param: Param[T]) T
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: str) Param #
Gets a param by its name.
- getParamValue(paramName)#
Gets the value of a parameter.
- Parameters:
paramName (str) – Name of the parameter
- hasDefault(param: str | Param[Any]) bool #
Checks whether a param has a default value.
- hasParam(paramName: str) bool #
Tests whether this instance contains a param with a given (string) name.
- inputColsValidation(value)#
- isDefined(param: str | Param[Any]) bool #
Checks whether a param is explicitly set by user or has a default value.
- isSet(param: str | Param[Any]) bool #
Checks whether a param is explicitly set by user.
- classmethod load(path: str) RL #
Reads an ML instance from the input path, a shortcut of read().load(path).
- static loadSavedModel(folder, spark_session)#
Loads a locally saved model.
- Parameters:
folder (str) – Folder of the saved model
spark_session (pyspark.sql.SparkSession) – The current SparkSession
- Returns:
The restored model
- Return type:
- static loadSavedModelOpenSource(bertForTokenClassifierPath, tfModelPath, spark_session)#
Loads a locally saved model.
- Parameters:
bertForTokenClassifierPath (str) – Folder of the bertForTokenClassifier
tfModelPath (str) – Folder taht contains the tf model
spark_session (pyspark.sql.SparkSession) – The current SparkSession
- Returns:
The restored model
- Return type:
- static pretrained(name='zero_shot_re', lang='en', remote_loc='clinical/models')#
Download a pre-trained ZeroShotRelationExtractionModel.
- Parameters:
name (str) – Name of the pre-trained model.
lang (str) – Language of the pre-trained model.
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 ZeroShotRelationExtractionModel.
- Return type:
- classmethod read()#
Returns an MLReader instance for this class.
- save(path: str) None #
Save this ML instance to the given path, a shortcut of ‘write().save(path)’.
- set(param: Param, value: Any) None #
Sets a parameter in the embedded param map.
- setCaseSensitive(value)#
Sets whether to ignore case in tokens for embeddings matching.
- Parameters:
value (bool) – Whether to ignore case in tokens for embeddings matching
- setCoalesceSentences(value)#
Instead of 1 class per sentence (if inputCols is ‘’’sentence’’’) output 1 class per document by averaging probabilities in all sentences. Due to max sequence length limit in almost all transformer models such as BERT (512 tokens), this parameter helps feeding all the sentences into the model and averaging all the probabilities for the entire document instead of probabilities per sentence. (Default: False)
- Parameters:
value (bool) – If the output of all sentences will be averaged to one output
- setConfigProtoBytes(b)#
Sets configProto from tensorflow, serialized into byte array.
- Parameters:
b (List[str]) – ConfigProto from tensorflow, serialized into byte array
- 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
- setMaxSentenceLength(value)#
Sets max sentence length to process, by default 128.
- Parameters:
value (int) – Max sentence length to process
- setNegativeRelationships(relations: list)#
Set the list of relational categories which serve as negative examples and are not included in the output annotations
- Parameters:
relations (List[str]) –
- 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()#
- setRelationalCategories(categories)#
Set definitions of relational categories
- Parameters:
categories (dict[str, list[str]]) –
- transform(dataset: pyspark.sql.dataframe.DataFrame, params: pyspark.ml._typing.ParamMap | None = None) pyspark.sql.dataframe.DataFrame #
Transforms the input dataset with optional parameters.
New in version 1.3.0.
- Parameters:
dataset (
pyspark.sql.DataFrame
) – input datasetparams (dict, optional) – an optional param map that overrides embedded params.
- Returns:
transformed dataset
- Return type:
- write() JavaMLWriter #
Returns an MLWriter instance for this ML instance.