pcs-annotator 0.1.4__tar.gz → 0.1.6__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {pcs_annotator-0.1.4 → pcs_annotator-0.1.6}/PKG-INFO +1 -1
- {pcs_annotator-0.1.4 → pcs_annotator-0.1.6}/pcs_annotator/LLM.py +1 -1
- pcs_annotator-0.1.6/pcs_annotator/PCS.py +430 -0
- {pcs_annotator-0.1.4 → pcs_annotator-0.1.6}/pyproject.toml +1 -1
- pcs_annotator-0.1.4/pcs_annotator/PCS.py +0 -237
- {pcs_annotator-0.1.4 → pcs_annotator-0.1.6}/LICENSE +0 -0
- {pcs_annotator-0.1.4 → pcs_annotator-0.1.6}/README.md +0 -0
- {pcs_annotator-0.1.4 → pcs_annotator-0.1.6}/pcs_annotator/Annotator.py +0 -0
- {pcs_annotator-0.1.4 → pcs_annotator-0.1.6}/pcs_annotator/TextMutator.py +0 -0
- {pcs_annotator-0.1.4 → pcs_annotator-0.1.6}/pcs_annotator/Tools.py +0 -0
- {pcs_annotator-0.1.4 → pcs_annotator-0.1.6}/pcs_annotator/__init__.py +0 -0
- {pcs_annotator-0.1.4 → pcs_annotator-0.1.6}/requirements.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pcs-annotator
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.6
|
|
4
4
|
Summary: A Python library for classification tasks using multiple LLMs
|
|
5
5
|
Project-URL: Homepage, https://github.com/salsina/PCS-Python-Library
|
|
6
6
|
Project-URL: Issues, https://github.com/salsina/PCS-Python-Library/issues
|
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
from .TextMutator import TextMutator
|
|
2
|
+
from .Annotator import Annotator
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import os
|
|
5
|
+
import numpy as np
|
|
6
|
+
from scipy.optimize import differential_evolution
|
|
7
|
+
from tqdm import tqdm
|
|
8
|
+
from sklearn.linear_model import LinearRegression
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PCS:
|
|
12
|
+
def __init__(self, prompt, dataset_path, annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "google/gemma-2-9b-it"], textmutator="llama-3.1-8b-instant", GROQ_API_KEY=None, OPENAI_API_KEY=None, ANTHROPIC_API_KEY=None, HUGGINGFACE_API_KEY=None, train=True):
|
|
13
|
+
self.prompt=prompt
|
|
14
|
+
if os.path.exists(dataset_path):
|
|
15
|
+
self.dataset_path = dataset_path
|
|
16
|
+
else:
|
|
17
|
+
raise FileNotFoundError(f"Invalid dataset path {dataset_path}")
|
|
18
|
+
self.annotator_model_names = annotators
|
|
19
|
+
self.annotators = []
|
|
20
|
+
|
|
21
|
+
if textmutator.startswith("llama"):
|
|
22
|
+
self.textMutator = TextMutator(model_name=textmutator, token=GROQ_API_KEY)
|
|
23
|
+
elif textmutator.startswith("gpt"):
|
|
24
|
+
self.textMutator = TextMutator(model_name=textmutator, token=OPENAI_API_KEY)
|
|
25
|
+
elif textmutator.startswith("claude"):
|
|
26
|
+
self.textMutator = TextMutator(model_name=textmutator, token=ANTHROPIC_API_KEY)
|
|
27
|
+
elif textmutator.startswith("mistral") or textmutator.startswith("google"):
|
|
28
|
+
self.textMutator = TextMutator(model_name=textmutator, token=HUGGINGFACE_API_KEY)
|
|
29
|
+
else:
|
|
30
|
+
raise ValueError(f"Unsupported text mutator model name: {textmutator}")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
self.annotations_filename = self.dataset_path.rsplit(".csv", 1)[0] + "_annotations.csv"
|
|
34
|
+
self.dataset = pd.read_csv(dataset_path)
|
|
35
|
+
self.possible_labels = self.dataset["label"].unique().tolist()
|
|
36
|
+
for annotator_model_name in self.annotator_model_names:
|
|
37
|
+
if annotator_model_name.startswith("llama"):
|
|
38
|
+
token = GROQ_API_KEY
|
|
39
|
+
elif annotator_model_name.startswith("gpt"):
|
|
40
|
+
token = OPENAI_API_KEY
|
|
41
|
+
elif annotator_model_name.startswith("claude"):
|
|
42
|
+
token = ANTHROPIC_API_KEY
|
|
43
|
+
elif annotator_model_name.startswith("mistral") or annotator_model_name.startswith("google"):
|
|
44
|
+
token = HUGGINGFACE_API_KEY
|
|
45
|
+
else:
|
|
46
|
+
raise ValueError(f"Unsupported annotator model name: {annotator_model_name}")
|
|
47
|
+
|
|
48
|
+
self.annotators.append(Annotator(prompt=self.prompt, labels=self.possible_labels, model_name=annotator_model_name, token=token))
|
|
49
|
+
self.optimal_llm_weights = [1] * len(self.annotators)
|
|
50
|
+
self.optimal_mr_weights = [1] * 4
|
|
51
|
+
# self.optimal_label_thresholds = [0.5] * len(self.possible_labels)
|
|
52
|
+
|
|
53
|
+
if train:
|
|
54
|
+
print("Labelling the dataset...")
|
|
55
|
+
self.create_annotations()
|
|
56
|
+
print("Generated the dataset annotations.")
|
|
57
|
+
|
|
58
|
+
print("Optimizing weights...")
|
|
59
|
+
# self.PDE()
|
|
60
|
+
self.LR()
|
|
61
|
+
print("Done Optimizing weights.")
|
|
62
|
+
|
|
63
|
+
def create_annotations(self):
|
|
64
|
+
csv_filename = self.annotations_filename
|
|
65
|
+
|
|
66
|
+
if os.path.exists(csv_filename):
|
|
67
|
+
# Read the existing dataset
|
|
68
|
+
existing_df = pd.read_csv(csv_filename)
|
|
69
|
+
if not existing_df.empty:
|
|
70
|
+
last_index = existing_df.index[-1] + 1 # Get last index and continue from there
|
|
71
|
+
else:
|
|
72
|
+
last_index = 0
|
|
73
|
+
else:
|
|
74
|
+
columns = ["label", "text", "text_mr1", "text_mr2", "text_mr3"]
|
|
75
|
+
for annotator in self.annotators:
|
|
76
|
+
columns.append(annotator.model_name+"_text")
|
|
77
|
+
columns.append(annotator.model_name+"_text_mr1")
|
|
78
|
+
columns.append(annotator.model_name+"_text_mr2")
|
|
79
|
+
columns.append(annotator.model_name+"_text_mr3")
|
|
80
|
+
|
|
81
|
+
existing_df = pd.DataFrame(columns=columns)
|
|
82
|
+
existing_df.to_csv(csv_filename, index=False)
|
|
83
|
+
last_index = 0
|
|
84
|
+
|
|
85
|
+
with tqdm(total=len(self.dataset), initial=last_index, desc="Processing Annotations", unit="sample") as pbar:
|
|
86
|
+
|
|
87
|
+
for index in range(last_index, len(self.dataset)):
|
|
88
|
+
row = self.dataset.iloc[index]
|
|
89
|
+
label = row['label']
|
|
90
|
+
text = row['text']
|
|
91
|
+
text_mr1 = self.textMutator.MutateText(text=text, mr="passive_active")
|
|
92
|
+
text_mr2 = self.textMutator.MutateText(text=text, mr="double_negation")
|
|
93
|
+
text_mr3 = self.textMutator.MutateText(text=text, mr="synonym")
|
|
94
|
+
|
|
95
|
+
existing_df.at[index, "label"] = label
|
|
96
|
+
existing_df.at[index, "text"] = text
|
|
97
|
+
existing_df.at[index, "text_mr1"] = text_mr1
|
|
98
|
+
existing_df.at[index, "text_mr2"] = text_mr2
|
|
99
|
+
existing_df.at[index, "text_mr3"] = text_mr3
|
|
100
|
+
|
|
101
|
+
for annotator in self.annotators:
|
|
102
|
+
existing_df.at[index, annotator.model_name+"_text"] = annotator.annotate(text)[0]
|
|
103
|
+
existing_df.at[index, annotator.model_name+"_text_mr1"] = annotator.annotate(text_mr1)[0]
|
|
104
|
+
existing_df.at[index, annotator.model_name+"_text_mr2"] = annotator.annotate(text_mr2)[0]
|
|
105
|
+
existing_df.at[index, annotator.model_name+"_text_mr3"] = annotator.annotate(text_mr3)[0]
|
|
106
|
+
|
|
107
|
+
row_df = existing_df.iloc[[index]]
|
|
108
|
+
row_df.to_csv(csv_filename, mode='a', index=False, header=not os.path.exists(csv_filename))
|
|
109
|
+
|
|
110
|
+
pbar.update(1) # Update progress bar
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def get_majority_vote_label(self, majority_votes, possible_labels=None):
|
|
114
|
+
if not possible_labels:
|
|
115
|
+
possible_labels = self.possible_labels
|
|
116
|
+
|
|
117
|
+
vote_counts = {label.strip().lower(): 0 for label in possible_labels}
|
|
118
|
+
|
|
119
|
+
for vote in majority_votes:
|
|
120
|
+
if not pd.isna(vote):
|
|
121
|
+
lowered_vote = vote.strip().lower()
|
|
122
|
+
if lowered_vote in vote_counts:
|
|
123
|
+
vote_counts[lowered_vote] += 1
|
|
124
|
+
|
|
125
|
+
max_votes = max(vote_counts.values())
|
|
126
|
+
|
|
127
|
+
for label, count in vote_counts.items():
|
|
128
|
+
if count == max_votes:
|
|
129
|
+
return label
|
|
130
|
+
|
|
131
|
+
# def get_pcs_label(self, llm_labels, w_llms=None, w_mrs=None, label_thresholds=None, possible_labels=None):
|
|
132
|
+
# if possible_labels is None:
|
|
133
|
+
# possible_labels = self.possible_labels
|
|
134
|
+
# if w_llms is None:
|
|
135
|
+
# w_llms = self.optimal_llm_weights
|
|
136
|
+
# if w_mrs is None:
|
|
137
|
+
# w_mrs = self.optimal_mr_weights
|
|
138
|
+
# if label_thresholds is None:
|
|
139
|
+
# label_thresholds = self.optimal_label_thresholds
|
|
140
|
+
|
|
141
|
+
# num_labels = len(possible_labels)
|
|
142
|
+
# pcs_labels = [0] * num_labels
|
|
143
|
+
|
|
144
|
+
# for i in range(len(w_llms)):
|
|
145
|
+
# pcs_label_llm = [0] * num_labels
|
|
146
|
+
# for j in range(len(llm_labels[i])): #Iterate through MR labels
|
|
147
|
+
# for k in range(len(pcs_label_llm)):
|
|
148
|
+
# if not pd.isna(llm_labels[i][j]):
|
|
149
|
+
# if llm_labels[i][j].strip().lower() == possible_labels[k].strip().lower():
|
|
150
|
+
# pcs_label_llm[k] += w_mrs[j]
|
|
151
|
+
|
|
152
|
+
# for j in range(len(pcs_label_llm)):
|
|
153
|
+
# # pcs_label_llm[j] = pcs_label_llm[j]/sum(w_mrs)
|
|
154
|
+
# if sum(w_mrs) != 0:
|
|
155
|
+
# pcs_label_llm[j] = pcs_label_llm[j] / sum(w_mrs)
|
|
156
|
+
# else:
|
|
157
|
+
# pcs_label_llm[j] = 0
|
|
158
|
+
|
|
159
|
+
# for j in range(len(pcs_label_llm)):
|
|
160
|
+
# pcs_labels[j] += w_llms[i] * pcs_label_llm[j]
|
|
161
|
+
|
|
162
|
+
# for i in range(num_labels):
|
|
163
|
+
# if sum(w_llms) != 0:
|
|
164
|
+
# pcs_labels[i] = pcs_labels[i]/sum(w_llms)
|
|
165
|
+
# else:
|
|
166
|
+
# pcs_labels[i] = 0
|
|
167
|
+
|
|
168
|
+
# for i in range(num_labels):
|
|
169
|
+
# if pcs_labels[i] > label_thresholds[i]:
|
|
170
|
+
# final_pred = possible_labels[i]
|
|
171
|
+
# return final_pred
|
|
172
|
+
|
|
173
|
+
# majority_votes = []
|
|
174
|
+
# for i in range(len(w_llms)):
|
|
175
|
+
# majority_votes.append(llm_labels[i][0])
|
|
176
|
+
|
|
177
|
+
# return self.get_majority_vote_label(majority_votes, possible_labels)
|
|
178
|
+
|
|
179
|
+
def get_pcs_label(self, llm_labels, w_llms=None, w_mrs=None, possible_labels=None):
|
|
180
|
+
if possible_labels is None:
|
|
181
|
+
possible_labels = self.possible_labels
|
|
182
|
+
if w_llms is None:
|
|
183
|
+
w_llms = self.optimal_llm_weights
|
|
184
|
+
if w_mrs is None:
|
|
185
|
+
w_mrs = self.optimal_mr_weights
|
|
186
|
+
|
|
187
|
+
num_labels = len(possible_labels)
|
|
188
|
+
pcs_labels = np.zeros(num_labels)
|
|
189
|
+
|
|
190
|
+
for i in range(len(w_llms)):
|
|
191
|
+
pcs_label_llm = np.zeros(num_labels)
|
|
192
|
+
for j in range(len(llm_labels[i])): #Iterate through MR labels
|
|
193
|
+
for k in range(len(pcs_label_llm)):
|
|
194
|
+
if llm_labels[i][j]:
|
|
195
|
+
if llm_labels[i][j].strip().lower() == possible_labels[k].strip().lower():
|
|
196
|
+
pcs_label_llm[k] += w_mrs[j]
|
|
197
|
+
|
|
198
|
+
# Normalize by sum of MR weights
|
|
199
|
+
if sum(w_mrs) != 0:
|
|
200
|
+
pcs_label_llm = pcs_label_llm / sum(w_mrs)
|
|
201
|
+
|
|
202
|
+
# Weight by LLM weights and accumulate
|
|
203
|
+
pcs_labels += w_llms[i] * pcs_label_llm
|
|
204
|
+
|
|
205
|
+
# Normalize by sum of LLM weights
|
|
206
|
+
if sum(w_llms) != 0:
|
|
207
|
+
pcs_labels = pcs_labels / sum(w_llms)
|
|
208
|
+
|
|
209
|
+
return pcs_labels
|
|
210
|
+
|
|
211
|
+
def Objective(self, params, llm_preds, NUM_LLMS, NUM_MRS, manual_labels):
|
|
212
|
+
w_mrs = params[:NUM_MRS] # Weights for 4 MRs
|
|
213
|
+
w_llms = params[NUM_MRS:NUM_MRS+NUM_LLMS] # Weights for 3 LLMs
|
|
214
|
+
label_thresholds = params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
|
|
215
|
+
predictions = []
|
|
216
|
+
|
|
217
|
+
predictions = [
|
|
218
|
+
self.get_pcs_label(llm_preds[i, :], w_llms, w_mrs, label_thresholds)
|
|
219
|
+
for i in range(len(manual_labels))
|
|
220
|
+
]
|
|
221
|
+
|
|
222
|
+
# Calculate accuracy
|
|
223
|
+
accuracy = np.mean([
|
|
224
|
+
manual_labels[i].strip().lower() == predictions[i].strip().lower()
|
|
225
|
+
for i in range(len(manual_labels))
|
|
226
|
+
])
|
|
227
|
+
return -accuracy # We want to maximize accuracy, so we minimize negative accuracy
|
|
228
|
+
|
|
229
|
+
def PDE(self):
|
|
230
|
+
if os.path.exists(self.annotations_filename):
|
|
231
|
+
df = pd.read_csv(self.annotations_filename)
|
|
232
|
+
else:
|
|
233
|
+
return
|
|
234
|
+
# Define model column mappings
|
|
235
|
+
model_columns = []
|
|
236
|
+
for annotator in self.annotators:
|
|
237
|
+
model_columns.append(df[[f"{annotator.model_name}_text", f"{annotator.model_name}_text_mr1", f"{annotator.model_name}_text_mr2", f"{annotator.model_name}_text_mr3"]])
|
|
238
|
+
llm_preds = np.stack(model_columns, axis=1)
|
|
239
|
+
|
|
240
|
+
manual_labels = df['label'].values
|
|
241
|
+
size, NUM_LLMS, NUM_MRS = llm_preds.shape[:3]
|
|
242
|
+
|
|
243
|
+
bounds = [(0, 1)] * (NUM_LLMS + NUM_MRS + len(self.possible_labels))
|
|
244
|
+
|
|
245
|
+
result = differential_evolution(self.Objective, bounds, args=(llm_preds, NUM_LLMS, NUM_MRS, manual_labels))
|
|
246
|
+
|
|
247
|
+
optimal_params = result.x
|
|
248
|
+
|
|
249
|
+
self.optimal_mr_weights = optimal_params[:NUM_MRS]
|
|
250
|
+
self.optimal_llm_weights = optimal_params[NUM_MRS:NUM_MRS+NUM_LLMS]
|
|
251
|
+
self.optimal_label_thresholds = optimal_params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
|
|
252
|
+
self.Accuracy = -result.fun
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def compute_features(self, llm_preds, selected_indices, optimize_params=["LLM", "MR"]):
|
|
256
|
+
"""
|
|
257
|
+
Compute feature matrix for linear regression.
|
|
258
|
+
Each row represents an example, and columns represent feature combinations based on optimize_params.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
llm_preds: Predictions from LLMs (shape: [n_samples, n_llms, n_mrs])
|
|
262
|
+
labels: List of possible label categories
|
|
263
|
+
selected_indices: Indices of samples to use
|
|
264
|
+
optimize_params: List of parameters to optimize (can include "LLM", "MR")
|
|
265
|
+
"""
|
|
266
|
+
num_examples = len(selected_indices)
|
|
267
|
+
num_llms = llm_preds.shape[1]
|
|
268
|
+
num_mrs = llm_preds.shape[2]
|
|
269
|
+
num_labels = len(self.possible_labels)
|
|
270
|
+
|
|
271
|
+
# Determine feature structure based on optimize_params
|
|
272
|
+
if "LLM" in optimize_params and "MR" in optimize_params:
|
|
273
|
+
# Original case: optimize both LLM and MR
|
|
274
|
+
feature_dim = num_llms * num_mrs * num_labels
|
|
275
|
+
|
|
276
|
+
# Initialize feature matrix
|
|
277
|
+
X = np.zeros((num_examples, feature_dim))
|
|
278
|
+
|
|
279
|
+
for idx, sample_idx in enumerate(selected_indices):
|
|
280
|
+
for i in range(num_llms):
|
|
281
|
+
for j in range(num_mrs):
|
|
282
|
+
for k, label in enumerate(self.possible_labels):
|
|
283
|
+
# Check if this LLM-MR combination predicts this label
|
|
284
|
+
if llm_preds[sample_idx, i, j].strip().lower() == label.strip().lower():
|
|
285
|
+
feature_idx = i * (num_mrs * num_labels) + j * num_labels + k
|
|
286
|
+
X[idx, feature_idx] = 1
|
|
287
|
+
|
|
288
|
+
elif "LLM" in optimize_params:
|
|
289
|
+
# Only optimize LLM weights
|
|
290
|
+
feature_dim = num_llms * num_labels
|
|
291
|
+
|
|
292
|
+
# Initialize feature matrix
|
|
293
|
+
X = np.zeros((num_examples, feature_dim))
|
|
294
|
+
|
|
295
|
+
for idx, sample_idx in enumerate(selected_indices):
|
|
296
|
+
for i in range(num_llms):
|
|
297
|
+
# Aggregate across all MRs for each LLM
|
|
298
|
+
llm_preds_aggregated = []
|
|
299
|
+
for j in range(num_mrs):
|
|
300
|
+
llm_preds_aggregated.append(llm_preds[sample_idx, i, j].strip().lower())
|
|
301
|
+
|
|
302
|
+
for k, label in enumerate(self.possible_labels):
|
|
303
|
+
# Count how many times this LLM predicts this label across MRs
|
|
304
|
+
count = llm_preds_aggregated.count(label.strip().lower())
|
|
305
|
+
if count > 0:
|
|
306
|
+
feature_idx = i * num_labels + k
|
|
307
|
+
X[idx, feature_idx] = count / num_mrs # Normalize by number of MRs
|
|
308
|
+
|
|
309
|
+
elif "MR" in optimize_params:
|
|
310
|
+
# Only optimize MR weights
|
|
311
|
+
feature_dim = num_mrs * num_labels
|
|
312
|
+
|
|
313
|
+
# Initialize feature matrix
|
|
314
|
+
X = np.zeros((num_examples, feature_dim))
|
|
315
|
+
|
|
316
|
+
for idx, sample_idx in enumerate(selected_indices):
|
|
317
|
+
for j in range(num_mrs):
|
|
318
|
+
# Aggregate across all LLMs for each MR
|
|
319
|
+
mr_preds_aggregated = []
|
|
320
|
+
for i in range(num_llms):
|
|
321
|
+
mr_preds_aggregated.append(llm_preds[sample_idx, i, j].strip().lower())
|
|
322
|
+
|
|
323
|
+
for k, label in enumerate(self.possible_labels):
|
|
324
|
+
# Count how many times this MR predicts this label across LLMs
|
|
325
|
+
count = mr_preds_aggregated.count(label.strip().lower())
|
|
326
|
+
if count > 0:
|
|
327
|
+
feature_idx = j * num_labels + k
|
|
328
|
+
X[idx, feature_idx] = count / num_llms # Normalize by number of LLMs
|
|
329
|
+
else:
|
|
330
|
+
# If optimize_params is empty or contains invalid parameters, default to both
|
|
331
|
+
return self.compute_features(llm_preds, selected_indices, ["LLM", "MR"])
|
|
332
|
+
|
|
333
|
+
return X
|
|
334
|
+
|
|
335
|
+
def LR(self):
|
|
336
|
+
if os.path.exists(self.annotations_filename):
|
|
337
|
+
df = pd.read_csv(self.annotations_filename)
|
|
338
|
+
else:
|
|
339
|
+
return
|
|
340
|
+
# Define model column mappings
|
|
341
|
+
model_columns = []
|
|
342
|
+
for annotator in self.annotators:
|
|
343
|
+
model_columns.append(df[[f"{annotator.model_name}_text", f"{annotator.model_name}_text_mr1", f"{annotator.model_name}_text_mr2", f"{annotator.model_name}_text_mr3"]])
|
|
344
|
+
llm_preds = np.stack(model_columns, axis=1)
|
|
345
|
+
|
|
346
|
+
manual_labels = df['label'].values
|
|
347
|
+
size, NUM_LLMS, NUM_MRS = llm_preds.shape[:3]
|
|
348
|
+
|
|
349
|
+
NUM_LABELS = len(self.possible_labels)
|
|
350
|
+
optimize_params = ["LLM", "MR"]
|
|
351
|
+
N_samples = llm_preds.shape[0]
|
|
352
|
+
selected_indices = np.random.choice(N_samples, size, replace=False)
|
|
353
|
+
|
|
354
|
+
# Prepare target variable (one-hot encoded labels)
|
|
355
|
+
y = np.zeros((len(selected_indices), NUM_LABELS))
|
|
356
|
+
for i, idx in enumerate(selected_indices):
|
|
357
|
+
label_idx = self.possible_labels.index(manual_labels[idx].strip().lower())
|
|
358
|
+
y[i, label_idx] = 1
|
|
359
|
+
|
|
360
|
+
# Compute features based on optimize_params
|
|
361
|
+
X = self.compute_features(llm_preds, selected_indices, optimize_params)
|
|
362
|
+
|
|
363
|
+
# Train linear regression model
|
|
364
|
+
model = LinearRegression(positive=True) # Ensure positive weights
|
|
365
|
+
model.fit(X, y)
|
|
366
|
+
|
|
367
|
+
# Extract weights from coefficients
|
|
368
|
+
coefficients = model.coef_
|
|
369
|
+
weights = np.sum(coefficients, axis=0)
|
|
370
|
+
|
|
371
|
+
# Initialize weights
|
|
372
|
+
optimal_llm_weights = None
|
|
373
|
+
optimal_mr_weights = None
|
|
374
|
+
|
|
375
|
+
# Extract and reshape weights based on optimize_params
|
|
376
|
+
if "LLM" in optimize_params and "MR" in optimize_params:
|
|
377
|
+
# Original case: optimize both LLM and MR
|
|
378
|
+
reshaped_weights = weights.reshape(NUM_LLMS, NUM_MRS, NUM_LABELS)
|
|
379
|
+
|
|
380
|
+
# Average across labels to get LLM and MR weights
|
|
381
|
+
optimal_llm_weights = np.mean(np.sum(reshaped_weights, axis=1), axis=1)
|
|
382
|
+
optimal_mr_weights = np.mean(np.sum(reshaped_weights, axis=0), axis=1)
|
|
383
|
+
|
|
384
|
+
elif "LLM" in optimize_params:
|
|
385
|
+
# Only optimize LLM weights
|
|
386
|
+
reshaped_weights = weights.reshape(NUM_LLMS, NUM_LABELS)
|
|
387
|
+
optimal_llm_weights = np.mean(reshaped_weights, axis=1)
|
|
388
|
+
|
|
389
|
+
# Use uniform weights for MRs
|
|
390
|
+
optimal_mr_weights = np.ones(NUM_MRS) / NUM_MRS
|
|
391
|
+
|
|
392
|
+
elif "MR" in optimize_params:
|
|
393
|
+
# Only optimize MR weights
|
|
394
|
+
reshaped_weights = weights.reshape(NUM_MRS, NUM_LABELS)
|
|
395
|
+
optimal_mr_weights = np.mean(reshaped_weights, axis=1)
|
|
396
|
+
|
|
397
|
+
# Use uniform weights for LLMs
|
|
398
|
+
optimal_llm_weights = np.ones(NUM_LLMS) / NUM_LLMS
|
|
399
|
+
|
|
400
|
+
# Normalize weights
|
|
401
|
+
if optimal_llm_weights is not None and np.sum(optimal_llm_weights) > 0:
|
|
402
|
+
optimal_llm_weights = optimal_llm_weights / np.sum(optimal_llm_weights)
|
|
403
|
+
|
|
404
|
+
if optimal_mr_weights is not None and np.sum(optimal_mr_weights) > 0:
|
|
405
|
+
optimal_mr_weights = optimal_mr_weights / np.sum(optimal_mr_weights)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
self.optimal_mr_weights = optimal_mr_weights
|
|
409
|
+
self.optimal_llm_weights = optimal_llm_weights
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def annotate(self, text):
|
|
413
|
+
text_mr1 = self.textMutator.MutateText(text=text, mr="passive_active")
|
|
414
|
+
text_mr2 = self.textMutator.MutateText(text=text, mr="double_negation")
|
|
415
|
+
text_mr3 = self.textMutator.MutateText(text=text, mr="synonym")
|
|
416
|
+
llm_preds = []
|
|
417
|
+
for annotator in self.annotators:
|
|
418
|
+
annotations = []
|
|
419
|
+
annotations.append(annotator.annotate(text)[0])
|
|
420
|
+
annotations.append(annotator.annotate(text_mr1)[0])
|
|
421
|
+
annotations.append(annotator.annotate(text_mr2)[0])
|
|
422
|
+
annotations.append(annotator.annotate(text_mr3)[0])
|
|
423
|
+
llm_preds.append(annotations)
|
|
424
|
+
|
|
425
|
+
confidences = self.get_pcs_label(llm_preds)
|
|
426
|
+
label_confidences = {}
|
|
427
|
+
for i in range(len(self.possible_labels)):
|
|
428
|
+
label_confidences[self.possible_labels[i]] = confidences[i]
|
|
429
|
+
return label_confidences
|
|
430
|
+
|
|
@@ -1,237 +0,0 @@
|
|
|
1
|
-
from .TextMutator import TextMutator
|
|
2
|
-
from .Annotator import Annotator
|
|
3
|
-
import pandas as pd
|
|
4
|
-
import os
|
|
5
|
-
import numpy as np
|
|
6
|
-
from scipy.optimize import differential_evolution
|
|
7
|
-
from tqdm import tqdm
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class PCS:
|
|
12
|
-
def __init__(self, prompt, dataset_path, annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "google/gemma-2-9b-it"], textmutator="llama-3.1-8b-instant", GROQ_API_KEY=None, OPENAI_API_KEY=None, ANTHROPIC_API_KEY=None, HUGGINGFACE_API_KEY=None, train=True):
|
|
13
|
-
self.prompt=prompt
|
|
14
|
-
if os.path.exists(dataset_path):
|
|
15
|
-
self.dataset_path = dataset_path
|
|
16
|
-
else:
|
|
17
|
-
raise FileNotFoundError(f"Invalid dataset path {dataset_path}")
|
|
18
|
-
self.annotator_model_names = annotators
|
|
19
|
-
self.annotators = []
|
|
20
|
-
|
|
21
|
-
if textmutator.startswith("llama"):
|
|
22
|
-
self.textMutator = TextMutator(model_name=textmutator, token=GROQ_API_KEY)
|
|
23
|
-
elif textmutator.startswith("gpt"):
|
|
24
|
-
self.textMutator = TextMutator(model_name=textmutator, token=OPENAI_API_KEY)
|
|
25
|
-
elif textmutator.startswith("claude"):
|
|
26
|
-
self.textMutator = TextMutator(model_name=textmutator, token=ANTHROPIC_API_KEY)
|
|
27
|
-
elif textmutator.startswith("mistral") or textmutator.startswith("google"):
|
|
28
|
-
self.textMutator = TextMutator(model_name=textmutator, token=HUGGINGFACE_API_KEY)
|
|
29
|
-
else:
|
|
30
|
-
raise ValueError(f"Unsupported text mutator model name: {textmutator}")
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
self.annotations_filename = self.dataset_path.rsplit(".csv", 1)[0] + "_annotations.csv"
|
|
34
|
-
self.dataset = pd.read_csv(dataset_path)
|
|
35
|
-
self.possible_labels = self.dataset["label"].unique().tolist()
|
|
36
|
-
for annotator_model_name in self.annotator_model_names:
|
|
37
|
-
if annotator_model_name.startswith("llama"):
|
|
38
|
-
token = GROQ_API_KEY
|
|
39
|
-
elif annotator_model_name.startswith("gpt"):
|
|
40
|
-
token = OPENAI_API_KEY
|
|
41
|
-
elif annotator_model_name.startswith("claude"):
|
|
42
|
-
token = ANTHROPIC_API_KEY
|
|
43
|
-
elif annotator_model_name.startswith("mistral") or annotator_model_name.startswith("google"):
|
|
44
|
-
token = HUGGINGFACE_API_KEY
|
|
45
|
-
else:
|
|
46
|
-
raise ValueError(f"Unsupported annotator model name: {annotator_model_name}")
|
|
47
|
-
|
|
48
|
-
self.annotators.append(Annotator(prompt=self.prompt, labels=self.possible_labels, model_name=annotator_model_name, token=token))
|
|
49
|
-
self.optimal_llm_weights = [1] * len(self.annotators)
|
|
50
|
-
self.optimal_mr_weights = [1] * 4
|
|
51
|
-
self.optimal_label_thresholds = [0.5] * len(self.possible_labels)
|
|
52
|
-
|
|
53
|
-
if train:
|
|
54
|
-
print("Labelling the dataset...")
|
|
55
|
-
self.create_annotations()
|
|
56
|
-
print("Generated the dataset annotations.")
|
|
57
|
-
|
|
58
|
-
print("Optimizing weights...")
|
|
59
|
-
self.PDE()
|
|
60
|
-
print("Done Optimizing weights.")
|
|
61
|
-
|
|
62
|
-
def create_annotations(self):
|
|
63
|
-
csv_filename = self.annotations_filename
|
|
64
|
-
|
|
65
|
-
if os.path.exists(csv_filename):
|
|
66
|
-
# Read the existing dataset
|
|
67
|
-
existing_df = pd.read_csv(csv_filename)
|
|
68
|
-
if not existing_df.empty:
|
|
69
|
-
last_index = existing_df.index[-1] + 1 # Get last index and continue from there
|
|
70
|
-
else:
|
|
71
|
-
last_index = 0
|
|
72
|
-
else:
|
|
73
|
-
columns = ["label", "text", "text_mr1", "text_mr2", "text_mr3"]
|
|
74
|
-
for annotator in self.annotators:
|
|
75
|
-
columns.append(annotator.model_name+"_text")
|
|
76
|
-
columns.append(annotator.model_name+"_text_mr1")
|
|
77
|
-
columns.append(annotator.model_name+"_text_mr2")
|
|
78
|
-
columns.append(annotator.model_name+"_text_mr3")
|
|
79
|
-
|
|
80
|
-
existing_df = pd.DataFrame(columns=columns)
|
|
81
|
-
existing_df.to_csv(csv_filename, index=False)
|
|
82
|
-
last_index = 0
|
|
83
|
-
|
|
84
|
-
with tqdm(total=len(self.dataset), initial=last_index, desc="Processing Annotations", unit="sample") as pbar:
|
|
85
|
-
|
|
86
|
-
for index in range(last_index, len(self.dataset)):
|
|
87
|
-
row = self.dataset.iloc[index]
|
|
88
|
-
label = row['label']
|
|
89
|
-
text = row['text']
|
|
90
|
-
text_mr1 = self.textMutator.MutateText(text=text, mr="passive_active")
|
|
91
|
-
text_mr2 = self.textMutator.MutateText(text=text, mr="double_negation")
|
|
92
|
-
text_mr3 = self.textMutator.MutateText(text=text, mr="synonym")
|
|
93
|
-
|
|
94
|
-
existing_df.at[index, "label"] = label
|
|
95
|
-
existing_df.at[index, "text"] = text
|
|
96
|
-
existing_df.at[index, "text_mr1"] = text_mr1
|
|
97
|
-
existing_df.at[index, "text_mr2"] = text_mr2
|
|
98
|
-
existing_df.at[index, "text_mr3"] = text_mr3
|
|
99
|
-
|
|
100
|
-
for annotator in self.annotators:
|
|
101
|
-
existing_df.at[index, annotator.model_name+"_text"] = annotator.annotate(text)[0]
|
|
102
|
-
existing_df.at[index, annotator.model_name+"_text_mr1"] = annotator.annotate(text_mr1)[0]
|
|
103
|
-
existing_df.at[index, annotator.model_name+"_text_mr2"] = annotator.annotate(text_mr2)[0]
|
|
104
|
-
existing_df.at[index, annotator.model_name+"_text_mr3"] = annotator.annotate(text_mr3)[0]
|
|
105
|
-
|
|
106
|
-
row_df = existing_df.iloc[[index]]
|
|
107
|
-
row_df.to_csv(csv_filename, mode='a', index=False, header=not os.path.exists(csv_filename))
|
|
108
|
-
|
|
109
|
-
pbar.update(1) # Update progress bar
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
def get_majority_vote_label(self, majority_votes, possible_labels=None):
|
|
113
|
-
if not possible_labels:
|
|
114
|
-
possible_labels = self.possible_labels
|
|
115
|
-
|
|
116
|
-
vote_counts = {label.strip().lower(): 0 for label in possible_labels}
|
|
117
|
-
|
|
118
|
-
for vote in majority_votes:
|
|
119
|
-
if not pd.isna(vote):
|
|
120
|
-
lowered_vote = vote.strip().lower()
|
|
121
|
-
if lowered_vote in vote_counts:
|
|
122
|
-
vote_counts[lowered_vote] += 1
|
|
123
|
-
|
|
124
|
-
max_votes = max(vote_counts.values())
|
|
125
|
-
|
|
126
|
-
for label, count in vote_counts.items():
|
|
127
|
-
if count == max_votes:
|
|
128
|
-
return label
|
|
129
|
-
|
|
130
|
-
def get_pcs_label(self, llm_labels, w_llms=None, w_mrs=None, label_thresholds=None, possible_labels=None):
|
|
131
|
-
if possible_labels is None:
|
|
132
|
-
possible_labels = self.possible_labels
|
|
133
|
-
if w_llms is None:
|
|
134
|
-
w_llms = self.optimal_llm_weights
|
|
135
|
-
if w_mrs is None:
|
|
136
|
-
w_mrs = self.optimal_mr_weights
|
|
137
|
-
if label_thresholds is None:
|
|
138
|
-
label_thresholds = self.optimal_label_thresholds
|
|
139
|
-
|
|
140
|
-
num_labels = len(possible_labels)
|
|
141
|
-
pcs_labels = [0] * num_labels
|
|
142
|
-
|
|
143
|
-
for i in range(len(w_llms)):
|
|
144
|
-
pcs_label_llm = [0] * num_labels
|
|
145
|
-
for j in range(len(llm_labels[i])): #Iterate through MR labels
|
|
146
|
-
for k in range(len(pcs_label_llm)):
|
|
147
|
-
if not pd.isna(llm_labels[i][j]):
|
|
148
|
-
if llm_labels[i][j].strip().lower() == possible_labels[k].strip().lower():
|
|
149
|
-
pcs_label_llm[k] += w_mrs[j]
|
|
150
|
-
|
|
151
|
-
for j in range(len(pcs_label_llm)):
|
|
152
|
-
# pcs_label_llm[j] = pcs_label_llm[j]/sum(w_mrs)
|
|
153
|
-
if sum(w_mrs) != 0:
|
|
154
|
-
pcs_label_llm[j] = pcs_label_llm[j] / sum(w_mrs)
|
|
155
|
-
else:
|
|
156
|
-
pcs_label_llm[j] = 0
|
|
157
|
-
|
|
158
|
-
for j in range(len(pcs_label_llm)):
|
|
159
|
-
pcs_labels[j] += w_llms[i] * pcs_label_llm[j]
|
|
160
|
-
|
|
161
|
-
for i in range(num_labels):
|
|
162
|
-
if sum(w_llms) != 0:
|
|
163
|
-
pcs_labels[i] = pcs_labels[i]/sum(w_llms)
|
|
164
|
-
else:
|
|
165
|
-
pcs_labels[i] = 0
|
|
166
|
-
|
|
167
|
-
for i in range(num_labels):
|
|
168
|
-
if pcs_labels[i] > label_thresholds[i]:
|
|
169
|
-
final_pred = possible_labels[i]
|
|
170
|
-
return final_pred
|
|
171
|
-
|
|
172
|
-
majority_votes = []
|
|
173
|
-
for i in range(len(w_llms)):
|
|
174
|
-
majority_votes.append(llm_labels[i][0])
|
|
175
|
-
|
|
176
|
-
return self.get_majority_vote_label(majority_votes, possible_labels)
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
def Objective(self, params, llm_preds, NUM_LLMS, NUM_MRS, manual_labels):
|
|
180
|
-
w_mrs = params[:NUM_MRS] # Weights for 4 MRs
|
|
181
|
-
w_llms = params[NUM_MRS:NUM_MRS+NUM_LLMS] # Weights for 3 LLMs
|
|
182
|
-
label_thresholds = params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
|
|
183
|
-
predictions = []
|
|
184
|
-
|
|
185
|
-
predictions = [
|
|
186
|
-
self.get_pcs_label(llm_preds[i, :], w_llms, w_mrs, label_thresholds)
|
|
187
|
-
for i in range(len(manual_labels))
|
|
188
|
-
]
|
|
189
|
-
|
|
190
|
-
# Calculate accuracy
|
|
191
|
-
accuracy = np.mean([
|
|
192
|
-
manual_labels[i].strip().lower() == predictions[i].strip().lower()
|
|
193
|
-
for i in range(len(manual_labels))
|
|
194
|
-
])
|
|
195
|
-
return -accuracy # We want to maximize accuracy, so we minimize negative accuracy
|
|
196
|
-
|
|
197
|
-
def PDE(self):
|
|
198
|
-
if os.path.exists(self.annotations_filename):
|
|
199
|
-
df = pd.read_csv(self.annotations_filename)
|
|
200
|
-
else:
|
|
201
|
-
return
|
|
202
|
-
# Define model column mappings
|
|
203
|
-
model_columns = []
|
|
204
|
-
for annotator in self.annotators:
|
|
205
|
-
model_columns.append(df[[f"{annotator.model_name}_text", f"{annotator.model_name}_text_mr1", f"{annotator.model_name}_text_mr2", f"{annotator.model_name}_text_mr3"]])
|
|
206
|
-
llm_preds = np.stack(model_columns, axis=1)
|
|
207
|
-
|
|
208
|
-
manual_labels = df['label'].values
|
|
209
|
-
size, NUM_LLMS, NUM_MRS = llm_preds.shape[:3]
|
|
210
|
-
|
|
211
|
-
bounds = [(0, 1)] * (NUM_LLMS + NUM_MRS + len(self.possible_labels))
|
|
212
|
-
|
|
213
|
-
result = differential_evolution(self.Objective, bounds, args=(llm_preds, NUM_LLMS, NUM_MRS, manual_labels))
|
|
214
|
-
|
|
215
|
-
optimal_params = result.x
|
|
216
|
-
|
|
217
|
-
self.optimal_mr_weights = optimal_params[:NUM_MRS]
|
|
218
|
-
self.optimal_llm_weights = optimal_params[NUM_MRS:NUM_MRS+NUM_LLMS]
|
|
219
|
-
self.optimal_label_thresholds = optimal_params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
|
|
220
|
-
self.Accuracy = -result.fun
|
|
221
|
-
|
|
222
|
-
def annotate(self, text):
|
|
223
|
-
text_mr1 = self.textMutator.MutateText(text=text, mr="passive_active")
|
|
224
|
-
text_mr2 = self.textMutator.MutateText(text=text, mr="double_negation")
|
|
225
|
-
text_mr3 = self.textMutator.MutateText(text=text, mr="synonym")
|
|
226
|
-
llm_preds = []
|
|
227
|
-
for annotator in self.annotators:
|
|
228
|
-
annotations = []
|
|
229
|
-
annotations.append(annotator.annotate(text)[0])
|
|
230
|
-
annotations.append(annotator.annotate(text_mr1)[0])
|
|
231
|
-
annotations.append(annotator.annotate(text_mr2)[0])
|
|
232
|
-
annotations.append(annotator.annotate(text_mr3)[0])
|
|
233
|
-
llm_preds.append(annotations)
|
|
234
|
-
|
|
235
|
-
pcs_label = self.get_pcs_label(llm_preds)
|
|
236
|
-
return pcs_label
|
|
237
|
-
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|