vkolasani commited on
Commit
4493985
·
verified ·
1 Parent(s): 5dafffc

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +60 -0
main.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments
3
+ import numpy as np
4
+ from sklearn.metrics import accuracy_score, f1_score
5
+
6
+ # Data loading
7
+ dataset = load_dataset("tweet_eval", "sentiment")
8
+
9
+ # Model Selection
10
+ model_name = "bert-base-uncased"
11
+
12
+ # Tokenization
13
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
14
+
15
+ def tokenize_function(examples):
16
+ return tokenizer(examples["text"], padding="max_length", truncation=True, max_length=128)
17
+
18
+ tokenized_datasets = dataset.map(tokenize_function, batched=True)
19
+ tokenized_datasets = tokenized_datasets.remove_columns(["text"])
20
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
21
+ tokenized_datasets.set_format("torch")
22
+
23
+ # Model setup
24
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=3)
25
+
26
+ def compute_metrics(eval_pred):
27
+ logits, labels = eval_pred
28
+ predictions = np.argmax(logits, axis=-1)
29
+ accuracy = accuracy_score(labels, predictions)
30
+ f1 = f1_score(labels, predictions, average='macro')
31
+ return {'accuracy': accuracy, 'f1': f1}
32
+
33
+ # Training Configuration
34
+ training_args = TrainingArguments(
35
+ output_dir="./results",
36
+ num_train_epochs=1, # Increase for better performance
37
+ per_device_train_batch_size=80, # Increase if possible
38
+ per_device_eval_batch_size=80,
39
+ warmup_steps=500, # Adjust warmup steps
40
+ weight_decay=0.01, # Slightly higher weight decay
41
+ logging_dir='./logs',
42
+ learning_rate=5e-5, # Slightly higher learning rate
43
+ load_best_model_at_end=True,
44
+ metric_for_best_model='accuracy', # Track accuracy
45
+ evaluation_strategy="epoch", # Evaluate at the end of each epoch
46
+ save_strategy="epoch",
47
+ save_total_limit=2, # Limit saved checkpoints
48
+ )
49
+
50
+ # Training
51
+ trainer = Trainer(
52
+ model=model,
53
+ args=training_args,
54
+ train_dataset=tokenized_datasets["train"],
55
+ eval_dataset=tokenized_datasets["validation"],
56
+ compute_metrics=compute_metrics # Add the compute_metrics function
57
+ )
58
+
59
+ trainer.train()
60
+