File size: 3,578 Bytes
6018ab2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | # Step 1: Install Required Libraries
# Uncomment the following lines if you are running this in a new environment
# !pip install transformers torch datasets pandas
# Step 2: Import Required Libraries
import pandas as pd
import torch
from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset
# Step 3: Prepare Your Dataset
# Create a sample dataset (replace this with your actual dataset)
data = {
'text': [
"అయ్యో, నిన్ను చూసి చాలా కాలమైంది!", # 0
"నువ్వు ఈ రోజు రాంబాబు ఇంటికి వెళ్ళావా?", # 1
"హే, నువ్వు ఈ కొత్త సినిమా చూసావా?", # 0
"ఈ ప్రాజెక్ట్ మీద పని ఎలా జరుగుతోంది?", # 1
"సూపర్ మాస్! బాగా ఎంజాయ్ చేశా.", # 0
"చాలా కష్టంగా ఉంది, కానీ మామూలుగా ఉంది." # 1
],
'label': [0, 1, 0, 1, 0, 1] # Example labels
}
# Create a DataFrame
df = pd.DataFrame(data)
# Split into train and test sets
train_texts = df['text'][:4].tolist()
train_labels = df['label'][:4].tolist()
test_texts = df['text'][4:].tolist()
test_labels = df['label'][4:].tolist()
# Step 4: Tokenization
tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased') # Use a multilingual model
train_encodings = tokenizer(train_texts, truncation=True, padding=True)
test_encodings = tokenizer(test_texts, truncation=True, padding=True)
# Step 5: Create a Dataset Class
class ColloquialDataset(torch.utils.data.Dataset):
def _init_(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def _getitem_(self, idx):
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
item['labels'] = torch.tensor(self.labels[idx])
return item
def _len_(self):
return len(self.labels)
# Create dataset objects
train_dataset = ColloquialDataset(train_encodings, train_labels)
test_dataset = ColloquialDataset(test_encodings, test_labels)
# Step 6: Load the Model
model = BertForSequenceClassification.from_pretrained('bert-base-multilingual-cased', num_labels=2)
# Step 7: Set Up Training Arguments
training_args = TrainingArguments(
output_dir='./results', # output directory
num_train_epochs=3, # total number of training epochs
per_device_train_batch_size=2, # batch size per device during training
per_device_eval_batch_size=2, # batch size for evaluation
warmup_steps=10, # number of warmup steps for learning rate scheduler
weight_decay=0.01, # strength of weight decay
logging_dir='./logs', # directory for storing logs
logging_steps=10,
)
# Step 8: Initialize the Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset
)
# Step 9: Train the Model
trainer.train()
# Step 10: Evaluate the Model
eval_results = trainer.evaluate()
print("Evaluation Results:", eval_results)
# Step 11: Save the Fine-Tuned Model
model.save_pretrained('./fine_tuned_model')
tokenizer.save_pretrained('./fine_tuned_model')
print("Model and tokenizer saved successfully!")
|