pcs-annotator 0.1.3__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.3
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
@@ -43,6 +43,9 @@ Respond only with the label and the reasoning.
43
43
  """
44
44
  ```
45
45
 
46
+ ### Training Dataset Path (`dataset_path`)
47
+
48
+ You will need a CSV file with two columns: `label` and `text` to ensure better annotation, as the data is used to train the LLMs.
46
49
 
47
50
 
48
51
 
@@ -53,7 +56,7 @@ The `PCS` class allows you to customize various hyperparameters, including the c
53
56
 
54
57
  ### 📌 Example Usage
55
58
  ```python
56
- PCS(
59
+ pcs = PCS(
57
60
  prompt="Your classification prompt here",
58
61
  dataset_path="path/to/dataset.csv",
59
62
  annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "google/gemma-2-9b-it"],
@@ -61,15 +64,14 @@ PCS(
61
64
  GROQ_API_KEY=None,
62
65
  OPENAI_API_KEY=None,
63
66
  ANTHROPIC_API_KEY=None,
64
- HUGGINGFACE_API_KEY=None
67
+ HUGGINGFACE_API_KEY=None,
68
+ train=True
65
69
  )
70
+
71
+ print(pcs.annotate("America is a country"))
66
72
  ```
67
73
 
68
74
  # Configuration
69
- ## 🔹 Training Dataset (`dataset_path`)
70
-
71
- You will need a CSV file with two columns: `label` and `text` to ensure better annotation, as the data is used to train the LLMs.
72
-
73
75
 
74
76
  ## 🔹 Annotators (`annotators`)
75
77
  Defines the list of LLMs used for annotation.
@@ -97,12 +99,8 @@ To access certain LLM models, you need to provide API keys. These can be passed
97
99
  | `HUGGINGFACE_API_KEY` | Required for **Mistral and Google Gemma models**. |
98
100
 
99
101
 
100
-
101
-
102
-
103
-
104
-
105
- ### Annotate a New Text
106
-
107
- ```python
108
- print(pcs.annotate("America is a country"))
102
+ ## 🔹 Continue the Training (`train`)
103
+ Determines whether to continue optimizing weights using more data or not
104
+ * **Default Value**: `True`
105
+ * **Customization**:
106
+ * You can change to `False`
@@ -22,6 +22,9 @@ Respond only with the label and the reasoning.
22
22
  """
23
23
  ```
24
24
 
25
+ ### Training Dataset Path (`dataset_path`)
26
+
27
+ You will need a CSV file with two columns: `label` and `text` to ensure better annotation, as the data is used to train the LLMs.
25
28
 
26
29
 
27
30
 
@@ -32,7 +35,7 @@ The `PCS` class allows you to customize various hyperparameters, including the c
32
35
 
33
36
  ### 📌 Example Usage
34
37
  ```python
