Here's a basic implementation of a multi-layer perceptron (MLP) using PyTorch for text classification tasks. This example assumes you're working with a binary classification problem, but it can be easily extended to more classes.
python
import torch
import torch.nn as nn
import torch.optim as optim
class SimpleMLP(nn.Module):
def __init__(self, input_dim, hidden_dim, num_classes):
super(SimpleMLP, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, num_classes)
def forward(self, x):
x = self.fc1(x)
x = torch.sigmoid(x)
x = self.fc2(x)
return x
def train(model, dataloader, criterion, optimizer, epochs):
for epoch in range(epochs):
model.train()
for inputs, labels in dataloader:
x = inputs.view(labels.size(0), -1)
targets = labels.view(labels.size(0), 1)
optimizer.zero_grad()
outputs = model(x)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
# Load your dataset
# X is your input text, y is your label (0 or 1)
# X and y should be loaded in batches for efficiency
# Instantiate the model
input_dim = X.shape[1]
hidden_dim = 128
num_classes = 2
model = SimpleMLP(input_dim, hidden_dim, num_classes)
# Define the loss function and optimizer
criterion = nn.BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Train the model
train(model, dataloader, criterion, optimizer, epochs=10)
# Evaluate the model on validation or test data
# Replace model(x) with model(x).view(x.size(0), 1) if you're using binary classification
This example assumes you have already loaded your dataset and prepared it for training. You'll need to adjust the input_dim, hidden_dim, and num_classes based on your specific problem. Additionally, you may want to fine-tune the learning rate, number of epochs, and other hyperparameters based on your dataset and problem requirements.