File size: 4,155 Bytes
04b0398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import numpy as np
from datasets import Dataset
from transformers import AutoTokenizer, AutoModelForTokenClassification, TrainingArguments, Trainer
from seqeval.metrics import classification_report
import torch


def main():
    # Verify GPU availability
    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(f"Using device: {device}")

    # Load dataset from CSV
    df = pd.read_excel('Augmented_Dataset.xlsx')

    # Clean the data
    df = df.dropna(subset=['Word', 'Tag'])
    df['Word'] = df['Word'].astype(str)
    df['Tag'] = df['Tag'].astype(str)

    # Group sentences
    grouped_data = df.groupby("Sentence").apply(lambda s: {
        'words': s['Word'].tolist(),
        'labels': s['Tag'].tolist()
    }).tolist()

    # Convert grouped data to Dataset
    dataset = Dataset.from_list(grouped_data)
    print(f"Total dataset size: {len(dataset)}")

    # Split into train and test sets
    train_test_split = dataset.train_test_split(test_size=0.2)
    train_dataset = train_test_split['train']
    test_dataset = train_test_split['test']

    # Load the tokenizer
    tokenizer = AutoTokenizer.from_pretrained("abdulhade/RoBERTa-large-SizeCorpus_1B")

    # Map labels to unique IDs
    unique_labels = list(set(df['Tag']))
    label2id = {label: i for i, label in enumerate(unique_labels)}
    id2label = {i: label for label, i in label2id.items()}

    # Tokenize and align labels
    def tokenize_and_align_labels(examples):
        tokenized_inputs = tokenizer(
            examples['words'],
            truncation=True,
            is_split_into_words=True,
            padding='max_length',
            max_length=128
        )
        labels = []
        for i, label in enumerate(examples['labels']):
            word_ids = tokenized_inputs.word_ids(batch_index=i)
            label_ids = [-100 if word_id is None else label2id[label[word_id]] for word_id in word_ids]
            labels.append(label_ids)

        tokenized_inputs["labels"] = labels
        return tokenized_inputs

    # Apply tokenization to datasets without parallel processing
    train_dataset = train_dataset.map(tokenize_and_align_labels, batched=True)
    test_dataset = test_dataset.map(tokenize_and_align_labels, batched=True)

    # Load the model
    model = AutoModelForTokenClassification.from_pretrained(
        "abdulhade/RoBERTa-large-SizeCorpus_1B",
        num_labels=len(unique_labels),
        id2label=id2label,
        label2id=label2id
    ).to(device)

    # Set up training arguments
    training_args = TrainingArguments(
        output_dir='results',
        evaluation_strategy="epoch",
        learning_rate=2e-5,
        per_device_train_batch_size=64,  # Adjusted for 8GB VRAM
        per_device_eval_batch_size=64,
        num_train_epochs=50,  # Increased to 50
        weight_decay=0.01,
        save_steps=5000,
        save_total_limit=2,
        logging_dir='./logs',
        fp16=True,  # Use mixed precision for faster computation
    )

    # Initialize Trainer
    trainer = Trainer(
        model=model,
        args=training_args,
        train_dataset=train_dataset,
        eval_dataset=test_dataset,
        tokenizer=tokenizer,
    )

    # Train the model
    trainer.train()

    # Save the trained model and tokenizer
    output_dir = 'NER_RoBERTa_fineTuning'
    model.save_pretrained(output_dir)
    tokenizer.save_pretrained(output_dir)

    print(f"Model and tokenizer saved to {output_dir}")

    # Evaluate the model
    predictions, labels, _ = trainer.predict(test_dataset)
    predictions = np.argmax(predictions, axis=2)

    true_labels = [[id2label[label] for label in label_set if label != -100] for label_set in labels]
    true_predictions = [[id2label[pred] for pred, label in zip(pred_set, label_set) if label != -100]
                        for pred_set, label_set in zip(predictions, labels)]

    # Print classification report
    print(classification_report(true_labels, true_predictions))


if __name__ == "__main__":
    main()