1 of 77

MACHINE LEARNING

FOR FRONT-END DEVELOPERS

Charlie Gerard / @devdevcharlie

2 of 77

Charlie Gerard

Front-end developer, Google Dev Expert & Mozilla Tech Speaker

3 of 77

WHAT IS MACHINE LEARNING

1

4 of 77

Giving the ability to computers to find patterns in data without being explicitly programmed

5 of 77

DIFFERENCE FROM TRADITIONAL PROGRAMMING

Example: Recognising spam emails

if(email.includes('viagra')){

filterAsSpam(email);

} else if(email.includes('v!agra')){

filterAsSpam(email);

} else if(...){

....

}

6 of 77

DIFFERENCE FROM TRADITIONAL PROGRAMMING

Example: Recognising spam emails

if(email.includes('viagra')){

filterAsSpam(email);

} else if(email.includes('v!agra')){

filterAsSpam(email);

} else if(...){

....

}

import * as spamModel from "model.json"

const model = load(spamModel);

const newEmail = getEmail();

const prediction = model.predict(newEmail);

prediction === 0 ? spam : not spam

7 of 77

ALGORITHMS

2

8 of 77

  • Naive Bayes

  • K-Nearest Neighbor (KNN)

  • Linear regression

  • Convolutional Neural Networks (CNN)

  • LSTM - Long Short Term Memory

  • ...

EXAMPLES OF ALGORITHMS

9 of 77

Supervised learning

Unsupervised learning

TYPES OF MACHINE LEARNING ALGORITHMS

Reinforcement learning

10 of 77

Supervised learning

TYPES OF MACHINE LEARNING ALGORITHMS

Reinforcement learning

Unsupervised learning

11 of 77

SUPERVISED LEARNING

Create predictive model based on a set of features

and labels.

12 of 77

SUPERVISED LEARNING

Create predictive model based on a set of features

and labels.

13 of 77

SUPERVISED LEARNING

Create predictive model based on a set of features

and labels.

14 of 77

SUPERVISED LEARNING

Create predictive model based on a set of features and labels.

15 of 77

SUPERVISED LEARNING

Create predictive model based on a set of features and labels.

Example: Predicting the price of a house

16 of 77

SUPERVISED LEARNING

Create predictive model based on a set of features and labels.

How you would classify each entry.

Example: Predicting the price of a house

Price

17 of 77

SUPERVISED LEARNING

Create predictive model based on a set of features and labels.

How you would classify each entry.

Example: Predicting the price of a house

Price

Characteristics of the entries in your dataset.

Number of rooms, floors, location, type of property, ...

18 of 77

SUPERVISED LEARNING

Create predictive model based on a set of features and labels.

How you would classify each entry.

Example: Predicting the price of a house

Price

Characteristics of the entries in your dataset.

Number of rooms, floors, location, type of property, ...

Mathematical representation of the outcome of your training.

Function that takes features as parameters and is able to predict a label as output.

19 of 77

UNSUPERVISED LEARNING

The ability to create predictions based only on a set of features.

20 of 77

UNSUPERVISED LEARNING

The ability to create predictions based only on a set of features.

21 of 77

UNSUPERVISED LEARNING

The ability to create predictions based only on a set of features.

Example: Predicting customer behaviour

22 of 77

APPLICATIONS

3

23 of 77

GENERATING ALT TEXT

24 of 77

FILTERING UNWANTED CONTENT

Nsfw.js by Gant Laborde

25 of 77

ACCESSIBILITY

26 of 77

MACHINE LEARNING

IN JAVASCRIPT

4

27 of 77

WHY

  • Accessible, easier learning curve.

28 of 77

WHY

  • Accessible, easier learning curve.

  • Rapid prototyping.

29 of 77

WHY

  • Accessible, easier learning curve.

  • Rapid prototyping.

  • Big ecosystem.

30 of 77

WHAT CAN YOU DO

Import an existing, pre-trained model.

31 of 77

WHAT CAN YOU DO

Import an existing, pre-trained model.

Re-train an imported model (transfer learning)

32 of 77

WHAT CAN YOU DO

Import an existing, pre-trained model.

Re-train an imported model (transfer learning)

Define, train and run models entirely in the browser.

33 of 77

TOOLS

34 of 77

DEMOS & CODE

5

35 of 77

USING A PRE-TRAINED MODEL

36 of 77

RECYCLING

37 of 77

CODE SAMPLE

import * as cocoSsd from "@tensorflow-models/coco-ssd";

import * as tf from '@tensorflow/tfjs-core';

let model = await cocoSsd.load();

