Spaces:
Runtime error
Runtime error
implement specificity
Browse filesFiles changed (3)
- README.md+75-18
- specificity.py+91-52
- tests.py+3-13
12345678910112 unmodified lines14151617181920212223242526272829303132333435363738394041424344454647484950---title: Specificitydatasets:-tags:- evaluate- metricdescription: "TODO: add a description here"sdk: gradiosdk_version: 3.19.1app_file: app.py2 unmodified lines# Metric Card for Specificity***Module Card Instructions:*** *Fill out the following subsections. Feel free to take a look at existing metric cards if you'd like examples.*## Metric Description*Give a brief overview of this metric, including what task(s) it is usually used for, if any.*## How to Use*Give general statement of how to use the metric**Provide simplest possible example for using the metric*### Inputs*List all input arguments in the format below*- **input_field** *(type): Definition of input, with explanation if necessary. State any default value(s).*### Output Values*Explain what this metric outputs and provide an example of what the metric output looks like. Modules should return a dictionary with one or multiple key-value pairs, e.g. {"bleu" : 6.02}**State the range of possible values that the metric's output can take, as well as what in that range is considered good. For example: "This metric can take on any value between 0 and 100, inclusive. Higher scores are better."*#### Values from Popular Papers*Give examples, preferrably with links to leaderboards or publications, to papers that have reported this metric, along with the values they have reported.*### Examples*Give code examples of the metric being used. Try to include examples that clear up any potential ambiguity left from the metric description above. If possible, provide a range of examples that show both typical and atypical results, as well as examples where a variety of input parameters are passed.*## Limitations and Bias*Note any known limitations or biases that the metric has, with links and references if possible.*## Citation*Cite the source where this metric was introduced.*## Further References*Add any useful further references.*1234567892 unmodified lines12131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107---title: Specificitytags:- evaluate- metricdescription: "Specificity is the fraction of the negatives examples that were correctly labeled by the model as negatives. It can be computed with the equation: Specificity = TN / (TN + FP) Where TN is the true negatives and FP is the false positives."sdk: gradiosdk_version: 3.19.1app_file: app.py2 unmodified lines# Metric Card for Specificity## Metric DescriptionSpecificity is the fraction of the negatives examples that were correctly labeled by the model as negatives. It can be computed with the equation:$$\text{Specificity} = \frac{TN}{TN + FP}$$Where $TN$ is the true negatives and $FP$ is the false positives.## How to UseAt minimum, this metric takes as input two lists, each containing ints: predictions and references.```python>>> specificity_metric = evaluate.load('nevikw39/specificity')>>> results = specificity_metric.compute(references=[0, 1], predictions=[0, 1])>>> print(results)["{'specificity': 1.0}"]```### Inputs- **predictions** (`list` of `int`): The predicted labels.- **references** (`list` of `int`): The ground truth labels.- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.- **neg_label** (`int`): The class label to use as the 'negative class' when calculating the specificity. Defaults to `0`.- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.- `'binary'`: Only report results for the class specified by `neg_label`. This is applicable only if the target labels and predictions are binary.- `'micro'`: Calculate metrics globally by counting the total true negatives, false positives, and false negatives.- `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.- `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between sensitivity and specificity.- `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .- `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.- `0`: If there is a zero division, the return value is `0`.- `1`: If there is a zero division, the return value is `1`.### Output Values- **specificity** (`float`, or `array` of `float`): Either the general specificity score, or the specificity scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher specificity means that more of the positive examples have been labeled correctly. Therefore, a higher specificity is generally considered better.#### Values from Popular Papers### ExamplesExample 1-A simple example with some errors```python>>> specificity_metric = evaluate.load('nevikw39/specificity')>>> results = specificity_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])>>> print(results){'specificity': 0.5}```Example 2-The same example as Example 1, but with `neg_label=1` instead of the default `neg_label=0`.```python>>> specificity_metric = evaluate.load('nevikw39/specificity')>>> results = specificity_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], neg_label=1)>>> print(results){'specificity': 0.6666666666666666}```Example 3-The same example as Example 1, but with `sample_weight` included.```python>>> specificity_metric = evaluate.load('nevikw39/specificity')>>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]>>> results = specificity_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)>>> print(results){'specificity': 0.8181818181818181}```Example 4-A multiclass example, using different averages.```python>>> specificity_metric = evaluate.load('nevikw39/specificity')>>> predictions = [0, 2, 1, 0, 0, 1]>>> references = [0, 1, 2, 0, 1, 2]>>> results = specificity_metric.compute(predictions=predictions, references=references, average='macro')>>> print(results){'specificity': 0.3333333333333333}>>> results = specificity_metric.compute(predictions=predictions, references=references, average='micro')>>> print(results){'specificity': 0.3333333333333333}>>> results = specificity_metric.compute(predictions=predictions, references=references, average='weighted')>>> print(results){'specificity': 0.3333333333333333}>>> results = specificity_metric.compute(predictions=predictions, references=references, average=None)>>> print(results){'specificity': array([1., 0., 0.])}```## Limitations and Bias## Citation```@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}}```## Further References
10 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949510 unmodified lines# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""TODO: Add a description here."""import evaluateimport datasets# TODO: Add BibTeX citation_CITATION = """\@InProceedings{huggingface:module,title = {A great new module},authors={huggingface, Inc.},year={2020}}"""# TODO: Add description of the module here_DESCRIPTION = """\This new module is designed to solve this great ML task and is crafted with a lot of care."""# TODO: Add description of the arguments of the module here_KWARGS_DESCRIPTION = """Calculates how good are predictions given some references, using certain scoresArgs:predictions: list of predictions to score. Each predictionsshould be a string with tokens separated by spaces.references: list of reference for each prediction. Eachreference should be a string with tokens separated by spaces.Returns:accuracy: description of the first score,another_score: description of the second score,Examples:Examples should be written in doctest format, and should illustrate howto use the function.>>> my_new_module = evaluate.load("my_new_module")>>> results = my_new_module.compute(references=[0, 1], predictions=[0, 1])>>> print(results){'accuracy': 1.0}"""# TODO: Define external resources urls if neededBAD_WORDS_URL = "http://url/to/external/resource/bad_words.txt"@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)class Specificity(evaluate.Metric):"""TODO: Short description of my evaluation module."""def _info(self):# TODO: Specifies the evaluate.EvaluationModuleInfo objectreturn evaluate.MetricInfo(# This is the description that will appear on the modules page.module_type="metric",description=_DESCRIPTION,citation=_CITATION,inputs_description=_KWARGS_DESCRIPTION,# This defines the format of each prediction and referencefeatures=datasets.Features({'predictions': datasets.Value('int64'),'references': datasets.Value('int64'),}),# Homepage of the module for documentationhomepage="http://module.homepage",# Additional links to the codebase or referencescodebase_urls=["http://github.com/path/to/codebase/of/new_module"],reference_urls=["http://path.to.reference.url/new_module"])def _download_and_prepare(self, dl_manager):"""Optional: download external resources useful to compute the scores"""# TODO: Download external resources if neededpassdef _compute(self, predictions, references):"""Returns the scores"""# TODO: Compute the different scores of the moduleaccuracy = sum(i == j for i, j in zip(predictions, references)) / len(predictions)return {"accuracy": accuracy,}10 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313410 unmodified lines# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Specificity metric."""import evaluateimport datasetsfrom sklearn.metrics import recall_score_CITATION = """\@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}}"""_DESCRIPTION = """\Specificity is the fraction of the negatives examples that were correctly labeled by the model as negatives. It can be computed with the equation:Specificity = TN / (TN + FP)Where TN is the true negatives and FP is the false positives."""_KWARGS_DESCRIPTION = """Args:- **predictions** (`list` of `int`): The predicted labels.- **references** (`list` of `int`): The ground truth labels.- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.- **neg_label** (`int`): The class label to use as the 'negative class' when calculating the specificity. Defaults to `0`.- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.- `'binary'`: Only report results for the class specified by `neg_label`. This is applicable only if the target labels and predictions are binary.- `'micro'`: Calculate metrics globally by counting the total true negatives, false positives, and false negatives.- `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.- `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between sensitivity and specificity.- `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .- `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.- `0`: If there is a zero division, the return value is `0`.- `1`: If there is a zero division, the return value is `1`.Returns:- **specificity** (`float`, or `array` of `float`): Either the general specificity score, or the specificity scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher specificity means that more of the positive examples have been labeled correctly. Therefore, a higher specificity is generally considered better.Examples:Example 1-A simple example with some errors>>> specificity_metric = evaluate.load('nevikw39/specificity')>>> results = specificity_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])>>> print(results){'specificity': 0.5}Example 2-The same example as Example 1, but with `neg_label=1` instead of the default `neg_label=0`.>>> specificity_metric = evaluate.load('nevikw39/specificity')>>> results = specificity_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], neg_label=1)>>> print(results){'specificity': 0.6666666666666666}Example 3-The same example as Example 1, but with `sample_weight` included.>>> specificity_metric = evaluate.load('nevikw39/specificity')>>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]>>> results = specificity_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)>>> print(results){'specificity': 0.8181818181818181}Example 4-A multiclass example, using different averages.>>> specificity_metric = evaluate.load('nevikw39/specificity')>>> predictions = [0, 2, 1, 0, 0, 1]>>> references = [0, 1, 2, 0, 1, 2]>>> results = specificity_metric.compute(predictions=predictions, references=references, average='macro')>>> print(results){'specificity': 0.3333333333333333}>>> results = specificity_metric.compute(predictions=predictions, references=references, average='micro')>>> print(results){'specificity': 0.3333333333333333}>>> results = specificity_metric.compute(predictions=predictions, references=references, average='weighted')>>> print(results){'specificity': 0.3333333333333333}>>> results = specificity_metric.compute(predictions=predictions, references=references, average=None)>>> print(results){'specificity': array([1., 0., 0.])}"""@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)class Specificity(evaluate.Metric):"""Specificity metric."""def _info(self):return evaluate.MetricInfo(module_type="metric",description=_DESCRIPTION,citation=_CITATION,inputs_description=_KWARGS_DESCRIPTION,features=datasets.Features({"predictions": datasets.Sequence(datasets.Value("int32")),"references": datasets.Sequence(datasets.Value("int32")),}if self.config_name == "multilabel"else {"predictions": datasets.Value("int32"),"references": datasets.Value("int32"),}),reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"],)def _compute(self,predictions: datasets.Sequence(datasets.Value("int32")) | datasets.Value("int32"),references: datasets.Sequence(datasets.Value("int32")) | datasets.Value("int32"),labels=None,neg_label=0,average="binary",sample_weight=None,zero_division="warn",):score = recall_score(references,predictions,labels=labels,pos_label=neg_label,average=average,sample_weight=sample_weight,zero_division=zero_division,)return {"specificity": float(score) if score.size == 1 else score}
1234567891011121314151617test_cases = [{"predictions": [0, 0],"references": [1, 1],"result": {"metric_score": 0}},{"predictions": [1, 1],"references": [1, 1],"result": {"metric_score": 1}},{"predictions": [1, 0],"references": [1, 1],"result": {"metric_score": 0.5}}]1234567test_cases = [{"predictions": [0, 0, 1, 1, 1],"references": [0, 1, 0, 1, 1],"result": {"specificity": 0.5}},]
README.md+75-18
specificity.py+91-52
tests.py+3-13