TechDivers/seqeval
0
1# Copyright 2020 The HuggingFace Evaluate Authors.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 at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# 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 and13# limitations under the License.14""" seqeval metric. """15 16import importlib17from typing import List, Optional, Union18 19import datasets20from seqeval.metrics import accuracy_score, classification_report21 22import evaluate23 24 25_CITATION = """\26@inproceedings{ramshaw-marcus-1995-text,27 title = "Text Chunking using Transformation-Based Learning",28 author = "Ramshaw, Lance and29 Marcus, Mitch",30 booktitle = "Third Workshop on Very Large Corpora",31 year = "1995",32 url = "https://www.aclweb.org/anthology/W95-0107",33}34@misc{seqeval,35 title={{seqeval}: A Python framework for sequence labeling evaluation},36 url={https://github.com/chakki-works/seqeval},37 note={Software available from https://github.com/chakki-works/seqeval},38 author={Hiroki Nakayama},39 year={2018},40}41"""42 43_DESCRIPTION = """\44seqeval is a Python framework for sequence labeling evaluation.45seqeval can evaluate the performance of chunking tasks such as named-entity recognition, part-of-speech tagging, semantic role labeling and so on.46This is well-tested by using the Perl script conlleval, which can be used for47measuring the performance of a system that has processed the CoNLL-2000 shared task data.48seqeval supports following formats:49IOB150IOB251IOE152IOE253IOBES54See the [README.md] file at https://github.com/chakki-works/seqeval for more information.55"""56 57_KWARGS_DESCRIPTION = """58Produces labelling scores along with its sufficient statistics59from a source against one or more references.60Args:61 predictions: List of List of predicted labels (Estimated targets as returned by a tagger)62 references: List of List of reference labels (Ground truth (correct) target values)63 suffix: True if the IOB prefix is after type, False otherwise. default: False64 scheme: Specify target tagging scheme. Should be one of ["IOB1", "IOB2", "IOE1", "IOE2", "IOBES", "BILOU"].65 default: None66 mode: Whether to count correct entity labels with incorrect I/B tags as true positives or not.67 If you want to only count exact matches, pass mode="strict". default: None.68 sample_weight: Array-like of shape (n_samples,), weights for individual samples. default: None69 zero_division: Which value to substitute as a metric value when encountering zero division. Should be on of 0, 1,70 "warn". "warn" acts as 0, but the warning is raised.71Returns:72 'scores': dict. Summary of the scores for overall and per type73 Overall:74 'accuracy': accuracy,75 'precision': precision,76 'recall': recall,77 'f1': F1 score, also known as balanced F-score or F-measure,78 Per type:79 'precision': precision,80 'recall': recall,81 'f1': F1 score, also known as balanced F-score or F-measure82Examples:83 >>> predictions = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]84 >>> references = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]85 >>> seqeval = evaluate.load("seqeval")86 >>> results = seqeval.compute(predictions=predictions, references=references)87 >>> print(list(results.keys()))88 ['MISC', 'PER', 'overall_precision', 'overall_recall', 'overall_f1', 'overall_accuracy']89 >>> print(results["overall_f1"])90 0.591 >>> print(results["PER"]["f1"])92 1.093"""94 95 96@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)97class Seqeval(evaluate.Metric):98 def _info(self):99 return evaluate.MetricInfo(100 description=_DESCRIPTION,101 citation=_CITATION,102 homepage="https://github.com/chakki-works/seqeval",103 inputs_description=_KWARGS_DESCRIPTION,104 features=datasets.Features(105 {106 "predictions": datasets.Sequence(datasets.Value("string", id="label"), id="sequence"),107 "references": datasets.Sequence(datasets.Value("string", id="label"), id="sequence"),108 }109 ),110 codebase_urls=["https://github.com/chakki-works/seqeval"],111 reference_urls=["https://github.com/chakki-works/seqeval"],112 )113 114 def _compute(115 self,116 predictions,117 references,118 suffix: bool = False,119 scheme: Optional[str] = None,120 mode: Optional[str] = None,121 sample_weight: Optional[List[int]] = None,122 zero_division: Union[str, int] = "warn",123 ):124 if scheme is not None:125 try:126 scheme_module = importlib.import_module("seqeval.scheme")127 scheme = getattr(scheme_module, scheme)128 except AttributeError:129 raise ValueError(f"Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {scheme}")130 report = classification_report(131 y_true=references,132 y_pred=predictions,133 suffix=suffix,134 output_dict=True,135 scheme=scheme,136 mode=mode,137 sample_weight=sample_weight,138 zero_division=zero_division,139 )140 report.pop("macro avg")141 report.pop("weighted avg")142 overall_score = report.pop("micro avg")143 144 scores = {145 type_name: {146 "precision": score["precision"],147 "recall": score["recall"],148 "f1": score["f1-score"],149 "number": score["support"],150 }151 for type_name, score in report.items()152 }153 scores["overall_precision"] = overall_score["precision"]154 scores["overall_recall"] = overall_score["recall"]155 scores["overall_f1"] = overall_score["f1-score"]156 scores["overall_accuracy"] = accuracy_score(y_true=references, y_pred=predictions)157 158 return scores159 