There are two kinds of future programmers, those who can machine learn and those who can’t
Laboo. Top /2018/11/21/…
The source code
digit-recognizer
demo
Lot – laziji. Making. IO/digit – recog… We need to load about 100 MB of training data at the start of the demo, wait a moment
Adjust the size of the training set and observe the accuracy of the test results
The data source
Data sources are recognizer with a title at www.kaggle.com the digi-recognizer gives 42,000 training pieces of data (including images and tags) and 28,000 test pieces (including images only) and requires them to be recognisable [0,1,2,3….,9] Be as accurate as possible
There are many other machine learning topics and data on the site, which is a great place to get your hands on it
implementation
Here we use tensorflow.js to implement the project
Create the model
The first layer of convolutional neural network has two functions. It is both the input layer and the executive layer, which receives black and white pixels of IMAGE_H * IMAGE_W size. The last layer is the output layer, which has 10 output units, representing the probability distribution of the ten values from 0 to 9, for example, Label=2. Output is [0.01, 0.02, 0.01, 0.9,…]
function createConvModel() {
const model = tf.sequential();
model.add(tf.layers.conv2d({
inputShape: [IMAGE_H, IMAGE_W, 1].kernelSize: 3.filters: 16.activation: 'relu'
}));
model.add(tf.layers.maxPooling2d({ poolSize: 2.strides: 2 }));
model.add(tf.layers.conv2d({ kernelSize: 3.filters: 32.activation: 'relu' }));
model.add(tf.layers.maxPooling2d({ poolSize: 2.strides: 2 }));
model.add(tf.layers.conv2d({ kernelSize: 3.filters: 32.activation: 'relu' }));
model.add(tf.layers.flatten({}));
model.add(tf.layers.dense({ units: 64.activation: 'relu' }));
model.add(tf.layers.dense({ units: 10.activation: 'softmax' }));
return model;
}
Copy the code
Training model
We select the appropriate optimizer and loss function to compile the model
async function train() {
ui.trainLog('Create model... ');
model = createConvModel();
ui.trainLog('Compile model... ');
const optimizer = 'rmsprop';
model.compile({
optimizer,
loss: 'categoricalCrossentropy'.metrics: ['accuracy']});const trainData = Data.getTrainData(ui.getTrainNum());
ui.trainLog('Training model... ');
await model.fit(trainData.xs, trainData.labels, {});
ui.trainLog('Completed! ');
ui.trainCompleted();
}
Copy the code
test
Here we test a set of test data and return the corresponding label, the subscript with the highest probability of the ten output units
function testOne(xs){
if(! model){ ui.viewLog('Need to train the model first');
return;
}
ui.viewLog('Testing... ');
let output = model.predict(xs);
ui.viewLog('Completed! ');
output.print();
const axis = 1;
const predictions = output.argMax(axis).dataSync();
return predictions[0];
}
Copy the code
Welcome to follow my blog public number