Training & Transfer Learning
Defining & Training a Model
// Mirrors Keras's Sequential API almost exactly
const model = tf.sequential({
layers: [
tf.layers.dense({ units: 16, activation: 'relu', inputShape: [4] }),
tf.layers.dense({ units: 1, activation: 'sigmoid' }),
],
});
model.compile({ optimizer: 'adam', loss: 'binaryCrossentropy', metrics: ['accuracy'] });
const xs = tf.tensor2d(features);
const ys = tf.tensor2d(labels);
await model.fit(xs, ys, {
epochs: 50,
callbacks: { onEpochEnd: (epoch, logs) => console.log(epoch, logs.loss) },
});Transfer Learning
import * as mobilenet from '@tensorflow-models/mobilenet';
// Reuse MobileNet's learned features, fine-tune only a small new head —
// far less data/time needed than training a full model from scratch
const baseModel = await mobilenet.load();
const activation = baseModel.infer(imgElement, true); // intermediate features
const classifier = tf.sequential({
layers: [tf.layers.dense({ units: 3, activation: 'softmax', inputShape: [1024] })],
});
classifier.compile({ optimizer: 'adam', loss: 'categoricalCrossentropy' });
await classifier.fit(activation, customLabels, { epochs: 10 });Client-Side vs. Server-Side Trade-offs
Running inference in the browser keeps user data on-device (privacy) with no network round-trip (latency) — but the model file itself is downloaded to the client, runs on whatever hardware the user has, and can be extracted/inspected by anyone with browser dev tools. For proprietary or sensitive models, that IP-exposure risk is a real reason to keep inference server-side instead, trading away the privacy/latency benefit.
Node.js for Performance
// package.json: "@tensorflow/tfjs-node": "^4.x"
const tf = require('@tensorflow/tfjs-node'); // binds to native TensorFlow C++ —
// much faster than browser WebGL
const model = await tf.loadLayersModel('file://./model/model.json');Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free