Skip to content

Instantly share code, notes, and snippets.

@risenW
Created May 15, 2020 01:15
Show Gist options
  • Save risenW/d8b779ac80ea4538803756cb00023cdd to your computer and use it in GitHub Desktop.
Save risenW/d8b779ac80ea4538803756cb00023cdd to your computer and use it in GitHub Desktop.
//Updating model status
tstatus = document.getElementById('status')
predval = document.getElementById('predval')
//Load the CNN Model on page load
document.addEventListener('DOMContentLoaded', async () => {
await loadModel();
}, false);
async function loadModel() {
tstatus.innerText = 'Loading Model...'
model = await tf.loadLayersModel("http://localhost:3000/assets/model/model.json");
tstatus.innerText = 'Model Loaded Successfully. Start Drawing!'
// model.summary()
}
/**
* Preprocess the Image drawn on canvas and reshape it to [1,28,28,1]
*/
function getImageFromCanvas(image) {
let tensor = tf.browser.fromPixels(image)
.resizeNearestNeighbor([28, 28])
.mean(2)
.expandDims(2)
.expandDims()
.toFloat()
return tensor.div(255.0)
}
async function predict() {
let tensor = getImageFromCanvas(canvas);
let pred = await model.predict(tensor).argMax([-1])
predval.innerText = `This is a ${pred.arraySync()}`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment