数字分类
用手写数字的 MNIST 数据库训练卷积网络预测一个给定图像的数字.
首先取得培训和验证数据.
In[1]:=
resource = ResourceObject["MNIST"];
trainingData = ResourceData[resource, "TrainingData"];
testData = ResourceData[resource, "TestData"];
In[2]:=
RandomSample[trainingData, 5]
Out[2]=
定义一个接受 28×28 的灰度图像为输入的卷积神经网络.
In[3]:=
lenet = NetChain[
{ConvolutionLayer[20, 5], Ramp, PoolingLayer[2, 2],
ConvolutionLayer[50, 5], Ramp, PoolingLayer[2, 2], FlattenLayer[],
500, Ramp, 10, SoftmaxLayer[]},
"Output" -> NetDecoder[{"Class", Range[0, 9]}],
"Input" -> NetEncoder[{"Image", {28, 28}, "Grayscale"}]
]
Out[3]=
对网络做四轮训练.
In[4]:=
lenet = NetTrain[lenet, trainingData, ValidationSet -> testData,
MaxTrainingRounds -> 3];
Out[5]=
在从验证集上随机抽样的图像上直接运行训练过的网络.
In[6]:=
imgs = Keys @ RandomSample[testData, 5];
Thread[imgs -> lenet[imgs]]
Out[6]=