import torch
import torch.nn as nn
import torch.optim as optim
# Define the model
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(MLP, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.fc3 = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# Initialize the model, loss function, and optimizer
model = MLP(input_dim=512, hidden_dim=512, output_dim=512)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Training data
inputs = torch.randn(1000, 512)
targets = torch.randn(1000, 512)
# Train the model
for epoch in range(1000):
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print(f'Epoch {epoch}: Loss = {loss.item()}')
This code defines a simple dense multilayer MLP with three fully connected (dense) layers. The input dimension is 512, the hidden dimension is 512, and the output dimension is also 512. The model uses the ReLU activation function in each hidden layer.
The model is then initialized along with the loss function (in this case, mean squared error) and the optimizer (in this case, Adam with a learning rate of 0.001).
Note that this is just a simple example, and in practice, you may need to fine-tune the architecture, hyperparameters, and optimization algorithm to achieve the best results for your specific problem.