Tensorflow JS: Linear Regression with Webpack and ES6 Classes

AI in the browser [1 of 2] Creating a Tensorflow JS model in a Webpack environment

Prelude: AI is now in the browser, with Tensorflow JS

How capable is Tensorflow JS now?

Tensor: Multi-dimensional array of numbers

Solution Briefing

// execution of a tensorflow JS prediction solutionget data -> define model -> format data for model -> train model -> make predictions
// models/VehicleEfficiency.jsclass VehicleEfficiency {   // class properties to handle configuration of model   // configure the instantiated object within constructor
constructor(config) {
}
// a method that retrieves the raw data we need to train the model
async getData() {}
// a method for defining the layers of the model and model type itself
createModel() {}
// a method to format data into tensors
dataToTensors() {}
// a method to train the model
async train() {}
// a method to make predictions
predict(inputData) {}
// an initialiser method that creates and trains the model, ready for predictions
async init() {
await this.getData();
this.createModel();
this.dataToTensors();
await this.train();
}
}

Alternatives to Webpack for Tensorflow JS

Setting up a Webpack project for Tensorflow JS

# create project directory
mkdir tfjs-linear-reg
cd tfjs-linear-reg
# initiate a new package.json
yarn init
#install tensorflow js and webpack dependencies
yarn add webpack webpack-cli \
@tensorflow/tfjs @tensorflow/tfjs-vis
#install babel plugins
yarn add --dev babel-loader babel-polyfill \
@babel/core \
@babel/preset-env \
@babel/plugin-proposal-class-properties

package.json build script

// package.json{
"mode": "development",
"scripts": {
"build": "webpack --config webpack.config.js"
},

...
}

Webpack configuration in webpack.config.js

const path = require('path');module.exports = {
mode: 'development',
entry: ['babel-polyfill', './src/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-proposal-class-properties']
}
}
}
]
}
};

Project structure

dist/
src/
index.js
models/
VehicleEfficiency.js
index.html
package.json
webpack.config.json
...

Tensorflow JS VehicleEfficiency Class

class VehicleEfficieny {
tfvis = true;
...
}
// toggling tfjs-vis graphs with this.tfvisif (this.tfvis) {   // generate graphs here
tfvis.render.scatterplot(
...
);
}
how tfjs-vis looks in the browser

Gathering data

// fetch data
const carsDataReq = await fetch(this.dataUrl);
const carsData = await carsDataReq.json();
^
format result as JSON object
// map data to create `cleaned` object storing mpg and horsepower
const cleaned = carsData.map(car => ({
mpg: car.Miles_per_Gallon,
horsepower: car.Horsepower,
}))
.filter(car => (car.mpg != null && car.horsepower != null));
^
only include entries where mpg and horsepower are defined

Creating the model

// creating a sequential model with two layerscreateModel () {   // instantiate a model
const model = tf.sequential();
// hidden layer
model.add(tf.layers.dense({ inputShape: [1], units: 1, useBias: true }));
// output layer
model.add(tf.layers.dense({ units: 1, useBias: true }));

// assign model as class property
this.model = model;
...
}

Up Next

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store