Get started with keras-js CDN

MIT licensed

Keras-JS: Lightweight browser library for building, training deep neural models.

Tags:
  • keras
  • deep
  • learning
  • machine
  • neural
  • networks
  • javascript
  • webgl
  • gpu

Stable version

Copied!

How to start using keras-js CDN


// Include Keras.js library from the CDN
const keras = document.createElement('script');
keras.src = 'https://cdn.cdnhub.io/keras-js/0.3.0/keras.js';
document.head.appendChild(keras);

// Wait for Keras.js to be loaded
new Promise(resolve => {
  keras.onload = () => {
    // Prepare a simple neural network model
    const model = keras.sequential();
    model.add(keras.layers.dense({units: 32, inputShape: [784], activation: 'relu'}));
    model.add(keras.layers.dense({units: 10, activation: 'softmax'}));

    // Compile the model
    model.compile({
      optimizer: keras.optimizers.Adam(),
      loss: 'categoricalCrossent',
      metrics: ['accuracy']
    });

    // Load MNIST dataset
    const data = keras.image.loadDatasets('https://storage.googleapis.com/download.tensorflow.org/data/mnist.npz');

    // Preprocess the data
    const xs = data.train.x.map(x => keras.utils.toTensorXData(x));
    const ys = data.train.labels.map(y => keras.utils.toTensorYData(y));

    // Reshape the data to fit the model
    const xsBatch = keras.utils.arrayReshape(xs, [60000, 784]);

    // Train the model
    model.fit(xsBatch, ys, {
      epochs: 10,
      batchSize: 128
    });

    // Make predictions on test data
    const xTestBatch = keras.utils.arrayReshape(data.test.x, [10000, 784]);
    const yPred = model.predict(xTestBatch);

    // Print predictions
    console.log(yPred);

    // Remove the script tag
    document.head.removeChild(keras);
    resolve();
  };
});
Copied!

All versions