Home

How to use TensorFlow.js with Angular 2+

If you are a frontend dev looking to play around with neural networks, this short guide may help you get started faster.

You will not learn any machine learning here. The goal is just to help you integrate (well, literally copy & paste, heh) the TensorFlow.js examples into your Angular application.

After you have done that, it becomes easier to start adapting the examples in order to match your specific needs.

Enjoy!

1. Create a new Angular application

$ ng new tfjs-with-angular

Note: I’m using Angular version 9.1.4

2. Install Tfjs

$ npm install --save @tensorflow/tfjs @tensorflow/tfjs-vis @tensorflow-models/mobilenet

3. Prevent TypeScript errors

Add the following lines to stop TypeScript errors:

package.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": ["es2018", "dom"],
    "skipLibCheck": true  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

You can remove // @ts-nocheck (bellow) later on - when you are done converting all the JS to TS.

app.component.ts
// @ts-nocheck/
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'tfjs-with-angular';
}

3. Add example code from tfjs-examples

In this guide we are using the addition-rnn example from their GitHub.

  1. Copy their index.js in your app.component.ts, and run OnInit.
app.components.ts
// @ts-nocheck

import { Component } from '@angular/core';

import * as tf from '@tensorflow/tfjs';import * as tfvis from '@tensorflow/tfjs-vis';[ ... rest of index.js code here... ]
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  title = 'tfjs-with-angular';

  ngOnInit() {
    runAdditionRNNDemo();  }
}
  1. Add the code from their index.html into app.component.html

Note: you may need to replace </input> closing tags with <input/>.

app.component.html
<div class="tfjs-example-container centered-container">
  <section class="title-area">
    <h1>TensorFlow.js: Addition RNN</h1>
    <p class="subtitle">Train a model to learn addition by example</p>
  </section>
  <section>
    <p class="section-head">Description</p>
    <p>
      This example trains a
      <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network"
        >Recurrent Neural Network</a
      >
      to do addition without explicitly defining the addition operator. Instead
      we feed it examples of sums and let it learn from that.
    </p>
    <p>
      Given a <span class="in-type">string</span> like
      <span class="in-example">3 + 4</span>, it will learn to output a
      <span class="out-type">number</span> like
      <span class="out-example">7</span>.
    </p>
    <p>
      This example generates it's own training data programatically.
    </p>
  </section>

  <div>
    <section>
      <p class="section-head">Instructions</p>
      <p>
        Click the "Train Model" to start the model training button. You can edit
        the parameters used to train the model as well.
      </p>
    </section>

    <div class="controls with-rows">
      <div class="settings">
        <div class="setting">
          <span class="setting-label">Digits:</span>
          <input id="digits" value="2" />
        </div>
        <div class="setting">
          <span class="setting-label">Training Size:</span>
          <input id="trainingSize" value="5000" />
        </div>
        <div class="setting">
          <span class="setting-label">RNN Type:</span>
          <select id="rnnType">
            <option value="SimpleRNN">SimpleRNN</option>
            <option value="GRU">GRU</option>
            <option value="LSTM">LSTM</option>
          </select>
        </div>
        <div class="setting">
          <span class="setting-label">RNN Layers:</span>
          <input id="rnnLayers" value="1" />
        </div>
        <div class="setting">
          <span class="setting-label">RNN Hidden Layer Size:</span>
          <input id="rnnLayerSize" value="128" />
        </div>
        <div class="setting">
          <span class="setting-label">Batch Size:</span>
          <input id="batchSize" value="128" />
        </div>
        <div class="setting">
          <span class="setting-label">Train Iterations:</span>
          <input id="trainIterations" value="100" />
        </div>
        <div class="setting">
          <span class="setting-label"># of test examples:</span>
          <input id="numTestExamples" value="20" />
        </div>
      </div>

      <div>
        <span>
          <button class="btn-primary" id="trainModel">Train Model</button>
        </span>
      </div>
    </div>

    <section>
      <p class="section-head">Training Progress</p>
      <p id="trainStatus"></p>
      <div class="with-cols">
        <div id="lossChart"></div>
        <div id="accuracyChart"></div>
        <!-- <div id="examplesPerSecCanvas"></div> -->
      </div>
    </section>

    <section>
      <p class="section-head">Test Examples</p>
      <p id="testExamples"></p>
    </section>
  </div>
</div>
  1. Add their styles into your global styles.scss.

Note: You may need to include their shared styles as well as project specific styles.

4. Run the code

$ ng serve
TensorFlow.js working
And voila, it works!

5. Next Steps

From here you can experiment with their examples, as well as replace their DOM manipulation with something more the Angular way.

The final code can be found here.