python Copy code
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from particle_swarm_optimization import PSO
# Define the neural network architecture
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = x.view(x.size(0), -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
# Define the particle swarm optimization algorithm
class PSOOptimizer(optim.Optimizer):
def __init__(self, params, lr, c1, c2, w):
defaults = dict(lr=lr, c1=c1, c2=c2, w=w)
super(PSOOptimizer, self).__init__(params, defaults)
def step(self):
for group in self.param_groups:
for p in group['params']:
# Update the velocity
p.data.add_(group['lr'] * (group['c1'] * torch.rand(p.size()) * (p.data - group['best_params']) + group['c2'] * torch.rand(p.size()) * (group['best_global_params'] - p.data)))
# Update the position
p.data.add_(group['lr'] * p.data)
# Update the best personal parameters
if p.data.norm() < group['best_params'].norm():
group['best_params'] = p.data
# Update the best global parameters
if p.data.norm() < group['best_global_params'].norm():
group['best_global_params'] = p.data
# Load the MNIST-1D dataset
train_data = datasets.MNIST('data', train=True, download=True, transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
# Initialize the neural network
net = Net()
# Initialize the particle swarm optimization algorithm
optimizer = PSOOptimizer(net.parameters(), lr=0.01, c1=2, c2=2, w=0.5)
# Train the neural network
for epoch in range(10):
for batch_idx, (data, target) in enumerate(train_loader):
# Forward pass
output = net(data)
# Calculate the loss
loss = F.cross_entropy(output, target)
# Backward pass
optimizer.zero_grad()
loss.backward()
# Update the weights
optimizer.step()
# Test the neural network
test_data = datasets.MNIST('data', train=False, download=True, transform=transforms.ToTensor())
test_loader = torch.utils.data.DataLoader(test_data, batch_size=64, shuffle=True)
correct = 0
total = 0
with torch.no_grad():
for data, target in test_loader:
output = net(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
total += target.size(0)
print(f'Accuracy: {correct / total:.2%}')