pcs-annotator 0.1.4__tar.gz → 0.1.5__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pcs-annotator
3
- Version: 0.1.4
3
+ Version: 0.1.5
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,449 @@
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
+ # Step 1: Rank MRs based on their weights
192
+ mrs_indices = np.argsort(w_mrs)[::-1] # Sort in descending order
193
+
194
+ # Get the labels from each MR for this LLM
195
+ mr_predictions = [llm_labels[i][j].strip().lower() for j in range(len(w_mrs))]
196
+
197
+ # Reorder predictions by MR weight
198
+ ranked_predictions = [mr_predictions[j] for j in mrs_indices]
199
+
200
+ # Step 2-4: Implement the voting logic for 4 MRs
201
+ selected_label = None
202
+
203
+ # Check if top two MRs choose the same label
204
+ if ranked_predictions[0] == ranked_predictions[1]:
205
+ selected_label = ranked_predictions[0]
206
+ # Check if the other two MRs (3rd and 4th) choose the same label
207
+ elif ranked_predictions[2] == ranked_predictions[3]:
208
+ selected_label = ranked_predictions[2]
209
+ else:
210
+ # Default to first (highest weighted) MR's label
211
+ selected_label = ranked_predictions[0]
212
+
213
+ # Convert the selected label to one-hot encoding
214
+ pcs_label_llm = np.zeros(num_labels)
215
+ if selected_label:
216
+ for k in range(num_labels):
217
+ if selected_label == possible_labels[k].strip().lower():
218
+ pcs_label_llm[k] = 1.0
219
+ break
220
+
221
+ # Weight by LLM weights and accumulate
222
+ pcs_labels += w_llms[i] * pcs_label_llm
223
+
224
+ # Normalize by sum of LLM weights
225
+ if sum(w_llms) != 0:
226
+ pcs_labels = pcs_labels / sum(w_llms)
227
+
228
+ return pcs_labels
229
+
230
+ def Objective(self, params, llm_preds, NUM_LLMS, NUM_MRS, manual_labels):
231
+ w_mrs = params[:NUM_MRS] # Weights for 4 MRs
232
+ w_llms = params[NUM_MRS:NUM_MRS+NUM_LLMS] # Weights for 3 LLMs
233
+ label_thresholds = params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
234
+ predictions = []
235
+
236
+ predictions = [
237
+ self.get_pcs_label(llm_preds[i, :], w_llms, w_mrs, label_thresholds)
238
+ for i in range(len(manual_labels))
239
+ ]
240
+
241
+ # Calculate accuracy
242
+ accuracy = np.mean([
243
+ manual_labels[i].strip().lower() == predictions[i].strip().lower()
244
+ for i in range(len(manual_labels))
245
+ ])
246
+ return -accuracy # We want to maximize accuracy, so we minimize negative accuracy
247
+
248
+ def PDE(self):
249
+ if os.path.exists(self.annotations_filename):
250
+ df = pd.read_csv(self.annotations_filename)
251
+ else:
252
+ return
253
+ # Define model column mappings
254
+ model_columns = []
255
+ for annotator in self.annotators:
256
+ 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"]])
257
+ llm_preds = np.stack(model_columns, axis=1)
258
+
259
+ manual_labels = df['label'].values
260
+ size, NUM_LLMS, NUM_MRS = llm_preds.shape[:3]
261
+
262
+ bounds = [(0, 1)] * (NUM_LLMS + NUM_MRS + len(self.possible_labels))
263
+
264
+ result = differential_evolution(self.Objective, bounds, args=(llm_preds, NUM_LLMS, NUM_MRS, manual_labels))
265
+
266
+ optimal_params = result.x
267
+
268
+ self.optimal_mr_weights = optimal_params[:NUM_MRS]
269
+ self.optimal_llm_weights = optimal_params[NUM_MRS:NUM_MRS+NUM_LLMS]
270
+ self.optimal_label_thresholds = optimal_params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
271
+ self.Accuracy = -result.fun
272
+
273
+
274
+ def compute_features(self, llm_preds, selected_indices, optimize_params=["LLM", "MR"]):
275
+ """
276
+ Compute feature matrix for linear regression.
277
+ Each row represents an example, and columns represent feature combinations based on optimize_params.
278
+
279
+ Args:
280
+ llm_preds: Predictions from LLMs (shape: [n_samples, n_llms, n_mrs])
281
+ labels: List of possible label categories
282
+ selected_indices: Indices of samples to use
283
+ optimize_params: List of parameters to optimize (can include "LLM", "MR")
284
+ """
285
+ num_examples = len(selected_indices)
286
+ num_llms = llm_preds.shape[1]
287
+ num_mrs = llm_preds.shape[2]
288
+ num_labels = len(self.possible_labels)
289
+
290
+ # Determine feature structure based on optimize_params
291
+ if "LLM" in optimize_params and "MR" in optimize_params:
292
+ # Original case: optimize both LLM and MR
293
+ feature_dim = num_llms * num_mrs * num_labels
294
+
295
+ # Initialize feature matrix
296
+ X = np.zeros((num_examples, feature_dim))
297
+
298
+ for idx, sample_idx in enumerate(selected_indices):
299
+ for i in range(num_llms):
300
+ for j in range(num_mrs):
301
+ for k, label in enumerate(self.possible_labels):
302
+ # Check if this LLM-MR combination predicts this label
303
+ if llm_preds[sample_idx, i, j].strip().lower() == label.strip().lower():
304
+ feature_idx = i * (num_mrs * num_labels) + j * num_labels + k
305
+ X[idx, feature_idx] = 1
306
+
307
+ elif "LLM" in optimize_params:
308
+ # Only optimize LLM weights
309
+ feature_dim = num_llms * num_labels
310
+
311
+ # Initialize feature matrix
312
+ X = np.zeros((num_examples, feature_dim))
313
+
314
+ for idx, sample_idx in enumerate(selected_indices):
315
+ for i in range(num_llms):
316
+ # Aggregate across all MRs for each LLM
317
+ llm_preds_aggregated = []
318
+ for j in range(num_mrs):
319
+ llm_preds_aggregated.append(llm_preds[sample_idx, i, j].strip().lower())
320
+
321
+ for k, label in enumerate(self.possible_labels):
322
+ # Count how many times this LLM predicts this label across MRs
323
+ count = llm_preds_aggregated.count(label.strip().lower())
324
+ if count > 0:
325
+ feature_idx = i * num_labels + k
326
+ X[idx, feature_idx] = count / num_mrs # Normalize by number of MRs
327
+
328
+ elif "MR" in optimize_params:
329
+ # Only optimize MR weights
330
+ feature_dim = num_mrs * num_labels
331
+
332
+ # Initialize feature matrix
333
+ X = np.zeros((num_examples, feature_dim))
334
+
335
+ for idx, sample_idx in enumerate(selected_indices):
336
+ for j in range(num_mrs):
337
+ # Aggregate across all LLMs for each MR
338
+ mr_preds_aggregated = []
339
+ for i in range(num_llms):
340
+ mr_preds_aggregated.append(llm_preds[sample_idx, i, j].strip().lower())
341
+
342
+ for k, label in enumerate(self.possible_labels):
343
+ # Count how many times this MR predicts this label across LLMs
344
+ count = mr_preds_aggregated.count(label.strip().lower())
345
+ if count > 0:
346
+ feature_idx = j * num_labels + k
347
+ X[idx, feature_idx] = count / num_llms # Normalize by number of LLMs
348
+ else:
349
+ # If optimize_params is empty or contains invalid parameters, default to both
350
+ return self.compute_features(llm_preds, selected_indices, ["LLM", "MR"])
351
+
352
+ return X
353
+
354
+ def LR(self):
355
+ if os.path.exists(self.annotations_filename):
356
+ df = pd.read_csv(self.annotations_filename)
357
+ else:
358
+ return
359
+ # Define model column mappings
360
+ model_columns = []
361
+ for annotator in self.annotators:
362
+ 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"]])
363
+ llm_preds = np.stack(model_columns, axis=1)
364
+
365
+ manual_labels = df['label'].values
366
+ size, NUM_LLMS, NUM_MRS = llm_preds.shape[:3]
367
+
368
+ NUM_LABELS = len(self.possible_labels)
369
+ optimize_params = ["LLM", "MR"]
370
+ N_samples = llm_preds.shape[0]
371
+ selected_indices = np.random.choice(N_samples, size, replace=False)
372
+
373
+ # Prepare target variable (one-hot encoded labels)
374
+ y = np.zeros((len(selected_indices), NUM_LABELS))
375
+ for i, idx in enumerate(selected_indices):
376
+ label_idx = self.possible_labels.index(manual_labels[idx].strip().lower())
377
+ y[i, label_idx] = 1
378
+
379
+ # Compute features based on optimize_params
380
+ X = self.compute_features(llm_preds, selected_indices, optimize_params)
381
+
382
+ # Train linear regression model
383
+ model = LinearRegression(positive=True) # Ensure positive weights
384
+ model.fit(X, y)
385
+
386
+ # Extract weights from coefficients
387
+ coefficients = model.coef_
388
+ weights = np.sum(coefficients, axis=0)
389
+
390
+ # Initialize weights
391
+ optimal_llm_weights = None
392
+ optimal_mr_weights = None
393
+
394
+ # Extract and reshape weights based on optimize_params
395
+ if "LLM" in optimize_params and "MR" in optimize_params:
396
+ # Original case: optimize both LLM and MR
397
+ reshaped_weights = weights.reshape(NUM_LLMS, NUM_MRS, NUM_LABELS)
398
+
399
+ # Average across labels to get LLM and MR weights
400
+ optimal_llm_weights = np.mean(np.sum(reshaped_weights, axis=1), axis=1)
401
+ optimal_mr_weights = np.mean(np.sum(reshaped_weights, axis=0), axis=1)
402
+
403
+ elif "LLM" in optimize_params:
404
+ # Only optimize LLM weights
405
+ reshaped_weights = weights.reshape(NUM_LLMS, NUM_LABELS)
406
+ optimal_llm_weights = np.mean(reshaped_weights, axis=1)
407
+
408
+ # Use uniform weights for MRs
409
+ optimal_mr_weights = np.ones(NUM_MRS) / NUM_MRS
410
+
411
+ elif "MR" in optimize_params:
412
+ # Only optimize MR weights
413
+ reshaped_weights = weights.reshape(NUM_MRS, NUM_LABELS)
414
+ optimal_mr_weights = np.mean(reshaped_weights, axis=1)
415
+
416
+ # Use uniform weights for LLMs
417
+ optimal_llm_weights = np.ones(NUM_LLMS) / NUM_LLMS
418
+
419
+ # Normalize weights
420
+ if optimal_llm_weights is not None and np.sum(optimal_llm_weights) > 0:
421
+ optimal_llm_weights = optimal_llm_weights / np.sum(optimal_llm_weights)
422
+
423
+ if optimal_mr_weights is not None and np.sum(optimal_mr_weights) > 0:
424
+ optimal_mr_weights = optimal_mr_weights / np.sum(optimal_mr_weights)
425
+
426
+
427
+ self.optimal_mr_weights = optimal_mr_weights
428
+ self.optimal_llm_weights = optimal_llm_weights
429
+
430
+
431
+ def annotate(self, text):
432
+ text_mr1 = self.textMutator.MutateText(text=text, mr="passive_active")
433
+ text_mr2 = self.textMutator.MutateText(text=text, mr="double_negation")
434
+ text_mr3 = self.textMutator.MutateText(text=text, mr="synonym")
435
+ llm_preds = []
436
+ for annotator in self.annotators:
437
+ annotations = []
438
+ annotations.append(annotator.annotate(text)[0])
439
+ annotations.append(annotator.annotate(text_mr1)[0])
440
+ annotations.append(annotator.annotate(text_mr2)[0])
441
+ annotations.append(annotator.annotate(text_mr3)[0])
442
+ llm_preds.append(annotations)
443
+
444
+ confidences = self.get_pcs_label(llm_preds)
445
+ label_confidences = {}
446
+ for i in range(len(self.possible_labels)):
447
+ label_confidences[self.possible_labels[i]] = confidences[i]
448
+ return label_confidences
449
+
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
5
5
 
6
6
  [project]
7
7
  name = "pcs-annotator"
8
- version = "0.1.4"
8
+ version = "0.1.5"
9
9
  authors = [
10
10
  { name = "Sina Salimian", email = "sina99.sn@gmail.com" }
11
11
  ]
@@ -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