m7mdal7aj commited on
Commit
636ef92
1 Parent(s): 16e925f

Create finetuning_evaluation.py

Browse files
my_model/tabs/finetuning_evaluation.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from fuzzywuzzy import fuzz
3
+ from collections import Counter
4
+ from nltk.stem import PorterStemmer
5
+ from ast import literal_eval
6
+ from typing import Union, List
7
+
8
+ class KBVQAEvaluator:
9
+ def __init__(self, data_path: str, use_fuzzy: bool = False):
10
+ """
11
+ Initialize the VQA Processor with the dataset and configuration settings.
12
+ """
13
+ self.stemmer = PorterStemmer()
14
+ self.df = pd.read_excel(data_path)
15
+ self.scores_df = pd.read_excel(data_path, sheet_name="Scores")
16
+ self.df = pd.read_excel(data_path, sheet_name="Main Data")
17
+ self.use_fuzzy = use_fuzzy
18
+ self.vqa_scores = {}
19
+ self.exact_match_scores = {}
20
+
21
+ def stem_answers(self, answers: Union[str, List[str]]) -> Union[str, List[str]]:
22
+ """
23
+ Apply Porter Stemmer to either a single string or a list of strings.
24
+ """
25
+ if isinstance(answers, list):
26
+ return [" ".join(self.stemmer.stem(word.strip()) for word in answer.split()) for answer in answers]
27
+ else:
28
+ words = answers.split()
29
+ return " ".join(self.stemmer.stem(word.strip()) for word in words)
30
+
31
+ def calculate_vqa_score(self, ground_truths, model_answer):
32
+ """
33
+ Calculate VQA score based on the number of matching answers, with optional fuzzy matching.
34
+ """
35
+ if self.use_fuzzy:
36
+ fuzzy_matches = sum(fuzz.partial_ratio(model_answer, gt) >= 80 for gt in ground_truths)
37
+ return min(fuzzy_matches / 3, 1)
38
+ else:
39
+ count = Counter(ground_truths)
40
+ return min(count.get(model_answer, 0) / 3, 1)
41
+
42
+ def calculate_exact_match_score(self, ground_truths, model_answer):
43
+ """
44
+ Calculate Exact Match score, with optional fuzzy matching.
45
+ """
46
+ if self.use_fuzzy:
47
+ return int(any(fuzz.partial_ratio(model_answer, gt) >= 80 for gt in ground_truths))
48
+ else:
49
+ return int(model_answer in ground_truths)
50
+
51
+ def evaluate(self):
52
+ """
53
+ Process the DataFrame: stem answers, calculate scores, and store results.
54
+ """
55
+ self.df['raw_answers_stemmed'] = self.df['raw_answers'].apply(literal_eval).apply(self.stem_answers)
56
+ model_configurations = ['caption+detic', 'caption+yolov5', 'only_caption', 'only_detic', 'only_yolov5']
57
+ model_names = ['13b', '7b']
58
+
59
+ for name in model_names:
60
+ for config in model_configurations:
61
+ full_config = f'{name}_{config}'
62
+ self.df[f'{full_config}_stemmed'] = self.df[full_config].apply(self.stem_answers)
63
+
64
+ self.df[f'vqa_score_{full_config}'] = self.df.apply(lambda x: self.calculate_vqa_score(x['raw_answers_stemmed'], x[f'{full_config}_stemmed']), axis=1)
65
+ self.df[f'exact_match_score_{full_config}'] = self.df.apply(lambda x: self.calculate_exact_match_score(x['raw_answers_stemmed'], x[f'{full_config}_stemmed']), axis=1)
66
+
67
+ self.vqa_scores[full_config] = round(self.df[f'vqa_score_{full_config}'].mean()*100, 2)
68
+ self.exact_match_scores[full_config] = round(self.df[f'exact_match_score_{full_config}'].mean()*100, 2)
69
+
70
+ def save_results(self):
71
+ # Create a DataFrame for the scores
72
+ scores_data = {
73
+ 'Model Configuration': list(self.vqa_scores.keys()),
74
+ 'VQA Score': list(self.vqa_scores.values()),
75
+ 'Exact Match Score': list(self.exact_match_scores.values())
76
+ }
77
+ scores_df = pd.DataFrame(scores_data)
78
+
79
+ # Saving the scores DataFrame to an Excel file
80
+ with pd.ExcelWriter('evaluation_results_final.xlsx', engine='openpyxl', mode='w') as writer:
81
+ scores_df.to_excel(writer, sheet_name='Scores', index=False)
82
+
83
+ def run_evaluator(self):
84
+ evaluator = KBVQAEvaluator('evaluation_results_final.xlsx', use_fuzzy=False)
85
+ evaluator.evaluate()
86
+ st.table(self.vqa_scores)
87
+ print(evaluator.exact_match_scores)
88
+ evaluator.save_results()