pytorch实现手写字符识别
时间: 2023-11-13 17:04:37 浏览: 119
手写数字识别(pytorch版)
以下是使用PyTorch实现手写字符识别的步骤:
1. 导入必要的库和模块
```python
import os
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch import nn
from torch.utils import data
import torchvision.transforms as transforms
from tensorboardX import SummaryWriter
import skimage.io as io
import matplotlib.pyplot as plt
```
2. 定义常量
```python
train_batch_size = 64
```
3. 加载数据集
```python
class TrainDataset(data.Dataset):
def __init__(self, array, label):
self.data = np.asarray(array)
self.label = np.asarray(label)
self.transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])
])
def __getitem__(self, index):
txt = torch.from_numpy(self.data[index])
label = torch.tensor(self.label[index])
return txt, label
def __len__(self):
return len(self.data)
train_data = np.load('train_data.npy')
train_label = np.load('train_label.npy')
train_dataset = TrainDataset(train_data, train_label)
train_loader = data.DataLoader(train_dataset, batch_size=train_batch_size, shuffle=True)
```
4. 定义模型
```python
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.fc1 = nn.Linear(1024, 128)
self.fc2 = nn.Linear(128, 47)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2(x), 2))
x = x.view(-1, 1024)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return F.log_softmax(x, dim=1)
model = Net()
```
5. 定义损失函数和优化器
```python
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
```
6. 训练模型
```python
def train(epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
if batch_idx % 10 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
for epoch in range(1, 11):
train(epoch)
```
7. 测试模型
```python
test_data = np.load('test_data.npy')
test_label = np.load('test_label.npy')
test_dataset = TrainDataset(test_data, test_label)
test_loader = data.DataLoader(test_dataset, batch_size=train_batch_size, shuffle=True)
def test():
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
output = model(data)
test_loss += criterion(output, target).item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
test()
```
阅读全文