Sure! Here's a simple multi-layer perceptron (MLP) implementation in PyTorch for text classification tasks:
python
import torch
import torch.nn as nn
import torch.optim as optim
class MLP(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(MLP, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
model = MLP(input_size=10000, hidden_size=128, output_size=8)
In this code, we define a class MLP that inherits from PyTorch's nn.Module. The __init__ method defines the two fully connected (dense) layers in the network: fc1 with an input size of 10000 (the number of unique words in our vocabulary) and an output size of 128, and fc2 with an input size of 128 and an output size of 8 (the number of classes in our classification problem).
The forward method defines how input data flows through the network. It first applies the activation function torch.relu to the output of fc1, which is then passed through fc2 to produce the final output.
To train the model, we would need to add a loss function, an optimizer, and some dataset loading and preprocessing code. Here's an example of how to do that:
python
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
import numpy as np
# Load the dataset
class TextDataset(Dataset):
def __init__(self, texts, labels):
self.texts = texts
self.labels = labels
def __len__(self):
return len(self.texts)
def __getitem__(self, idx):
text = self.texts[idx]
label = self.labels[idx]
return text, label
# Load the data
train_data = TextDataset(train_texts, train_labels)
test_data = TextDataset(test_texts, test_labels)
# Define the loss function and optimizer
criterion = F.cross_entropy
optimizer = optim.SGD(model.parameters(), lr=0.01)
# Train the model
for epoch in range(10):
for texts, labels in DataLoader(train_data, batch_size=32):
optimizer.zero_grad()
outputs = model(texts)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
In this code, we define a custom dataset class TextDataset that loads the text data and labels from two separate lists. We then create a DataLoader instance to batch the data and define the loss function and optimizer.
In the training loop, we iterate over the batches of data using DataLoader and call the model's forward method on each batch. We then calculate the loss using the cross_entropy function from PyTorch's nn.functional module, and backpropagate the gradients using the loss.backward() method. Finally, we update the model parameters using the optimizer's step() method.
Note that this is a very basic implementation of a text classification model, and there are many ways to improve it, such as adding preprocessing steps, using different activation functions, or trying different architectures.