TensorFlow.JS — Using JavaScript Web Worker to Run ML Predict Function

This post is about Machine Learning on client-side. I will explain how to run ML model in JavaScript Web Worker. The model was trained in TensorFlow/Keras (using Python) to detect sentiment for a hotel review.

Andrej Baranovskij
Sep 7 · 5 min read
Source: Pixabay
  • How ML model was converted to be compatible with TensorFlow.js
  • JavaScript Web Worker to run TensorFlow.js predict function
JS app with TensorFlow.js
JS app with TensorFlow.js
JS app with TensorFlow.js
df = pd.read_csv('hotel-reviews.csv', nrows=100000)
df['REVIEW_TEXT'] = df['REVIEW_TEXT'].astype(str)
print('Number of rows ', df.shape[0])
model.fit(np.array(X_train_tokens), np.array(Y_train),
          validation_split=0.2, epochs=5, batch_size=128)
Model training results
tensorflowjs_converter --input_format keras hotel-reviews-model.h5 tensorflowjs/
  1. From app root folder run: ojet restore
  2. From app root folder run: ojet serve
if (!worker) {
  worker = new Worker("js/worker.js");
}worker.postMessage(seq);
worker.onmessage = function (event) {
  console.log('prediction: ' + event.data);
  self.negativityScore(event.data);
  self.sentiment(convertToSentiment(event.data));
};
importScripts('https://cdn.jsdelivr.net/npm/setimmediate@1.0.5/setImmediate.min.js');importScripts('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.2.7/dist/tf.min.js');tf.setBackend('cpu');
onmessage = async function (event) {
  console.log('executing worker');
  seq = event.data;
  if (!model) {
    model = await createModel();
  }
  input = tf.tensor(seq);
  input = input.expandDims(0);
  predictOut = model.predict(input);
  score = predictOut.dataSync()[0];
  postMessage(score);
  predictOut.dispose();
};async function createModel() {
  const model = await tf.loadLayersModel('ml/model.json')
  return model
}

Towards Data Science

Sharing concepts, ideas, and codes.

You're following Towards Data Science.

You’ll see more from Towards Data Science across Medium and in your inbox.

Comments

Ankita Kumari said…
Thank you for sharing this informative post. Looking forward to read more.
Professional Website Development Services India

Popular posts from this blog

Flutter for Single-Page Scrollable Websites with Navigator 2.0

A Data Science Portfolio is More Valuable than a Resume

Better File Storage in Oracle Cloud