[playground] Tensorflow.Js & Typescript [1]: Quick Start

Posted at — Sep 27, 2022

TensorFlow is one of the most well-known libraries for machine learning. The most significant advantage of TensorFlow versus other libraries is designed to simplify the development of cross-platform projects.

These days, TensorFlow.js (Javascript) is a sub-project of Tensorflow that support three environments: Node.js, Web browser, and Mobile (via React Native). Unfortunately, Javascript is not a good programming language for data science projects because it is easy to make mistakes with little experience. There is another choice, and very familiar with the javascript ecosystem. TypeScript is a programming language with a strong type system that compiles to javascript. The development with Typescript is quick and less error-prone.

This tutorial will set up a development environment with Tensorflow.JS and TypeScript.

Github: https://github.com/quangtiencs/tensorflowjs_typescript_tutorials

NodeJS Evironment:

Create project directory

mkdir nodejs_tensorflowjs_typescript
cd nodejs_tensorflowjs_typescript

Initialize a new project. Follow the prompts of npm (nodejs package manager)

npm init

Install typescript compiler and more!

npm install --save-dev typescript tslint @types/node

TSC (Typescript Compiler) init

npx tsc --init

Edit tsconfig.json and add these lines:

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": [
    "src"
  ]
}

Install Tensorflow.js backend

npm install @tensorflow/tfjs-node

Add build and start command in package.json file:

{
  "name": "nodejs_tensorflowjs_typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npm run build ; node index.js",
    "build": "tsc"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^18.11.9",
    "tslint": "^6.1.3",
    "typescript": "^4.9.3"
  },
  "dependencies": {
    "@tensorflow/tfjs-node": "^4.1.0"
  }
}

Write our first tensorflowjs typescript program src/index.ts:

import { Tensor, tensor2d, Tensor2D } from "@tensorflow/tfjs-node"

let t1: Tensor2D = tensor2d([[1, 2], [3, 4], [5, 6]])
let t2: Tensor2D = tensor2d([[1, 2, 3], [4, 5, 6]])

console.log("Tensor 1")
t1.print()

console.log("Tensor 2")
t2.print()

console.log("Dot product")

let t3 : Tensor = t1.dot(t2)
t3.print()

t1.dispose()
t2.dispose()
console.log(t1.isDisposed)
console.log(t2.isDisposed)
console.log(t3.isDisposed)

Hello World

npm start

> tensorflowjs_typescript@1.0.0 start
> npm run build & node index.js


> tensorflowjs_typescript@1.0.0 build
> tsc

Tensor 1
Tensor
    [[1, 2],
     [3, 4],
     [5, 6]]
Tensor 2
Tensor
    [[1, 2, 3],
     [4, 5, 6]]
Dot product
Tensor
    [[9 , 12, 15],
     [19, 26, 33],
     [29, 40, 51]]
true
true
false

Nodejs tensorflowjs

Web browser Evironment:

Create project directory

mkdir webbrowser_tensorflowjs_typescript
cd webbrowser_tensorflowjs_typescript

Initialize a new project. Follow the prompts of npm (nodejs package manager)

npm init

Install typescript compiler and more!

npm install --save-dev typescript ts-loader tslint @types/node

TSC (Typescript Compiler) init

npx tsc --init

Edit tsconfig.json and add these lines:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node",
    "strict": true,
    "skipLibCheck": true
  },
  "include": [
    "src"
  ]
}

Install Tensorflow.js

npm install @tensorflow/tfjs

Install http-server and webpack

npm install --save-dev http-server webpack webpack-cli

Write index.html

<h1>Hello Tensorflow.js in Browser</h1>
<div id="place_holder_1"></div>
<div id="place_holder_2"></div>
<div id="place_holder_3"></div>
<script src="dist/bundle.js"></script>

Write webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

Add build and start command in package.json file:

{
  "name": "webbrowser_tensorflowjs_typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npm run build ;  npx http-server . -p 8888",
    "build": "npx webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^18.11.9",
    "http-server": "^14.1.1",
    "ts-loader": "^9.4.1",
    "tslint": "^6.1.3",
    "typescript": "^4.9.3",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.0"
  },
  "dependencies": {
    "@tensorflow/tfjs": "^4.1.0"
  }
}

Write our first tensorflowjs typescript program src/index.ts:

import { Tensor, tensor2d, Tensor2D } from "@tensorflow/tfjs"

let t1: Tensor2D = tensor2d([[1, 2], [3, 4], [5, 6]])
let t2: Tensor2D = tensor2d([[1, 2, 3], [4, 5, 6]])

console.log("Tensor 1")
t1.print()
let dom_1 = document.querySelector("#place_holder_1")
if (dom_1!=null){
    dom_1.innerHTML = t1.toString()
}

t1.toString()
console.log("Tensor 2")
t2.print()
let dom_2 = document.querySelector("#place_holder_2")
if (dom_2 != null) {
    dom_2.innerHTML = t2.toString()
}

console.log("Dot product")

let t3: Tensor = t1.dot(t2)
t3.print()
let dom_3 = document.querySelector("#place_holder_3")
if (dom_3 != null) {
    dom_3.innerHTML = "Dot Product: " + t1.toString()
}

t1.dispose()
t2.dispose()
console.log(t1.isDisposed)
console.log(t2.isDisposed)
console.log(t3.isDisposed)

Then start that program :D

npm start

Go to localhost:8888 and see the result:

Web browser tensorflowjs

Mobile Environment:

Requirements: Setting up the development environment

First, init react-native and go to the root directory of project:

npx react-native init react_native_tensorflowjs_typescript --template react-native-template-typescript
cd react_native_tensorflowjs_typescript

Then install all requirement packages:

npm install @react-native-async-storage/async-storage
npm install react-native-unimodules
npm install react-native-fs
npm install expo-gl expo-gl-cpp
npm install @tensorflow/tfjs
npm install @tensorflow/tfjs-react-native --legacy-peer-deps

Change App.tsx to:

import { Tensor, tensor2d, Tensor2D } from "@tensorflow/tfjs"
import React, {type PropsWithChildren} from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
} from 'react-native';

import {
  Colors,
  Header,
} from 'react-native/Libraries/NewAppScreen';

const Section: React.FC<
  PropsWithChildren<{
    title: string;
  }>
> = ({children, title}) => {
  const isDarkMode = useColorScheme() === 'dark';
  return (
    <View style={styles.sectionContainer}>
      <Text
        style={[
          styles.sectionTitle,
          {
            color: isDarkMode ? Colors.white : Colors.black,
          },
        ]}>
        {title}
      </Text>
      <Text
        style={[
          styles.sectionDescription,
          {
            color: isDarkMode ? Colors.light : Colors.dark,
          },
        ]}>
        {children}
      </Text>
    </View>
  );
};

const App = () => {
  const isDarkMode = useColorScheme() === 'dark';

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  let t1: Tensor2D = tensor2d([[1, 2], [3, 4], [5, 6]])
  let t2: Tensor2D = tensor2d([[1, 2, 3], [4, 5, 6]])


  return (
    <SafeAreaView style={backgroundStyle}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        style={backgroundStyle}>
        <Text style={{fontSize: 30}}>Tensorflow.JS TypeScript</Text>
        <View
          style={{
            backgroundColor: isDarkMode ? Colors.black : Colors.white,
          }}>
          <Section title="Tensor 1">
            {t1.toString()}
          </Section>
          <Section title="Tensor 2">
            {t1.toString()}
          </Section>
          <Section title="Dot product">
            {t1.dot(t2).toString()}
          </Section>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
});

export default App;

Then start the app (android or ios) by command:

npm run ios

React Native tensorflowjs