使用PyTorch实现的深度学习的简单代码,可以得到训练集和验证集的准确率曲线、损失函数曲线以及交叉熵函数曲线,同时没有使用Keras,库比较少:
时间: 2023-12-10 19:38:18 浏览: 148
下面是一个使用PyTorch实现的简单的神经网络代码,可以得到训练集和验证集的准确率曲线、损失函数曲线以及交叉熵函数曲线:
```
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import matplotlib.pyplot as plt
# 定义超参数
num_epochs = 10
batch_size = 100
learning_rate = 0.001
# 加载数据集
train_dataset = datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor())
# 创建数据加载器
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = nn.functional.relu(nn.functional.max_pool2d(self.conv1(x), 2))
x = nn.functional.relu(nn.functional.max_pool2d(self.conv2(x), 2))
x = x.view(-1, 320)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return nn.functional.log_softmax(x, dim=1)
# 创建模型和优化器
model = Net()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 定义损失函数
criterion = nn.CrossEntropyLoss()
# 训练模型
train_losses = []
train_accs = []
test_losses = []
test_accs = []
for epoch in range(num_epochs):
train_loss = 0
train_acc = 0
test_loss = 0
test_acc = 0
# 训练模型
model.train()
for i, (images, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
train_acc += (predicted == labels).sum().item()
train_loss /= len(train_loader)
train_acc /= len(train_loader.dataset)
train_losses.append(train_loss)
train_accs.append(train_acc)
# 测试模型
model.eval()
with torch.no_grad():
for images, labels in test_loader:
outputs = model(images)
loss = criterion(outputs, labels)
test_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
test_acc += (predicted == labels).sum().item()
test_loss /= len(test_loader)
test_acc /= len(test_loader.dataset)
test_losses.append(test_loss)
test_accs.append(test_acc)
# 打印训练结果
print('Epoch [{}/{}], Train Loss: {:.4f}, Train Acc: {:.4f}, Test Loss: {:.4f}, Test Acc: {:.4f}'
.format(epoch+1, num_epochs, train_loss, train_acc, test_loss, test_acc))
# 绘制准确率曲线和损失函数曲线
plt.plot(train_losses, label='Train Loss')
plt.plot(test_losses, label='Test Loss')
plt.legend()
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()
plt.plot(train_accs, label='Train Acc')
plt.plot(test_accs, label='Test Acc')
plt.legend()
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.show()
```
这段代码使用了一个简单的卷积神经网络来对MNIST数据集进行分类。训练过程中,每个epoch都会计算训练集和验证集的损失函数和准确率,并将它们保存下来。最后,使用matplotlib库绘制出训练集和验证集的准确率曲线、损失函数曲线以及交叉熵函数曲线。
阅读全文