# 导包 from utils import load_data_fashion_mnist, train_ch3 from mxnet import nd from mxnet.gluon import loss as gloss
使⽤Fashion-MNIST数据集,采用多层感知机对图像进⾏分类。
batch_size = 256 train_iter, test_iter = load_data_fashion_mnist(batch_size)
Fashion-MNIST数据集中图像形状为28 × 28,类别数为10。本节中我们依然使⽤⻓度为28 × 28 = 784的向量表⽰每⼀张图像。因此,输⼊个数为784,输出个数为10。实验中,我们设超参数隐藏单元个数为256。
num_inputs, num_outputs, num_hiddens = 784, 10, 256 W1 = nd.random.normal(scale=0.01, shape=(num_inputs, num_hiddens)) b1 = nd.zeros(num_hiddens) W2 = nd.random.normal(scale=0.01, shape=(num_hiddens, num_outputs)) b2 = nd.zeros(num_outputs)
params = [W1, b1, W2, b2] for param in params: param.attach_grad()
使⽤基础的maximum函数来实现ReLU,而⾮直接调⽤relu函数。
def relu(X): return nd.maximum(X, 0)
通过reshape函数将每张原始图像改成⻓度为num_inputs的向量。
def net(X): X = X.reshape((-1, num_inputs)) H = relu(nd.dot(X, W1) + b1) return nd.dot(H, W2) + b2
为了得到更好的数值稳定性,我们直接使⽤Gluon提供的包括softmax运算和交叉熵损失计算的函数。
loss = gloss.SoftmaxCrossEntropyLoss()
设超参数迭代周期数为5,学习率为0.5。
num_epochs, lr = 5, 0.5 train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params, lr)
epoch 1, loss 0.8036, train acc 0.700, test acc 0.833 epoch 2, loss 0.4897, train acc 0.819, test acc 0.846 epoch 3, loss 0.4285, train acc 0.841, test acc 0.852 epoch 4, loss 0.3948, train acc 0.854, test acc 0.865 epoch 5, loss 0.3716, train acc 0.862, test acc 0.861