Creating and serving a Tensorflow javascript model in the browser.
In this tutorial we learn how to
We will create a simple model that models XOR operation. Given two inputs $(x_0, x_1)$ it outputs $y$
$$\left[\begin{array}{cc|c} x_0 & x_1 & y\\ 0 & 0 & 0\\ 0 & 1 & 1\\ 1 & 0 & 1\\ 1 & 1 & 0 \end{array}\right]$$Imports
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
import numpy as np
Using TensorFlow backend.
Initialize the inputs
X = np.array([[0,0],[0,1],[1,0],[1,1]])
y = np.array([[0],[1],[1],[0]])
Create the model
model = Sequential()
model.add(Dense(8, input_dim=2))
model.add(Activation('tanh'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
sgd = SGD(lr=0.1)
model.compile(loss='binary_crossentropy', optimizer=sgd)
Train the model
model.fit(X, y, batch_size=1, epochs=1000, verbose= 0)
<keras.callbacks.callbacks.History at 0x7fa063e40c88>
Predict the output
print(model.predict_proba(X))
[[0.00149857] [0.99531186] [0.9949425 ] [0.00591634]]
Save the model
model.save('saved_model/keras.h5')
Download the library
!pip install tensorflowjs
Convert the model
!tensorflowjs_converter --input_format keras saved_model/keras.h5 web_model
Import TensorFlow.js
header = '<head><script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.5.2/dist/tf.min.js"> </script>\n'
Code for loading the web model. We predict a tensor of zeros and show the result in the page.
script = '\
<script>\n\
async function loadModel(){ \n\
model = await tf.loadLayersModel(\'web_model/model.json\') \n\
y = model.predict(tf.zeros([1,2])) \n\
document.getElementById(\'out\').innerHTML = y.dataSync()[0] \n\
} \n\
loadModel() \n\
</script>\n\
</head> \n'
Body of the page
body = '\
<body>\n\
<p id =\'out\'></p> \n\
</body>'
Save the code as html file
with open('index.html','w') as f:
f.write(header+script+body)
f.close()