完成一个神经网络,网络类型不限,可以是多层感知器或CNN。完整的过程:包含从数据集(Dataset)定义到训练损失和测试损失的曲线展示。
时间: 2024-03-17 18:46:51 浏览: 45
MobileNetV1:这是训练和测试神经网络的全过程
好的,这是一个使用PyTorch实现的多层感知器神经网络的例子,包含从数据集定义到训练损失和测试损失的曲线展示。
```python
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# 加载数据集
data = load_breast_cancer()
x = data.data
y = data.target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
# 转换为PyTorch张量
x_train = torch.tensor(x_train, dtype=torch.float32)
y_train = torch.tensor(y_train, dtype=torch.float32)
x_test = torch.tensor(x_test, dtype=torch.float32)
y_test = torch.tensor(y_test, dtype=torch.float32)
# 定义模型
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(30, 64)
self.fc2 = nn.Linear(64, 32)
self.fc3 = nn.Linear(32, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.fc1(x)
x = self.sigmoid(x)
x = self.fc2(x)
x = self.sigmoid(x)
x = self.fc3(x)
x = self.sigmoid(x)
return x
# 定义数据集和数据加载器
train_dataset = TensorDataset(x_train, y_train)
test_dataset = TensorDataset(x_test, y_test)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# 定义损失函数和优化器
criterion = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# 训练模型
model = MLP()
train_losses = []
test_losses = []
for epoch in range(50):
train_loss = 0
test_loss = 0
model.train()
for x, y in train_loader:
optimizer.zero_grad()
y_pred = model(x)
loss = criterion(y_pred, y.view(-1, 1))
loss.backward()
optimizer.step()
train_loss += loss.item() * len(x)
model.eval()
with torch.no_grad():
for x, y in test_loader:
y_pred = model(x)
loss = criterion(y_pred, y.view(-1, 1))
test_loss += loss.item() * len(x)
train_loss /= len(x_train)
test_loss /= len(x_test)
train_losses.append(train_loss)
test_losses.append(test_loss)
print(f"Epoch {epoch+1}: train_loss={train_loss:.4f}, test_loss={test_loss:.4f}")
# 绘制损失曲线
plt.plot(train_losses, label="Train Loss")
plt.plot(test_losses, label="Test Loss")
plt.legend()
plt.show()
```
在这个例子中,我们使用了`scikit-learn`库中的乳腺癌数据集,将数据集拆分为训练集和测试集,然后将它们转换为PyTorch张量,并定义了一个包含3个全连接层和一个Sigmoid激活函数的多层感知器神经网络。我们使用`BCELoss`作为损失函数,使用`Adam`作为优化器进行模型训练。最后,我们绘制了训练损失和测试损失的曲线。
阅读全文