-
Notifications
You must be signed in to change notification settings - Fork 0
/
llm_evaluator.py
129 lines (87 loc) · 4.38 KB
/
llm_evaluator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
from ctransformers import AutoConfig, AutoModelForCausalLM, Config
import openai
import pandas as pd
import numpy as np
import os
import regex
import re
from transformers import AutoTokenizer, AutoModel
import torch
from langchain.evaluation import load_evaluator
from langchain.evaluation import EvaluatorType
#import langchain.evaluator as evaluator
##########################################################################
##########################################################################
# USAGE:
# enter the filepath and filename as prompted
# INPUT
# Input file should be a csv file list of questions to be sent to the bot,
# along with the generated output, and the ground truth or expected answer.
# OUTPUT:
# This will output a csv file with the Original question, the bot responses,
# the ground truth responses, along with the correctness, as calculated by
# langchain's evaluator, and cosine similarity scores
##########################################################################
##########################################################################
#api_key=
os.environ['OPENAI_API_KEY'];
huggingfacehub_api_token=os.environ['HUGGINGFACEHUB_API_TOKEN']
# User inputs:
filepath=input("Please enter the path and filename of the csv that contains the questions, bot responses, and root truth answers that require analysis:\n")
def remove_number_period(text):
return re.sub(r'^\d{1,3}\.', '', text)
def remove_character(s):
return s.replace('Â', '')
model_name = "sentence-transformers/all-MiniLM-L6-v2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)
def get_embedding(text):
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
with torch.no_grad():
outputs = model(**inputs)
return outputs.last_hidden_state.mean(dim=1)
def cosine_similarity(embedding1, embedding2):
return torch.nn.functional.cosine_similarity(embedding1, embedding2).item()
# Define a custom evaluator
#class ContinuousEvaluator(evaluators.BaseEvaluator):
def evaluate2(ground_truth, generated):
ground_truth_embedding = get_embedding(ground_truth)
generated_embedding = get_embedding(generated)
return cosine_similarity(ground_truth_embedding, generated_embedding)
# function to generate utterances from a dataframe entry:
def response_analysis(dataframe, column_name, column_name2, column_name3):
results = []
#for sentence,index in dataframe[column_name]:
for i, row in dataframe.iterrows():
#for sentence2 in dataframe[column_name2]:
sentence = row[column_name]
sentence2 = row[column_name2]
sentence3 = row[column_name3]
try:
evaluator=load_evaluator("labeled_criteria",criteria="correctness")
eval_result=evaluator.evaluate_strings(prediction=sentence, input=sentence3, reference=sentence2)
#evaluator2 = ContinuousEvaluator()
ground_truth = sentence2
generated_response = sentence
score = evaluate2(ground_truth, generated_response)
results.append({'Response': sentence, 'Answer': sentence2, 'Correctness Score': eval_result['score'],
'Reason': eval_result['reasoning'].replace('\n','').split('.')[:-1],
'Similarity': score})
except Exception as e:
print(f"An error occurred: {e}")
results.append({'Response': sentence, 'Answer': sentence2, 'Correctness Score': [], 'Reason': [],
'Similarity': []})
return pd.DataFrame(results)
if __name__ == "__main__":
test_df = pd.read_csv(filepath, encoding = "ISO-8859-1")
test_df.dropna(subset=['Question','Response','Answer'], inplace=True)
test_df = test_df.loc[:, ['Question','Response','Answer']]
test_df['Response']=test_df['Response'].astype('string')
test_df['Answer']=test_df['Answer'].astype('string')
test_df['Question']=test_df['Question'].astype('string')
remove_character(test_df['Response'])
analysis_df = response_analysis(test_df, 'Response', 'Answer', 'Question')
# extract filename from filepath variable:
file=os.path.basename(filepath)
# write to new csv file using original filename to identify:
analysis_df.to_csv('CorrectnessPlusSimilarity_' + file, sep=',', index=False, encoding='utf-8')