let webcam = document.getElementById('webcam');

const webcamImage = tf.browser.fromPixels(webcam);

const batchedImage = webcamImage.expandDims(0);

const processedImage =

batchedImage.toFloat().div(tf.scalar(127)).sub(tf.scalar(1));

let predictions = await model.detect(processedImage);

return predictions;

38 of 77

CODE SAMPLE

import * as cocoSsd from "@tensorflow-models/coco-ssd";

import * as tf from '@tensorflow/tfjs-core';

let model = await cocoSsd.load();

let webcam = document.getElementById('webcam');

const webcamImage = tf.browser.fromPixels(webcam);

const batchedImage = webcamImage.expandDims(0);

const processedImage =

batchedImage.toFloat().div(tf.scalar(127)).sub(tf.scalar(1));

let predictions = await model.detect(processedImage);

return predictions;

39 of 77

CODE SAMPLE

import * as cocoSsd from "@tensorflow-models/coco-ssd";

import * as tf from '@tensorflow/tfjs-core';

let model = await cocoSsd.load();

let webcam = document.getElementById('webcam');

const webcamImage = tf.browser.fromPixels(webcam);

const batchedImage = webcamImage.expandDims(0);

const processedImage =

batchedImage.toFloat().div(tf.scalar(127)).sub(tf.scalar(1));

let predictions = await model.detect(processedImage);

return predictions;

40 of 77

CODE SAMPLE

import * as cocoSsd from "@tensorflow-models/coco-ssd";

import * as tf from '@tensorflow/tfjs-core';

let model = await cocoSsd.load();

let webcam = document.getElementById('webcam');

const webcamImage = tf.browser.fromPixels(webcam);

const batchedImage = webcamImage.expandDims(0);

const processedImage =

batchedImage.toFloat().div(tf.scalar(127)).sub(tf.scalar(1));

let predictions = await model.detect(processedImage);

return predictions;

41 of 77

TRANSFER LEARNING

42 of 77

THE TEACHABLE KEYBOARD

43 of 77

CODE SAMPLE

import * as mobilenetModule from '@tensorflow-models/mobilenet';

import * as tf from '@tensorflow/tfjs';

import * as knnClassifier from '@tensorflow-models/knn-classifier';

// Number of classes to classify

const NUM_CLASSES = 4;

// Webcam Image size. Must be 227.

const IMAGE_SIZE = 227;

// K value for KNN

const TOPK = 10;

const classes = ["Right", "Left", "Down", "Neutral"];

44 of 77

CODE SAMPLE

import * as mobilenetModule from '@tensorflow-models/mobilenet';

import * as tf from '@tensorflow/tfjs';

import * as knnClassifier from '@tensorflow-models/knn-classifier';

// Number of classes to classify

const NUM_CLASSES = 4;

// Webcam Image size. Must be 227.

const IMAGE_SIZE = 227;

// K value for KNN

const TOPK = 10;

const classes = ["Right", "Left", "Down", "Neutral"];

45 of 77

CODE SAMPLE

const knn = knnClassifier.create();

const mobilenet = await mobilenetModule.load();

const image = tf.browser.fromPixels(video);

let logits = mobilenet.infer(image, 'conv_preds');

knn.addExample(logits, training);

const res = await knn.predictClass(logits, TOPK);

console.log(classes[res.classIndex]) // ‘Right’, ‘Left’, …

// Dispose image when done

image.dispose();

46 of 77

CODE SAMPLE

const knn = knnClassifier.create();

const mobilenet = await mobilenetModule.load();

const image = tf.browser.fromPixels(video);

let logits = mobilenet.infer(image, 'conv_preds');

knn.addExample(logits, training);

const res = await knn.predictClass(logits, TOPK);

console.log(classes[res.classIndex]) // ‘Right’, ‘Left’, …

// Dispose image when done

image.dispose();

47 of 77

CODE SAMPLE

const knn = knnClassifier.create();

const mobilenet = await mobilenetModule.load();

const image = tf.browser.fromPixels(video);

let logits = mobilenet.infer(image, 'conv_preds');

knn.addExample(logits, training);

const res = await knn.predictClass(logits, TOPK);

console.log(classes[res.classIndex]) // ‘Right’, ‘Left’, …

// Dispose image when done

image.dispose();

48 of 77

CODE SAMPLE

const knn = knnClassifier.create();

const mobilenet = await mobilenetModule.load();

const image = tf.browser.fromPixels(video);

let logits = mobilenet.infer(image, 'conv_preds');

knn.addExample(logits, training);

const res = await knn.predictClass(logits, TOPK);

