帮我写一段使用三层MLP神经网络模型的代码,分为训练及预测两个部分,使用ACC评估函数,nn.CrossEntropyLoss()损失
时间: 2024-10-23 21:14:12 浏览: 22
当然可以,这里是一个简单的例子,使用PyTorch库来构建一个三层全连接(Multilayer Perceptron,MLP)神经网络模型,包括训练和预测功能,并采用交叉熵损失函数(nn.CrossEntropyLoss)以及准确率(Accuracy)作为评估指标。首先,确保已经安装了torch库。
```python
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.metrics import accuracy_score
# 定义三层MLP模型
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
# 示例数据设置
input_dim = 784 # 假设输入特征维度为28x28
hidden_dim = 512
output_dim = 10 # 假设是10分类任务
num_epochs = 10
batch_size = 64
learning_rate = 0.001
# 创建模型、损失函数和优化器
model = MLP(input_dim, hidden_dim, output_dim)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 模拟数据集
# train_loader, test_loader = ... # 这里假设你已经有了数据加载器
# 实际上你需要从torch.utils.data中加载数据
def train(model, data_loader, criterion, optimizer):
model.train()
running_loss = 0.0
total_correct = 0
for inputs, labels in data_loader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
_, predicted = torch.max(outputs.data, 1)
total_correct += (predicted == labels).sum().item()
running_loss += loss.item() * inputs.size(0)
avg_loss = running_loss / len(data_loader.dataset)
accuracy = total_correct / len(data_loader.dataset)
return avg_loss, accuracy
def predict(model, data_loader):
model.eval()
predictions = []
true_labels = []
with torch.no_grad():
for inputs, labels in data_loader:
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
predictions.extend(predicted.tolist())
true_labels.extend(labels.tolist())
return predictions, true_labels
# 训练过程
for epoch in range(num_epochs):
train_loss, train_acc = train(model, train_loader, criterion, optimizer)
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {train_loss:.4f}, Accuracy: {train_acc*100:.2f}%")
# 预测阶段
test_predictions, test_true_labels = predict(model, test_loader)
test_accuracy = accuracy_score(test_true_labels, test_predictions)
print(f"Test Accuracy: {test_accuracy*100:.2f}%")
阅读全文