Wolfram Language

Neural Networks

Digit Classification

Use the MNIST database of handwritten digits to train a convolutional network to predict the digit given an image.

First obtain the training and validation data.

In[1]:=
Click for copyable input
resource = ResourceObject["MNIST"]; trainingData = ResourceData[resource, "TrainingData"]; testData = ResourceData[resource, "TestData"];
In[2]:=
Click for copyable input
RandomSample[trainingData, 5]
Out[2]=

Define a convolutional neural network that takes in 28×28 grayscale images as input.

In[3]:=
Click for copyable input
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]=

Train the network for four training rounds.

In[4]:=
Click for copyable input
lenet = NetTrain[lenet, trainingData, ValidationSet -> testData, MaxTrainingRounds -> 3];
Out[5]=

Evaluate the trained network directly on images randomly sampled from the validation set.

In[6]:=
Click for copyable input
imgs = Keys @ RandomSample[testData, 5]; Thread[imgs -> lenet[imgs]]
Out[6]=

Related Examples

de es fr ja ko pt-br ru zh