console.log(classes[res.classIndex]) // ‘Right’, ‘Left’, …

// Dispose image when done

image.dispose();

49 of 77

CODE SAMPLE

const knn = knnClassifier.create();

const mobilenet = await mobilenetModule.load();

const image = tf.browser.fromPixels(video);

let logits = mobilenet.infer(image, 'conv_preds');

knn.addExample(logits, training);

const res = await knn.predictClass(logits, TOPK);

console.log(classes[res.classIndex]) // ‘Right’, ‘Left’, …

// Dispose image when done

image.dispose();

50 of 77

CODE SAMPLE

const knn = knnClassifier.create();

const mobilenet = await mobilenetModule.load();

const image = tf.browser.fromPixels(video);

let logits = mobilenet.infer(image, 'conv_preds');

knn.addExample(logits, training);

const res = await knn.predictClass(logits, TOPK);

console.log(classes[res.classIndex]) // ‘Right’, ‘Left’, …

// Dispose image when done

image.dispose();

51 of 77

EVERYTHING!

52 of 77

THE WILLY DETECTOR

53 of 77

PROCESS

Hand-drawn

Quickdraw dataset

Data collection

54 of 77

PROCESS

200x200

Data processing

28x28

55 of 77

PROCESS

Splitting training / test set

Training data - 80%

Test data - 20%

56 of 77

PROCESS

Choose algorithm

Convolutional Neural Network (CNN) using Keras

57 of 77

PROCESS

Final steps

Parameter tuning

58 of 77

PROCESS

Final steps

Parameter tuning

Train

59 of 77

PROCESS

Final steps

Parameter tuning

Train

Prediction

60 of 77

CODE SAMPLE

getTrainData() {

const xs = tf.tensor4d(this.trainImages, [NUM_TRAIN_ELEMENTS, IMAGE_H, IMAGE_W, 1]);

const labels = tf.tensor2d(this.trainLabels, [this.trainLabels.length / NUM_CLASSES, NUM_CLASSES]);

return {xs, labels};

}

getTestData() {

let xs = tf.tensor4d(this.testImages,[this.testImages.length / IMAGE_SIZE, IMAGE_H, IMAGE_W, 1]);

let labels = tf.tensor2d(this.testLabels, [this.testLabels.length / NUM_CLASSES, NUM_CLASSES]);

return {xs, labels};

}

61 of 77

CODE SAMPLE

const model = tf.sequential();

model.add(tf.layers.conv2d({

inputShape: [28, 28, 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.flatten({}));

model.add(tf.layers.dense({units: 64, activation: 'relu'}));

model.add(tf.layers.dense({units: NUM_CLASSES, activation: 'softmax'}));

return model;

62 of 77

CODE SAMPLE

const trainData = getTrainData();

await model.fit(trainData.xs, trainData.labels, {

batchSize, // 2

validationSplit, // 0.15

epochs: trainEpochs, // 3

});

const examples = getTestData();

const output = model.predict(examples.xs);

const labels = Array.from(examples.labels.argMax().dataSync());

const predictions = Array.from(output.argMax().dataSync());

return {predictions, labels};

63 of 77

LIMITS

6

64 of 77

LIMITS

  • Need large amount of data (except if using pre-trained model).

65 of 77

LIMITS

  • Need large amount of data (except if using pre-trained model).

  • Can take a lot of time to train your own model.

66 of 77

LIMITS

  • Need large amount of data (except if using pre-trained model).

  • Can take a lot of time to train your own model.

  • Think about the mobile experience.

67 of 77

LIMITS

  • Need large amount of data (except if using pre-trained model).

  • Can take a lot of time to train your own model.

  • Think about the mobile experience.

  • Liability (some models are black boxes).

68 of 77

LIMITS

  • Need large amount of data (except if using pre-trained model).

  • Can take a lot of time to train your own model.

  • Think about the mobile experience.

  • Liability (some models are black boxes).

  • Bias / ethics.

69 of 77

ALGORITHMS ARE NOT BIASED,

WE ARE.

70 of 77

ETHICS

71 of 77

ADVERSARIAL EXAMPLES

“[...] deep-learning models are also brittle. Because an image recognition system relies only on pixel patterns rather than a deeper conceptual understanding of what it sees, it’s easy to trick the system into seeing something else entirely—just by disturbing the patterns in the right way.”

72 of 77

RESOURCES

7

73 of 77

TOOLS

74 of 77

USEFUL LINKS

75 of 77

DATASETS

76 of 77

77 of 77

MACHINE LEARNING FOR FRONT-END DEVELOPERS

THANK YOU!

@devdevcharlie