coding-train

TensorFlow.js

Introduction

https://www.tensorflow.org/js/
https://github.com/tensorflow/tfjs
https://www.tensorflow.org/js/tutorials

TensorFlow.js is an open-source hardware-accelerated JavaScript library for training and deploying machine learning models.

APIs:

Backends/Platforms:

Getting Started

Via script tag

<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"> </script>


    <!-- Place your code in the script tag below. You can also use an external .js file -->
    <script>
      // Notice there is no 'import' statement. 'tf' is available on the index-page
      // because of the script tag above.

      // Define a model for linear regression.
      const model = tf.sequential();
      model.add(tf.layers.dense({units: 1, inputShape: [1]}));

      // Prepare the model for training: Specify the loss and the optimizer.
      model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

      // Generate some synthetic data for training.
      const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
      const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

      // Train the model using the data.
      model.fit(xs, ys).then(() => {
        // Use the model to do inference on a data point the model hasn't seen before:
        // Open the browser devtools to see the output
        model.predict(tf.tensor2d([5], [1, 1])).print();
      });
    </script>
  </head>

  <body>
  </body>
</html>

via NPM

Add TensorFlow.js to your project using yarn or npm.
Note: Because we use ES2017 syntax (such as import), this workflow assumes you are using a modern browser or a bundler/transpiler to convert your code to something older browsers understand. See our examples to see how we use Parcel to build our code. However, you are free to use any build tool that you prefer.

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

// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

// Train the model using the data.
model.fit(xs, ys).then(() => {
  // Use the model to do inference on a data point the model hasn't seen before:
  model.predict(tf.tensor2d([5], [1, 1])).print();
});

What is Tensors

Tensors are the core datastructure of TensorFlow.js They are a generalization of vectors and matrices to potentially higher dimensions.

Creation

We have utility functions for common cases like Scalar, 1D, 2D, 3D and 4D tensors, as well a number of functions to initialize tensors in ways useful for machine learning.

tf.tensor (values, shape?, dtype?) - function

Creates a tf.Tensor with the provided values, shape and dtype. Parameters:

Returns: tf.Tensor

// Pass an array of values to create a vector.
tf.tensor([1, 2, 3, 4]);

// Pass a nested array of values to make a matrix or a higher
// dimensional tensor.
tf.tensor([[1, 2], [3, 4]])

// Pass a flat array and specify a shape yourself.
tf.tensor([1, 2, 3, 4], [2, 2])

tf.scalar (values, dtype?) - function

Creates rank-0 tf.Tensor (scalar) with the provided value and dtype.

Returns: tf.Scalar

tf.scalar(3.14);

others

Tensors/Classes

Variables & Operations

Memory Managements

텐서들은 기본적으로 메모리 공간에 따로 저장되고, 따라서 비동기로 동작하게 됨. 위의 tf.Tensor.data()Promise를 리턴하는 것을 보면 알 수 있음.

const values = [];
for (let i = 0; i < 30; i++) {
    values[i] = Math.random(0, 100);
}
const shape = [2, 5, 3];
const ts = tf.tensor3d(values, shape, 'int32');
ts.data().then(data => {
    console.log(data); // -> Int32Array(30)
});

위 예제에서 보듯, 실제 데이터의 저장은 3D tensor임에도 1D로 저장됨을 알 수 있음. 그냥 출력을 원하면 ts.print()를 사용하면 콘솔 창에서 3차원 배열 형태로 볼 수 있음. 혹은 ts.dataSync()를 사용할 수도 있음.

메모리를 해제하고 싶다면 ts.dispose()와 같은 식으로 할당을 해제할 수 있음.

Memory API

Variables

텐서는 기본적으로 immutable이며, 값을 바꾸고 싶다면 tf.Variable을 사용한다.

const tv = ts.variable(0);

Operations

Layers API

Similar to Keras (Keras API를 모델로 함)
You can architect NeuralNetwork using Layers API.
https://www.tensorflow.org/js/guide/models_and_layers

개요

Layers API

Custom Layer

Core API