File size: 2,847 Bytes
5ee4795
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ai.py

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
from datasets import load_dataset
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
from tqdm import tqdm

# Load IMDb dataset
dataset = load_dataset("imdb")
texts, labels = dataset["train"]["text"], dataset["train"]["label"]

# Split the dataset into training and validation sets
train_texts, val_texts, train_labels, val_labels = train_test_split(texts, labels, test_size=0.1, random_state=42)

# Tokenize and preprocess the data
tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
train_encodings = tokenizer(train_texts, truncation=True, padding=True, return_tensors="pt", max_length=256)
val_encodings = tokenizer(val_texts, truncation=True, padding=True, return_tensors="pt", max_length=256)

# Define Sentiment Analysis Model
class SentimentAnalysisModel(nn.Module):
    def __init__(self):
        super(SentimentAnalysisModel, self).__init__()
        self.distilbert = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)

    def forward(self, input_ids, attention_mask):
        return self.distilbert(input_ids, attention_mask=attention_mask).logits

# Initialize model, criterion, and optimizer
model = SentimentAnalysisModel()
criterion = nn.CrossEntropyLoss()
optimizer = optim.AdamW(model.parameters(), lr=5e-5)

# Convert labels to tensor
train_labels = torch.tensor(train_labels)
val_labels = torch.tensor(val_labels)

# Prepare DataLoader
train_dataset = torch.utils.data.TensorDataset(train_encodings["input_ids"], train_encodings["attention_mask"], train_labels)
train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True)

val_dataset = torch.utils.data.TensorDataset(val_encodings["input_ids"], val_encodings["attention_mask"], val_labels)
val_loader = DataLoader(val_dataset, batch_size=8, shuffle=False)

# Train the model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

num_epochs = 5  # Increase the number of epochs
for epoch in range(num_epochs):
    model.train()
    total_loss = 0.0

    for input_ids, attention_mask, labels in tqdm(train_loader, desc=f"Epoch {epoch + 1}/{num_epochs}"):
        input_ids, attention_mask, labels = input_ids.to(device), attention_mask.to(device), labels.to(device)

        optimizer.zero_grad()
        outputs = model(input_ids, attention_mask=attention_mask)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        total_loss += loss.item()

    print(f"Epoch {epoch + 1}/{num_epochs}, Average Loss: {total_loss / len(train_loader)}")

# Save the trained model
torch.save(model.state_dict(), "sentiment_analysis_model.pth")