用pytorch搭建一个神经网络,输入为583个神经元,三个隐藏层,每个隐藏层后接batchnorm和非线性激活,输出层为2个神经单元,并设计优化器,损失函数并训练和测试模型
时间: 2024-06-06 18:11:12 浏览: 12
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 创建数据集
X, y = make_classification(n_samples=1000, n_features=583, n_informative=583, n_redundant=0, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 转换为tensor
X_train = torch.from_numpy(X_train).float()
X_test = torch.from_numpy(X_test).float()
y_train = torch.from_numpy(y_train).long()
y_test = torch.from_numpy(y_test).long()
# 定义神经网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(583, 256)
self.bn1 = nn.BatchNorm1d(256)
self.fc2 = nn.Linear(256, 128)
self.bn2 = nn.BatchNorm1d(128)
self.fc3 = nn.Linear(128, 64)
self.bn3 = nn.BatchNorm1d(64)
self.fc4 = nn.Linear(64, 2)
def forward(self, x):
x = self.fc1(x)
x = self.bn1(x)
x = nn.functional.relu(x)
x = self.fc2(x)
x = self.bn2(x)
x = nn.functional.relu(x)
x = self.fc3(x)
x = self.bn3(x)
x = nn.functional.relu(x)
x = self.fc4(x)
return x
# 实例化模型
model = Net()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# 训练模型
for epoch in range(100):
# 训练模式
model.train()
optimizer.zero_grad()
outputs = model(X_train)
loss = criterion(outputs, y_train)
loss.backward()
optimizer.step()
# 测试模式
model.eval()
with torch.no_grad():
outputs = model(X_test)
test_loss = criterion(outputs, y_test)
_, predicted = torch.max(outputs.data, 1)
accuracy = (predicted == y_test).sum().item() / y_test.size(0)
print('Epoch [{}/{}], Train Loss: {:.4f}, Test Loss: {:.4f}, Test Accuracy: {:.2f}%'
.format(epoch + 1, 100, loss.item(), test_loss.item(), accuracy * 100))