以识别手写数字为例,手写数字从0-9
p
r
e
=
W
3
∗
(
W
2
(
W
1
X
+
b
1
)
+
b
2
)
+
b
3
pre = W_3*(W_2(W_1X+b_1)+b_2)+b_3
pre=W3∗(W2(W1X+b1)+b2)+b3
上述式子是一个很简单的线性模型,但是线性模型并不能应用到复杂任务上去,我们在每一次线性的后边加入一个激活函数,增强模型的非线性表达能力。
H
1
=
r
e
l
u
(
X
W
1
+
b
1
)
H
2
=
r
e
l
u
(
H
1
W
2
+
b
2
)
H
3
=
r
e
l
u
(
H
2
W
3
+
b
3
)
H_1=relu(XW_1+b_1) \\ H_2 = relu(H_1W_2+b_2) \\ H_3 = relu(H_2W_3+b_3)
H1=relu(XW1+b1)H2=relu(H1W2+b2)H3=relu(H2W3+b3)
pre输出是one-hot向量
[0.1 0.8 .... 0.01]
label:
[0 1 0 0 0...]
这个意思是这个数字是1, 模型预测这个数字为1的概率为0.8
max(pred) = 0.8 argmax(pred) = 1
实际操作
4-steps
- load data
- Build Model
- Train
- Test
实战代码
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
import utils
batch_size = 512
# step 1、 load dataset
train_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST('mnist_data',
train=True,
download=True,
transform=torchvision.transforms.Compose([
# 将输入图像或Numpy数组转换为tensor
# 将原始图像的像素值从[0, 255]缩放到 [0, 1]
torchvision.transforms.ToTensor(),
# 均值-标准差归一化,均值,方差,对于图像的通道,都需要指定一个均值
#但这是灰度图,因此只需要一个
# x' = x-u/sigma
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())
utils.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 = relu(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, feature]
x = x.view(x.size(0), 28*28)
# > [b,10]
out = net(x)
y_onehot = utils.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())
utils.plot_curve(train_loss)
# we get optimal [w1, b1, w2, b2, w3, b3]
# test
total_correct = 0
for x, y in test_loader:
x = x.view(x.size(0), 28*28)
out = net(x)
# out: [b, 10]
pred = out.argmax(dim=1)
correct = pred.eq(y).sum().float()
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)
utils.plot_image(x, pred, 'test')