|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import functools |
| 4 | +import warnings |
| 5 | +from typing import Literal |
| 6 | + |
| 7 | +from scipy.stats import kendalltau, pearsonr, spearmanr |
| 8 | + |
| 9 | +from .base import Metric, MetricResult |
| 10 | +from .string_processor import StringProcessor |
| 11 | + |
| 12 | + |
| 13 | +class Correlation(Metric): |
| 14 | + """ |
| 15 | + Correlation metric to compute Pearson, Spearman, or Kendall correlation coefficients. |
| 16 | + The lm_outputs and references should be numeric values, optionally preprocessed by StringProcessor. |
| 17 | +
|
| 18 | + Args: |
| 19 | + method: The correlation method to use ('pearson', 'spearman', 'kendall'). |
| 20 | + lm_output_processor: StringProcessor or a list of StringProcessor to be applied to the model outputs before |
| 21 | + computing the correlation. If a list is provided, the processors will be applied in order. |
| 22 | + reference_processor: StringProcessor or a list of StringProcessor to be applied to the references before |
| 23 | + computing the correlation. If a list is provided, the processors will be applied in order. |
| 24 | +
|
| 25 | + Examples: |
| 26 | + >>> from flexeval import Correlation |
| 27 | + >>> correlation = Correlation(method='pearson') |
| 28 | + >>> lm_outputs = ["1", "2", "3", "4", "5"] |
| 29 | + >>> references = [["5"], ["4"], ["3"], ["2"], ["1"]] |
| 30 | + >>> result = correlation.evaluate(lm_outputs, references) |
| 31 | + >>> print(result) |
| 32 | + MetricResult( |
| 33 | + summary={"pearson_correlation": -1.0, "pearson_pvalue": 0.0}, |
| 34 | + instance_details=[], |
| 35 | + ) |
| 36 | + """ |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, |
| 40 | + method: Literal["pearson", "spearman", "kendall"] = "pearson", |
| 41 | + lm_output_processor: StringProcessor | list[StringProcessor] | None = None, |
| 42 | + reference_processor: StringProcessor | list[StringProcessor] | None = None, |
| 43 | + ) -> None: |
| 44 | + if method not in {"pearson", "spearman", "kendall"}: |
| 45 | + msg = f"Invalid method '{method}'. Choose from 'pearson', 'spearman', 'kendall'." |
| 46 | + raise ValueError(msg) |
| 47 | + self.method = method |
| 48 | + |
| 49 | + if isinstance(lm_output_processor, StringProcessor): |
| 50 | + lm_output_processor = [lm_output_processor] |
| 51 | + if isinstance(reference_processor, StringProcessor): |
| 52 | + reference_processor = [reference_processor] |
| 53 | + self.lm_output_processors = lm_output_processor |
| 54 | + self.reference_processors = reference_processor |
| 55 | + |
| 56 | + def evaluate( |
| 57 | + self, |
| 58 | + lm_outputs: list[str], |
| 59 | + references_list: list[list[str]], |
| 60 | + task_inputs_list: list[dict[str, str]] | None = None, |
| 61 | + ) -> MetricResult: |
| 62 | + if len(lm_outputs) != len(references_list): |
| 63 | + msg = ( |
| 64 | + f"Number of model outputs ({len(lm_outputs)}) and number of references ({len(references_list)}) " |
| 65 | + "should be the same." |
| 66 | + ) |
| 67 | + raise ValueError(msg) |
| 68 | + |
| 69 | + # We only use the first reference here |
| 70 | + references = [refs[0] for refs in references_list] |
| 71 | + |
| 72 | + if self.lm_output_processors: |
| 73 | + lm_outputs = [ |
| 74 | + functools.reduce(lambda x, norm: norm(x), self.lm_output_processors, output) for output in lm_outputs |
| 75 | + ] |
| 76 | + |
| 77 | + if self.reference_processors: |
| 78 | + references = [ |
| 79 | + functools.reduce(lambda x, norm: norm(x), self.reference_processors, ref) for ref in references |
| 80 | + ] |
| 81 | + |
| 82 | + # The model output should be converted to float, if fails it will be treated as 0 |
| 83 | + lm_outputs_as_float: list[float] = [] |
| 84 | + for output in lm_outputs: |
| 85 | + try: |
| 86 | + lm_outputs_as_float.append(float(output)) |
| 87 | + except ValueError: # noqa:PERF203 |
| 88 | + warnings.warn(f"Failed to convert model output '{output}' to float. Treating it as 0.", stacklevel=2) |
| 89 | + lm_outputs_as_float.append(0.0) |
| 90 | + |
| 91 | + # The reference should be converted to float |
| 92 | + references_as_float = [float(ref) for ref in references] |
| 93 | + |
| 94 | + # Compute correlation |
| 95 | + if self.method == "pearson": |
| 96 | + correlation, pvalue = pearsonr(lm_outputs_as_float, references_as_float) |
| 97 | + elif self.method == "spearman": |
| 98 | + correlation, pvalue = spearmanr(lm_outputs_as_float, references_as_float) |
| 99 | + elif self.method == "kendall": |
| 100 | + correlation, pvalue = kendalltau(lm_outputs_as_float, references_as_float) |
| 101 | + else: |
| 102 | + msg = f"Unsupported method: {self.method}" |
| 103 | + raise ValueError(msg) |
| 104 | + |
| 105 | + return MetricResult( |
| 106 | + {f"{self.method}_correlation": correlation, f"{self.method}_pvalue": pvalue}, |
| 107 | + instance_details=[], |
| 108 | + ) |
0 commit comments