CNN手写数字识别csv训练集读取保存训练好的pytorch模型,另一个文件加载调用pytorch模型测试csv数据集和单张图片
时间: 2023-12-08 08:07:03 浏览: 151
你可以按照以下步骤来实现CNN手写数字别的训练、保存模型以及加载模型进行测试。
1. 导入所需的库:
```python
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.optim as optim
import pandas as pd
```
2. 创建一个自定义的CNN模型:
```python
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2)
self.relu1 = nn.ReLU()
self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2)
self.relu2 = nn.ReLU()
self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.fc = nn.Linear(7*7*32, 10)
def forward(self, x):
out = self.conv1(x)
out = self.relu1(out)
out = self.maxpool1(out)
out = self.conv2(out)
out = self.relu2(out)
out = self.maxpool2(out)
out = out.view(out.size(0), -1)
out = self.fc(out)
return out
model = CNN()
```
3. 加载训练集数据并进行预处理:
```python
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
train_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
```
4. 定义损失函数和优化器:
```python
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
```
5. 进行模型训练:
```python
total_epochs = 5
for epoch in range(total_epochs):
running_loss = 0.0
for i, (inputs, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if (i+1) % 100 == 0:
print(f'Epoch [{epoch+1}/{total_epochs}], Step [{i+1}/{len(train_loader)}], Loss: {running_loss/100:.4f}')
running_loss = 0.0
print('Training finished!')
```
6. 保存训练好的模型:
```python
torch.save(model.state_dict(), 'model.pth')
print('Model saved!')
```
7. 在另一个文件中加载保存的模型并进行测试:
```python
# 加载模型
model = CNN()
model.load_state_dict(torch.load('model.pth'))
model.eval()
# 加载测试集数据
test_dataset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
# 测试模型
correct = 0
total = 0
with torch.no_grad():
for inputs, labels in test_loader:
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print(f'Test Accuracy: {accuracy}%')
```
以上是一个简单的示例,展示了如何使用PyTorch构建、训练和保存CNN模型,并在另一个文件中加载模型进行测试。你可以根据自己的需求进行修改和扩展。
阅读全文