Getting Started with Tensorflow.js

Tue, Sep 03 20192 min read
Computer science is no more about computers than astronomy is about telescopes.
--Edsger Dijkstra
In order to have easy way of Machine learning in Javascript, you need Tensorflow.js, this guide will help you setup Tensorflow.js with Node.js environment.


Before you start, you need at least:
  • Node.js > 10
  • Windows or Linux
  • A Terminal


If you have a CPU, things were super easy.
just create a new repo with
npm init
and install the tfjs native c++ bindings.
npm install @tensorflow/tfjs-node
If you have a Nvidia gpu, and wish to use it to your advantage, things get more complicated.
First you need:
| NVIDIA® GPU drivers | >410.x | | ------------------------------------------------------------ | ------- | | CUDA® Toolkit | 10.0 | | cuDNN SDK | >=7.4.1 |
you also need Python2.7 if you plan to use windows.


After download and install those tools, you need to setup the PATH variable
SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\bin;%PATH%
SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\extras\CUPTI\libx64;%PATH%
SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\include;%PATH%
SET PATH=C:\tools\cuda\bin;%PATH%
then you need windows-build-tools:
npm install -g --production windows-build-tools
make sure you have node-gyp
npm install -g node-gyp
and finally you can:
npm install @tensorflow/tfjs-node-gpu
now run this sample program:
const tf = require('@tensorflow/tfjs');
// Train a simple model:
const model = tf.sequential();
model.add(tf.layers.dense({ units: 100, activation: 'relu', inputShape: [10] }));
model.add(tf.layers.dense({ units: 1, activation: 'linear' }));
model.compile({ optimizer: 'sgd', loss: 'meanSquaredError' });
const xs = tf.randomNormal([100, 10]);
const ys = tf.randomNormal([100, 1]);, ys, {
epochs: 100,
callbacks: {
onEpochEnd: (epoch, log) => console.log(`Epoch ${epoch}: loss = ${log.loss}`)
now you got blazing fast ML computing on your gpu.


Continue with
to comment