TensorFlow.js
TensorFlow.js runs models directly in the browser via WebGL or WebGPU, with no server round-trip. You can train small models in-page or load a pre-trained model exported from Python TF and run inference on user data that never leaves the device. That privacy property is the main reason teams pick TF.js.
Load a pretrained model and predict in-browser
EXAMPLE
<!DOCTYPE html>
<html>
<head>
<script src='https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.20.0/dist/tf.min.js'></script>
</head>
<body>
<input type='file' id='file' accept='image/*'>
<img id='img' style='max-width:300px'>
<div id='out'></div>
<script type='module'>
import * as mobilenet from 'https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.1.1/dist/mobilenet.esm.js';
const model = await mobilenet.load();
const img = document.getElementById('img');
const out = document.getElementById('out');
document.getElementById('file').addEventListener('change', async (e) => {
const f = e.target.files[0];
if (!f) return;
img.src = URL.createObjectURL(f);
await img.decode();
const preds = await model.classify(img);
out.innerHTML = preds.map(p =>
`<div>${p.className}: ${(p.probability * 100).toFixed(1)}%</div>`
).join('');
});
</script>
</body>
</html>
Why it matters
WebGL backend is usually fastest on desktops with discrete GPUs; on mobile and low-end devices fall back to the WASM backend, which uses SIMD for predictable CPU performance.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
# Convert a Keras model to TF.js pip install tensorflowjs tensorflowjs_converter --input_format keras mymodel.keras tfjs_model/Try it Yourself »
Discussion
Loading…