目录
二、不用Deep Learning 用简单的函数映射怎么训练?
1. plot_image(x, y, 'image sample')
一、什么是MNIST数据集
MNIST数据集已经是一个极其经典的数据集了,先放上下载链接MNIST handwritten digit database, Yann LeCun, Corinna Cortes and Chris Burges
图片是以字节的形式进行存储,我需要将其读取到Numpy array中,以便训练与计算。
数据集大概有 60,000 个训练样本和 10,000 个测试样本。
例举数据集一张图片来说 [0 - 1 , 28 ,28 ] ,存储数据的形式如矩阵所示,第1维度为0-1之间表示灰度,第2维度与第3维度表示28*28格。
二、不用Deep Learning 用简单的函数映射怎么训练?
1. 简单函数叠加拟合复杂函数
我们知道28*28矩阵的具体参数有784个,那么我们将其打平为X = [1,784]向量进行计算,简写为X = [1,dx] , 接下来将其投入激活函数中进行计算 H1 = XW1 + b1 ,不停拟合(三层)。 这样可能还比较难理解,我们实际代数据进入计算。
首先打平[28*28] 矩阵为X= [1,784], 继续W1=[784,256], b1=[256]
第一层 矩阵H1 = XW1 + b1 得 H1 = [1,256]
第二层 矩阵H2 = H1W2 + b2 ,W2为[256 , 64] ,b2 = [64] ,得 H2 = [1,64]
第三层 矩阵H3 = H2W3 + b3 ,W3为[64,10], b3 = [10],得H3 = [1,10]
得出10个分类。
2. Loss函数的设定
3. 梯度下降
4.结果
对于一个X最终推出其结果为一个1维10列的概率数组:[0.1, 0.8, 0.01, 0, 0.02, .........]
取该维度最大的索引下的数字即可 𝑎𝑟𝑔𝑚𝑎𝑥(𝑝𝑟𝑒𝑑) 。
三、实例代码
1. plot_image(x, y, 'image sample')
2. 训练过程
最终的训练精度大约为0.88左右
损失函数的数值如下所示
3.代码如下
import torch
from torch import nn
from torch.nn import functional as F
from torch import optim
import torchvision
from matplotlib import pyplot as plt
from utils import plot_image, plot_curve, one_hot
batch_size = 512 # 一次抓取512张图片。当然batch_size不是越大越好
# step1. load dataset
train_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('mnist_data', train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('mnist_data/', train=False, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=False)
x, y = next(iter(train_loader))
print(x.shape, y.shape, x.min(), x.max())
plot_image(x, y, 'image sample')
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# xw+b
self.fc1 = nn.Linear(28*28, 256)
self.fc2 = nn.Linear(256, 64)
self.fc3 = nn.Linear(64, 10)
def forward(self, x):
# x: [b, 1, 28, 28]
# h1 = relu(xw1+b1)
x = F.relu(self.fc1(x))
# h2 = relu(h1w2+b2)
x = F.relu(self.fc2(x))
# h3 = h2w3+b3
x = self.fc3(x)
return x
net = Net()
# [w1, b1, w2, b2, w3, b3]
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9) # 随机梯度下降
train_loss = []
for epoch in range(3):
for batch_idx, (x, y) in enumerate(train_loader):
# x: [b, 1, 28, 28], y: [512] b为batch size
# [b, 1, 28, 28] => [b, 784]
x = x.view(x.size(0), 28*28)
# => [b, 10]
out = net(x)
# [b, 10]
y_onehot = one_hot(y)
# loss = mse(out, y_onehot)
loss = F.mse_loss(out, y_onehot)
optimizer.zero_grad()
loss.backward()
# w' = w - lr*grad
optimizer.step()
train_loss.append(loss.item())
if batch_idx % 10==0:
print(epoch, batch_idx, loss.item())
plot_curve(train_loss)
# we get optimal [w1, b1, w2, b2, w3, b3]
total_correct = 0
for x,y in test_loader:
x = x.view(x.size(0), 28*28)
out = net(x)
# out: [b, 10] => pred: [b]
pred = out.argmax(dim=1)
correct = pred.eq(y).sum().float().item()
total_correct += correct
total_num = len(test_loader.dataset)
acc = total_correct / total_num
print('test acc:', acc)
x, y = next(iter(test_loader))
out = net(x.view(x.size(0), 28*28))
pred = out.argmax(dim=1)
plot_image(x, pred, 'test')