mnist 数据集是一个非常出名的数据集,基本上很多网络都将其作为一个测试的标准,其来自美国国家标准与技术研究所, National Institute of Standards and Technology (NIST)。 训练集 (training set) 由来自 250 个不同人手写的数字构成, 其中 50% 是高中学生, 50% 来自人口普查局 (the Census Bureau) 的工作人员,一共有 60000 张图片。 测试集(test set) 也是同样比例的手写数字数据,一共有 10000 张图片。
每张图片大小是 28 x 28 的灰度图:
完整代码在:GitHub 一共4个文件
MNIST.py 是主函数
net.py 里面定义了3种网络,训练的时候选择其中一种
readpic.py 用于读取图片,看看能否识别出来
3.jpg 就是自己用画图手写的一个数字和28*28差不多大
import torch
import torch.nn as nn
class simpleNet(nn.Module):
"""
简单的三层全连接神经网络
"""
def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):
super(simpleNet, self).__init__()
self.layer1 = nn.Linear(in_dim, n_hidden_1)
self.layer2 = nn.Linear(n_hidden_1, n_hidden_2)
self.layer3 = nn.Linear(n_hidden_2, out_dim)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
return x
class Activation_Net(nn.Module):
"""
添加激活函数增加网络的非线性
"""
def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):
super(Activation_Net, self).__init__()
"""
nn.Sequential() 将nn.Linear()和nn.ReLU()组合到一起
"""
self.layer1 = nn.Sequential(nn.Linear(in_dim, n_hidden_1), nn.ReLU(True))
self.layer2 = nn.Sequential(nn.Linear(n_hidden_1, n_hidden_2), nn.ReLU(True))
self.layer3 = nn.Sequential(nn.Linear(n_hidden_2, out_dim))
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
return x
class Batch_Net(nn.Module):
"""
添加批标准化,批标准化一般放在全连接层后面,激活层前面
"""
def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):
super(Batch_Net, self).__init__()
self.layer1 = nn.Sequential(nn.Linear(in_dim, n_hidden_1), nn.BatchNorm1d(n_hidden_1), nn.ReLU(True))
self.layer2 = nn.Sequential(nn.Linear(n_hidden_1, n_hidden_2), nn.BatchNorm1d(n_hidden_2), nn.ReLU(True))
self.layer3 = nn.Sequential(nn.Linear(n_hidden_2, out_dim))
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
return x
# hyperparameters
batch_size = 64*2
learning_rate = 1e-2
num_epoches = 20
data_tf = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])]
)
transforms.Compose()是将各种预处理操作组合在一起
transforms.ToTensor():将图片转成Tensor,同时标准化,所以范围为0-1
transforms.Normalize():需要传入两个参数:第一个是均值,第二个是方差,将数据减均值,再除以方差
相当于:
def data_tf(x):
x = np.array(x, dtype='float32') / 255 # 放到0-1之间
x = (x - 0.5) / 0.5
x = torch.from_numpy(x)
return x
train_dataset = datasets.MNIST(root='./data', train=True, transform=data_tf, download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=data_tf)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
关于dataset和DataLoader使用教程参考:https://www.jianshu.com/p/8ea7fba72673
model = net.Batch_Net(28*28, 300, 100, 10)
if torch.cuda.is_available():
model = model.cuda()
# 定义loss函数和优化方法
loss_fn = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
因为是多分类所以使用 nn.CrossEntropyLoss()
nn.BCELoss是二分类的损失函数
for epoch in range(num_epoches):
model.train()
for data in train_loader: # 每次取一个batch_size张图片
img, label = data # img.size:128*1*28*28
img = img.view(img.size(0), -1) # 展开成128 *784(28*28)
if torch.cuda.is_available():
img = img.cuda()
label = label.cuda()
output = model(img)
loss = loss_fn(output, label)
# 反向传播
optimizer.zero_grad()
loss.backward()
optimizer.step()
# print('epoch:', epoch, '|loss:', loss.item())
# 在测试集上检验效果
model.eval() # 将模型改为测试模式
eval_loss = 0
eval_acc = 0
for data in test_loader:
img, label = data
img = img.view(img.size(0), -1)
if torch.cuda.is_available():
img = img.cuda()
label = label.cuda()
out = model(img)
loss = loss_fn(out, label)
eval_loss += loss.item() * label.size(0) # lable.size(0)=128
_, pred = torch.max(out, 1)
num_correct = (pred == label).sum()
eval_acc += num_correct.item()
print('Epoch:{}, Test loss:{:.6f}, Acc:{:.6f}'.format(epoch, eval_loss/(len(test_dataset)), eval_acc/(len(test_dataset))))
from PIL import Image
import matplotlib.pyplot as plt
from torchvision import datasets, transforms
def readImage(path='./3.jpg', size=28):
mode = Image.open(path).convert('L') # 转换成灰度图
transform1 = transforms.Compose([
transforms.Resize(size),
transforms.CenterCrop((size, size)), # 切割
transforms.ToTensor()
])
mode = transform1(mode)
mode = mode.view(mode.size(0), -1)
return mode
def showTorchImage(image):
mode = transforms.ToPILImage()(image)
plt.imshow(mode)
plt.show()
在MNIST.py里测试:
figure = readpic.readImage(size=28)
figure = figure.cuda()
y_pred = model(figure)
_, pred = torch.max(y_pred, 1)
print('prediction = ', pred.item())
用测试集识别的效果很好,但是自己手写数字识别时发现精度并不是很高。
用的图片也是和28*28的差不多大,不知道哪边出了问题。