35
- PCS(
38
+ pcs = PCS(
36
39
  prompt="Your classification prompt here",
37
40
  dataset_path="path/to/dataset.csv",
38
41
  annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "google/gemma-2-9b-it"],
@@ -40,15 +43,14 @@ PCS(
40
43
  GROQ_API_KEY=None,
41
44
  OPENAI_API_KEY=None,
42
45
  ANTHROPIC_API_KEY=None,
43
- HUGGINGFACE_API_KEY=None
46
+ HUGGINGFACE_API_KEY=None,
47
+ train=True
44
48
  )
49
+
50
+ print(pcs.annotate("America is a country"))
45
51
  ```
46
52
 
47
53
  # Configuration
48
- ## 🔹 Training Dataset (`dataset_path`)
49
-
50
- You will need a CSV file with two columns: `label` and `text` to ensure better annotation, as the data is used to train the LLMs.
51
-
52
54
 
53
55
  ## 🔹 Annotators (`annotators`)
54
56
  Defines the list of LLMs used for annotation.
@@ -76,12 +78,8 @@ To access certain LLM models, you need to provide API keys. These can be passed
76
78
  | `HUGGINGFACE_API_KEY` | Required for **Mistral and Google Gemma models**. |
77
79
 
78
80
 
79
-
80
-
81
-
82
-
83
-
84
- ### Annotate a New Text
85
-
86
- ```python
87
- print(pcs.annotate("America is a country"))
81
+ ## 🔹 Continue the Training (`train`)
82
+ Determines whether to continue optimizing weights using more data or not
83
+ * **Default Value**: `True`
84
+ * **Customization**:
85
+ * You can change to `False`
@@ -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.3"
8
+ version = "0.1.5"
9
9
  authors = [
10
10
  { name = "Sina Salimian", email = "sina99.sn@gmail.com" }
11
11
  ]
@@ -1,234 +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):
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
- print("Labelling the dataset...")
54
- self.create_annotations()
55
- print("Generated the dataset annotations.")
56
-
57
- print("Optimizing weights...")
58
- self.PDE()
59
- print("Done Optimizing weights.")
60
-
61
- def create_annotations(self):
62
- csv_filename = self.annotations_filename
63
-
64
- if os.path.exists(csv_filename):
65
- # Read the existing dataset
66
- existing_df = pd.read_csv(csv_filename)
67
- if not existing_df.empty:
68
- last_index = existing_df.index[-1] + 1 # Get last index and continue from there
69
- else:
70
- last_index = 0
71
- else:
72
- columns = ["label", "text", "text_mr1", "text_mr2", "text_mr3"]
73
- for annotator in self.annotators:
74
- columns.append(annotator.model_name+"_text")
75
- columns.append(annotator.model_name+"_text_mr1")
76
- columns.append(annotator.model_name+"_text_mr2")
77
- columns.append(annotator.model_name+"_text_mr3")
78
-
79
- existing_df = pd.DataFrame(columns=columns)
80
- existing_df.to_csv(csv_filename, index=False)
81
- last_index = 0
82
-
83
- with tqdm(total=len(self.dataset), initial=last_index, desc="Processing Annotations", unit="sample") as pbar:
84
-
85
- for index in range(last_index, len(self.dataset)):
86
- row = self.dataset.iloc[index]
87
- label = row['label']
88
- text = row['text']
89
- text_mr1 = self.textMutator.MutateText(text=text, mr="passive_active")
90
- text_mr2 = self.textMutator.MutateText(text=text, mr="double_negation")
91
- text_mr3 = self.textMutator.MutateText(text=text, mr="synonym")
92
-
93
- existing_df.at[index, "label"] = label
94
- existing_df.at[index, "text"] = text
95
- existing_df.at[index, "text_mr1"] = text_mr1
96
- existing_df.at[index, "text_mr2"] = text_mr2
97
- existing_df.at[index, "text_mr3"] = text_mr3
98
-
99
- for annotator in self.annotators:
100
- existing_df.at[index, annotator.model_name+"_text"] = annotator.annotate(text)[0]
101
- existing_df.at[index, annotator.model_name+"_text_mr1"] = annotator.annotate(text_mr1)[0]
102
- existing_df.at[index, annotator.model_name+"_text_mr2"] = annotator.annotate(text_mr2)[0]
103
- existing_df.at[index, annotator.model_name+"_text_mr3"] = annotator.annotate(text_mr3)[0]
104
-
105
- row_df = existing_df.iloc[[index]]
106
- row_df.to_csv(csv_filename, mode='a', index=False, header=not os.path.exists(csv_filename))
107
-
108
- pbar.update(1) # Update progress bar
109
-
110
-
111
- def get_majority_vote_label(self, majority_votes, possible_labels=None):
112
- if not possible_labels:
113
- possible_labels = self.possible_labels
114
-
115
- vote_counts = {label.strip().lower(): 0 for label in possible_labels}
116
-
117
- for vote in majority_votes:
118
- if not pd.isna(vote):
119
- lowered_vote = vote.strip().lower()
120
- if lowered_vote in vote_counts:
121
- vote_counts[lowered_vote] += 1
122
-
123
- max_votes = max(vote_counts.values())
124
-
125
- for label, count in vote_counts.items():
126
- if count == max_votes:
127
- return label
128
-
129
- def get_pcs_label(self, llm_labels, w_llms=None, w_mrs=None, label_thresholds=None, possible_labels=None):
130
- if possible_labels is None:
131
- possible_labels = self.possible_labels
132
- if w_llms is None:
133
- w_llms = self.optimal_llm_weights
134
- if w_mrs is None:
135
- w_mrs = self.optimal_mr_weights
136
- if label_thresholds is None:
137
- label_thresholds = self.optimal_label_thresholds
138
-
139
- num_labels = len(possible_labels)
140
- pcs_labels = [0] * num_labels
141
-
142
- for i in range(len(w_llms)):
143
- pcs_label_llm = [0] * num_labels
144
- for j in range(len(llm_labels[i])): #Iterate through MR labels
145
- for k in range(len(pcs_label_llm)):
146
- if not pd.isna(llm_labels[i][j]):
147
- if llm_labels[i][j].strip().lower() == possible_labels[k].strip().lower():
148
- pcs_label_llm[k] += w_mrs[j]
149
-
150
- for j in range(len(pcs_label_llm)):
151
- # pcs_label_llm[j] = pcs_label_llm[j]/sum(w_mrs)
152
- if sum(w_mrs) != 0:
153
- pcs_label_llm[j] = pcs_label_llm[j] / sum(w_mrs)
154
- else:
155
- pcs_label_llm[j] = 0
156
-
157
- for j in range(len(pcs_label_llm)):
158
- pcs_labels[j] += w_llms[i] * pcs_label_llm[j]
159
-
160
- for i in range(num_labels):
161
- if sum(w_llms) != 0:
162
- pcs_labels[i] = pcs_labels[i]/sum(w_llms)
163
- else:
164
- pcs_labels[i] = 0
165
-
166
- for i in range(num_labels):
167
- if pcs_labels[i] > label_thresholds[i]:
168
- final_pred = possible_labels[i]
169
- return final_pred
170
-
171
- majority_votes = []
172
- for i in range(len(w_llms)):
173
- majority_votes.append(llm_labels[i][0])
174
-
175
- return self.get_majority_vote_label(majority_votes, possible_labels)
176
-
177
-
178
- def Objective(self, params, llm_preds, NUM_LLMS, NUM_MRS, manual_labels):
179
- w_mrs = params[:NUM_MRS] # Weights for 4 MRs
180
- w_llms = params[NUM_MRS:NUM_MRS+NUM_LLMS] # Weights for 3 LLMs
181
- label_thresholds = params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
182
- predictions = []
183
-
184
- predictions = [
185
- self.get_pcs_label(llm_preds[i, :], w_llms, w_mrs, label_thresholds)
186
- for i in range(len(manual_labels))
187
- ]
188
-
189
- # Calculate accuracy
190
- accuracy = np.mean([
191
- manual_labels[i].strip().lower() == predictions[i].strip().lower()
192
- for i in range(len(manual_labels))
193
- ])
194
- return -accuracy # We want to maximize accuracy, so we minimize negative accuracy
195
-
196
- def PDE(self):
197
- df = pd.read_csv(self.annotations_filename)
198
-
199
- # Define model column mappings
200
- model_columns = []
201
- for annotator in self.annotators:
202
- 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"]])
203
- llm_preds = np.stack(model_columns, axis=1)
204
-
205
- manual_labels = df['label'].values
206
- size, NUM_LLMS, NUM_MRS = llm_preds.shape[:3]
207
-
208
- bounds = [(0, 1)] * (NUM_LLMS + NUM_MRS + len(self.possible_labels))
209
-
210
- result = differential_evolution(self.Objective, bounds, args=(llm_preds, NUM_LLMS, NUM_MRS, manual_labels))
211
-
212
- optimal_params = result.x
213
-
214
- self.optimal_mr_weights = optimal_params[:NUM_MRS]
215
- self.optimal_llm_weights = optimal_params[NUM_MRS:NUM_MRS+NUM_LLMS]
216
- self.optimal_label_thresholds = optimal_params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
217
- self.Accuracy = -result.fun
218
-
219
- def annotate(self, text):
220
- text_mr1 = self.textMutator.MutateText(text=text, mr="passive_active")
221
- text_mr2 = self.textMutator.MutateText(text=text, mr="double_negation")
222
- text_mr3 = self.textMutator.MutateText(text=text, mr="synonym")
223
- llm_preds = []
224
- for annotator in self.annotators:
225
- annotations = []
226
- annotations.append(annotator.annotate(text)[0])
227
- annotations.append(annotator.annotate(text_mr1)[0])
228
- annotations.append(annotator.annotate(text_mr2)[0])
229
- annotations.append(annotator.annotate(text_mr3)[0])
230
- llm_preds.append(annotations)
231
-
232
- pcs_label = self.get_pcs_label(llm_preds)
233
- return pcs_label
234
-
File without changes