Skip to Main Content
Learning TensorFlow.js
book

Learning TensorFlow.js

by Gant Laborde
May 2021
Intermediate to advanced content levelIntermediate to advanced
338 pages
7h 44m
English
O'Reilly Media, Inc.
Content preview from Learning TensorFlow.js

Appendix B. Chapter Challenge Answers

Chapter 2: Truck Alert!

The MobileNet model can detect all kinds of different trucks. You could solve this problem by going through the list of identifiable trucks, or you can simply search for the word truck in the given list of class names. For simplicity, the provided answer did the latter.

The entire solution with HTML and JavaScript is here:

<!DOCTYPE html>
<html>
  <head>
    <script
    src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.7.0/dist/tf.min.js">
  </script>
    <script
    src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@1.0.0">
  </script> 1
    <script>
      mobilenet.load().then(model => {
        const img = document.getElementById('myImage'); 2
        // Classify the image
        model.classify(img).then(predictions => {
          console.log('Predictions: ', predictions);
          // Was there a truck?
          let foundATruck
          predictions.forEach(p => {
            foundATruck = foundATruck || p.className.includes("truck") 3
          })
          // TRUCK ALERT!
          if (foundATruck) alert("TRUCK DETECTED!") 4
        });
      });
    </script>
  </head>
  <body>
    <h1>Is this a truck?</h1>
    <img id="myImage" src="truck.jpg" width="100%"></img> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Go

Learning Go

Jon Bodner
Learning Algorithms

Learning Algorithms

George Heineman
Learning Spark, 2nd Edition

Learning Spark, 2nd Edition

Jules S. Damji, Brooke Wenig, Tathagata Das, Denny Lee

Publisher Resources

ISBN: 9781492090786Errata PageSupplemental Content