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+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
|
4 |
+
import torch
|
5 |
+
from torch.utils.data import Dataset
|
6 |
+
from torch.utils.data import DataLoader
|
7 |
+
from transformers import RobertaTokenizer, RobertaForSequenceClassification
|
8 |
+
import pandas as pd
|
9 |
+
|
10 |
+
#from sklearn.linear_model import LogisticRegression
|
11 |
+
#from sklearn.metrics import accuracy_score, confusion_matrix
|
12 |
+
#import matplotlib.pyplot as plt
|
13 |
+
import seaborn as sns
|
14 |
+
#import numpy as np
|
15 |
+
import sys
|
16 |
+
import torch.nn.functional as F
|
17 |
+
#from torch.nn import CrossEntropyLoss
|
18 |
+
#from sklearn.decomposition import PCA
|
19 |
+
import matplotlib.pyplot as plt
|
20 |
+
|
21 |
+
if len(sys.argv) > 1:
|
22 |
+
# sys.argv[0] is the script name, sys.argv[1] is the first argument, etc.
|
23 |
+
runModel = sys.argv[1]
|
24 |
+
print(f"Passed value: {runModel}")
|
25 |
+
print (sys.argv[2])
|
26 |
+
|
27 |
+
else:
|
28 |
+
print("No argument was passed.")
|
29 |
+
|
30 |
+
|
31 |
+
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
|
32 |
+
modelNameToUse = sys.argv[2]
|
33 |
+
|
34 |
+
if (runModel=='1'):
|
35 |
+
dataFileName = sys.argv[2] + '.csv'
|
36 |
+
print (dataFileName)
|
37 |
+
# Load the data from the CSV file
|
38 |
+
df = pd.read_csv(dataFileName)
|
39 |
+
# Access the text and labels
|
40 |
+
texts = df['text'].tolist()
|
41 |
+
labels = df['label'].tolist()
|
42 |
+
|
43 |
+
print('Train Model')
|
44 |
+
# Encode the labels
|
45 |
+
sorted_labels = sorted(df['label'].unique())
|
46 |
+
label_mapping = {label: i for i, label in enumerate(sorted_labels)}
|
47 |
+
df['label'] = df['label'].map(label_mapping)
|
48 |
+
print(df['label'])
|
49 |
+
# Train/test split
|
50 |
+
train_df, test_df = train_test_split(df, test_size=0.2, random_state=42)
|
51 |
+
|
52 |
+
# Tokenization
|
53 |
+
tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
|
54 |
+
|
55 |
+
# Model and training setup
|
56 |
+
model = RobertaForSequenceClassification.from_pretrained('roberta-base', output_attentions=True, num_labels=len(label_mapping)).to('cpu')
|
57 |
+
|
58 |
+
model.resize_token_embeddings(len(tokenizer))
|
59 |
+
|
60 |
+
train_encodings = tokenizer(list(train_df['text']), truncation=True, padding=True, max_length=64)
|
61 |
+
test_encodings = tokenizer(list(test_df['text']), truncation=True, padding=True, max_length=64)
|
62 |
+
|
63 |
+
# Dataset class
|
64 |
+
class IntentDataset(Dataset):
|
65 |
+
def __init__(self, encodings, labels):
|
66 |
+
|
67 |
+
self.encodings = encodings
|
68 |
+
self.labels = labels
|
69 |
+
|
70 |
+
def __getitem__(self, idx):
|
71 |
+
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
|
72 |
+
label = self.labels[idx]
|
73 |
+
item['labels'] = torch.tensor(self.labels[idx])
|
74 |
+
|
75 |
+
|
76 |
+
return item
|
77 |
+
|
78 |
+
def __len__(self):
|
79 |
+
return len(self.labels)
|
80 |
+
|
81 |
+
train_dataset = IntentDataset(train_encodings, list(train_df['label']))
|
82 |
+
test_dataset = IntentDataset(test_encodings, list(test_df['label']))
|
83 |
+
|
84 |
+
|
85 |
+
|
86 |
+
# Create an instance of the custom loss function
|
87 |
+
training_args = TrainingArguments(
|
88 |
+
output_dir='./results_' + modelNameToUse,
|
89 |
+
num_train_epochs=25,
|
90 |
+
per_device_train_batch_size=2,
|
91 |
+
per_device_eval_batch_size=2,
|
92 |
+
warmup_steps=500,
|
93 |
+
weight_decay=0.02,
|
94 |
+
logging_dir='./logs_' + modelNameToUse,
|
95 |
+
logging_steps=10,
|
96 |
+
evaluation_strategy="epoch",
|
97 |
+
)
|
98 |
+
|
99 |
+
trainer = Trainer(
|
100 |
+
model=model,
|
101 |
+
args=training_args,
|
102 |
+
train_dataset=train_dataset,
|
103 |
+
eval_dataset=test_dataset
|
104 |
+
)
|
105 |
+
|
106 |
+
# Train the model
|
107 |
+
trainer.train()
|
108 |
+
|
109 |
+
# Evaluate the model
|
110 |
+
trainer.evaluate()
|
111 |
+
|
112 |
+
label_mapping = {
|
113 |
+
0: "lastmonth",
|
114 |
+
1: "nextweek",
|
115 |
+
2: "sevendays",
|
116 |
+
3: "today",
|
117 |
+
4: "tomorrow",
|
118 |
+
5: "yesterday"
|
119 |
+
|
120 |
+
}
|
121 |
+
|
122 |
+
def evaluate_and_report_errors(model, dataloader, tokenizer):
|
123 |
+
model.eval()
|
124 |
+
incorrect_predictions = []
|
125 |
+
with torch.no_grad():
|
126 |
+
#print(dataloader)
|
127 |
+
for batch in dataloader:
|
128 |
+
input_ids = batch['input_ids'].to(device)
|
129 |
+
attention_mask = batch['attention_mask'].to(device)
|
130 |
+
labels = batch['labels'].to(device)
|
131 |
+
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
|
132 |
+
logits = outputs.logits
|
133 |
+
predictions = torch.argmax(logits, dim=1)
|
134 |
+
|
135 |
+
for i, prediction in enumerate(predictions):
|
136 |
+
if prediction != labels[i]:
|
137 |
+
incorrect_predictions.append({
|
138 |
+
"prompt": tokenizer.decode(input_ids[i], skip_special_tokens=True),
|
139 |
+
"predicted": prediction.item(),
|
140 |
+
"actual": labels[i].item()
|
141 |
+
})
|
142 |
+
|
143 |
+
# Print incorrect predictions
|
144 |
+
if incorrect_predictions:
|
145 |
+
print("\nIncorrect Predictions:")
|
146 |
+
for error in incorrect_predictions:
|
147 |
+
print(f"Sentence: {error['prompt']}")
|
148 |
+
#print(f"Predicted Label: {GetCategoryFromCategoryLong(error['predicted'])} | Actual Label: {GetCategoryFromCategoryLong(error['actual'])}\n")
|
149 |
+
print(f"Predicted Label: {label_mapping[error['predicted']]} | Actual Label: {label_mapping[error['actual']]}\n")
|
150 |
+
#print(f"Predicted Label: {error['predicted']} | Actual Label: {label_mapping[error['actual']]}\n")
|
151 |
+
else:
|
152 |
+
print("\nNo incorrect predictions found.")
|
153 |
+
|
154 |
+
train_dataloader = DataLoader(train_dataset, batch_size=10, shuffle=True)
|
155 |
+
evaluate_and_report_errors(model,train_dataloader, tokenizer)
|
156 |
+
|
157 |
+
# Save the model and tokenizer
|
158 |
+
model.save_pretrained('./' + modelNameToUse + '_model')
|
159 |
+
tokenizer.save_pretrained('./' + modelNameToUse + '_tokenizer')
|
160 |
+
else:
|
161 |
+
print('Load Pre-trained')
|
162 |
+
model_save_path = "./" + modelNameToUse + "_model"
|
163 |
+
tokenizer_save_path = "./" + modelNameToUse + "_tokenizer"
|
164 |
+
|
165 |
+
# RobertaTokenizer.from_pretrained(model_save_path)
|
166 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_save_path).to('cpu')
|
167 |
+
tokenizer = AutoTokenizer.from_pretrained(tokenizer_save_path)
|
168 |
+
|
169 |
+
#Define the label mappings (this must match the mapping used during training)
|
170 |
+
label_mapping = {
|
171 |
+
0: "lastmonth",
|
172 |
+
1: "nextweek",
|
173 |
+
2: "sevendays",
|
174 |
+
3: "today",
|
175 |
+
4: "tomorrow",
|
176 |
+
5: "yesterday"
|
177 |
+
}
|
178 |
+
|
179 |
+
|
180 |
+
#Function to classify user input
|
181 |
+
def classifyTimeFrame():
|
182 |
+
while True:
|
183 |
+
user_input = input("Enter a command (or type 'q' to quit): ")
|
184 |
+
if user_input.lower() == 'q':
|
185 |
+
print("Exiting...")
|
186 |
+
break
|
187 |
+
|
188 |
+
# Tokenize and predict
|
189 |
+
input_encoding = tokenizer(user_input, padding=True, truncation=True, return_tensors="pt").to('cpu')
|
190 |
+
|
191 |
+
with torch.no_grad():
|
192 |
+
attention_mask = input_encoding['attention_mask'].clone()
|
193 |
+
|
194 |
+
|
195 |
+
|
196 |
+
# Modify the attention mask to emphasize certain key tokens
|
197 |
+
# for idx, token_id in enumerate(input_encoding['input_ids'][0]):
|
198 |
+
# word = tokenizer.decode([token_id])
|
199 |
+
# print(word)
|
200 |
+
# if word.strip() in ["now", "same", "continue", "again", "also"]: # Target key tokens
|
201 |
+
# attention_mask[0, idx] = 3 # Increase attention weight for these words
|
202 |
+
# else:
|
203 |
+
# attention_mask[0, idx] = 0
|
204 |
+
# print (attention_mask)
|
205 |
+
# input_encoding['attention_mask'] = attention_mask
|
206 |
+
# print (input_encoding)
|
207 |
+
output = model(**input_encoding, output_hidden_states=True)
|
208 |
+
|
209 |
+
probabilities = F.softmax(output.logits, dim=-1)
|
210 |
+
|
211 |
+
prediction = torch.argmax(output.logits, dim=1).cpu().numpy()
|
212 |
+
|
213 |
+
# Map prediction back to label
|
214 |
+
print(prediction)
|
215 |
+
predicted_label = label_mapping[prediction[0]]
|
216 |
+
|
217 |
+
|
218 |
+
print(f"Predicted intent: {predicted_label}\n")
|
219 |
+
# Print the confidence for each label
|
220 |
+
print("\nLabel Confidence Scores:")
|
221 |
+
for i, label in label_mapping.items():
|
222 |
+
confidence = probabilities[0][i].item() # Get confidence score for each label
|
223 |
+
print(f"{label}: {confidence:.4f}")
|
224 |
+
print("\n")
|
225 |
+
|
226 |
+
#Run the function
|
227 |
+
classifyTimeFrame()
|
228 |
+
|
229 |
+
|