In this code, we define a simple neural network model called TextClassifier, which consists of an embedding layer, a fully connected layer, a ReLU activation function, and another fully connected layer. We split the dataset into a training set and a validation set using PyTorch's random_split function.
We define hyperparameters such as the vocabulary size, embedding dimension, hidden dimension, learning rate, and number of epochs. We also define the loss function and optimizer to train the model.
We then train the model for a specified number of epochs using a loop. For each epoch, we iterate over the training set in batches and compute the loss and gradients using backpropagation. We then evaluate the model on the validation set using a separate data loader. We compute the validation loss and accuracy and print the results.
Note that the validation set is used to prevent overfitting and evaluate the model's performance on unseen data. You can modify the code to perform additional operations such as saving the model checkpoint, early stopping, or other techniques to improve the model's performance on your specific dataset.
import csv
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torchtext.vocab import Vocab
from torchtext.utils import extract_archive, download_from_url
from torchtext.datasets import text_classification
from torchtext.data.utils import get_tokenizer
# Define the model architecture
class TextClassifier(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.embedding = nn.EmbeddingBag(vocab_size, embedding_dim, sparse=True)
self.fc = nn.Sequential(
nn.Linear(embedding_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, output_dim)
)
self.num_layers = num_layers
def forward(self, text):
embedded = self.embedding(text, None)
hidden = self.fc[0](embedded)
for i in range(1, self.num_layers):
hidden = self.fc[i](hidden)
output = self.fc[-1](hidden)
return output
# Define a custom dataset class for the text data
class MyDataset(Dataset):
def __init__(self, data_file, vocab):
self.data = []
with open(data_file, 'r') as f:
reader = csv.reader(f)
next(reader) # Skip the header row
for row in reader:
id_, text, label = row
text = torch.tensor([vocab[token] for token in tokenizer(text)])
label = torch.tensor(int(label))
self.data.append((text, label))
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data)
# Define the training and evaluation functions
def train(model, train_loader, criterion, optimizer):
model.train()
train_loss = 0.0
train_acc = 0.0
for text, label in train_loader:
optimizer.zero_grad()
output = model(text)
loss = criterion(output, label)
loss.backward()
optimizer.step()
train_loss += loss.item()
train_acc += (output.argmax(dim=1) == label).sum().item()
train_loss /= len(train_loader.dataset)
train_acc /= len(train_loader.dataset)
return train_loss, train_acc
def evaluate(model, data_loader, criterion):
model.eval()
eval_loss = 0.0
eval_acc = 0.0
with torch.no_grad():
for text, label in data_loader:
output = model(text)
loss = criterion(output, label)
eval_loss += loss.item()
eval_acc += (output.argmax(dim=1) == label).sum().item()
eval_loss /= len(data_loader.dataset)
eval_acc /= len(data_loader.dataset)
return eval_loss, eval_acc
# Define some hyperparameters
batch_size = 64
embedding_dim = 32
hidden_dim = 64
num_layers = 2
lr = 0.01
num_epochs = 10
# Download and preprocess the data
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00331/sentiment%20labelled%20sentences.zip'
train_file, test_file = extract_archive(download_from_url(url))
tokenizer = get_tokenizer('basic_english')
train_dataset = MyDataset(train_file, vocab)
test_dataset = MyDataset(test_file, vocab)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True,