evaluator.py 6.28 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import os
from typing import Any, Dict, List

import gpt_evaluate
import metrics
import pandas as pd
from utils import get_data_per_category, jdump


class Evaluator(object):
    """
        A class named Evaluator includes GPT-3.5/GPT-4 evaluation
        and automatic evaluation

    """

17
18
    def __init__(self, params: Dict[str, Any], battle_prompt: Dict[str, Any], gpt_evaluation_prompt: Dict[str, Any],
                 gpt_model: str, language: str) -> None:
19
20
21
        self.params = params
        self.battle_prompt = battle_prompt
        self.gpt_evaluation_prompt = gpt_evaluation_prompt
22
23
        self.gpt_model = gpt_model
        self.language = language
24
        self.automatic_metric_stats = dict()
25
        self.gpt_evaluation_results = dict()
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
        self.battle_results = []

    def battle(self, answers1: List[Dict], answers2: List[Dict]) -> None:
        """
        Comparison between two models using GPT-4 as the reviewer.
        """

        self.battle_results = gpt_evaluate.battle(answers1, answers2, self.battle_prompt)

    def evaluate(self, answers: List[Dict], targets: List[Dict]) -> None:
        """
        A comprehensive evaluation of the answers from the model.
        The function evaluates the model's performance from different perspectives
        using GPT-3.5, GPT-4, and off-the-shelf evaluation metrics.

        The metrics will be decided by the config file.

        """

        def switch(metric):
            if metric == "BLEU":
                return metrics.bleu_score(preds=predicts_list, targets=targets_list)
            elif metric == "ROUGE":
                return metrics.rouge_cn_score(preds=predicts_list, targets=targets_list)
            elif (metric == "Distinct"):
                return metrics.distinct_score(preds=predicts_list)
            elif (metric == "BERTScore"):
                return metrics.bert_score(preds=predicts_list, targets=targets_list)
            elif (metric == "Precision"):
                return metrics.precision(preds=predicts_list, targets=targets_list)
            elif (metric == "Recall"):
                return metrics.recall(preds=predicts_list, targets=targets_list)
            elif (metric == "F1 score"):
                return metrics.F1_score(preds=predicts_list, targets=targets_list)
            else:
                raise ValueError(f"Unexpected metric")

        answers_per_category = get_data_per_category(answers, list(self.params.keys()))
        targets_per_category = get_data_per_category(targets, list(self.params.keys()))

        # automatic evaluation
        for category in self.params:
68
69
70
71
            if len(answers_per_category[category]) == 0:
                print(f"Category {category} specified in your config doesn't have corresponding answers!")
                continue

72
73
74
75
76
77
78
79
80
81
82
            category_metrics = self.params[category]["Metrics"]
            self.automatic_metric_stats[category] = {}

            targets_list = [
                target["target"] if target["target"] else target["output"] for target in targets_per_category[category]
            ]
            predicts_list = [answer["output"] for answer in answers_per_category[category]]

            for metric in category_metrics:
                self.automatic_metric_stats[category].update(switch(metric=metric))

83
        # gpt evaluation
84
        for category in self.params:
85
86
87
88
89
            if len(answers_per_category[category]) == 0:
                print(f"Category {category} specified in your config doesn't have corresponding answers!")
                continue

            category_metrics = self.params[category]["GPT"]
90
91
92
93
94
95

            prompt = self.gpt_evaluation_prompt.get(category, None)
            if prompt is None:
                print(f"No prompt for category {category}! Use prompt for category general now.")
                prompt = self.gpt_evaluation_prompt["general"]

96
97
            self.gpt_evaluation_results[category] = gpt_evaluate.evaluate(answers_per_category[category], prompt,
                                                                          category_metrics, category, self.gpt_model)
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

    def save(self, path: str, model_name_list: List[str]) -> None:
        """
        Save evaluation results of GPT-3.5, GPT-4, and off-the-shelf evaluation metrics.

        """

        if len(model_name_list) == 2:
            save_path = os.path.join(path, "gpt_evaluate", "battle_results")
            gpt_evaluate.save_battle_results(self.battle_results, model_name_list[0], model_name_list[1], save_path)
        else:
            # save evaluation results for automatic metrics
            automatic_df = pd.DataFrame(self.automatic_metric_stats)

            automatic_results_save_path = os.path.join(path, "automatic_results")
            if not os.path.exists(automatic_results_save_path):
                os.makedirs(automatic_results_save_path)
            automatic_df.to_csv(os.path.join(automatic_results_save_path, f"{model_name_list[0]}.csv"), index=True)

            # Save evaluation results for GPT-3.5 evaluation metrics.
            all_evaluations = []
119
            base_save_path = os.path.join(path, "gpt_evaluate", "gpt_evaluate_results")
120
121
            evaluation_results_save_path = os.path.join(base_save_path, "evaluation_results")

122
            for category, evaluations in self.gpt_evaluation_results.items():
123
124
125
126
127
128
129
130
131
                jdump(
                    evaluations,
                    os.path.join(evaluation_results_save_path, model_name_list[0],
                                 f"{category}_evaluation_results.json"))
                all_evaluations.extend(evaluations)

            jdump(all_evaluations,
                  os.path.join(evaluation_results_save_path, f"{model_name_list[0]}_evaluation_results.json"))

132
            # Start to calculate scores and save statistics.
133
            evaluation_statistics_save_path = os.path.join(base_save_path, "evaluation_statistics")
134
135
            gpt_evaluate.save_gpt_evaluation_statistics(model_name_list[0], all_evaluations,
                                                        evaluation_statistics_save_path)
136
137
138

            # Save charts and csv.
            evaluation_analyses_save_path = os.path.join(base_save_path, "evaluation_analyses")
139
140
            gpt_evaluate.analyze_gpt_evaluation_statistics(evaluation_statistics_save_path,
                                                           evaluation_analyses_save_path)