How to use the @tensorflow/tfjs.sequential function in @tensorflow/tfjs

To help you get started, we’ve selected a few @tensorflow/tfjs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github googlecreativelab / teachablemachine-community / image / src / teachable-mobilenet.ts View on Github external
const validationData = this.validationDataset.batch(params.batchSize);

        // For debugging: check for shuffle or result from trainDataset
        /*
        await trainDataset.forEach((e: tf.Tensor[]) => {
            console.log(e);
        })
        */

        const history = await this.trainingModel.fitDataset(trainData, {
            epochs: params.epochs,
            validationData,
            callbacks
        });

        const jointModel = tf.sequential();
        jointModel.add(this.truncatedModel);
        jointModel.add(this.trainingModel);
        this.model = jointModel;

        optimizer.dispose(); // cleanup of memory

        return this.model;
    }
github eram / tensorflow-stack-ts / scripts / verifyTF.js View on Github external
// Load the TF Node binding:
    const tfjsn = require("@tensorflow/tfjs-node"); // Use '@tensorflow/tfjs-node-gpu' if running with GPU.
    if (!tfjsn) {
        throw new Error("@tensorflow/tfjs-node failed to load.")
    };

    // Load TF
    const tf = require("@tensorflow/tfjs");
    if (!tf || !tf.sequential) {
        throw new Error("@tensorflow/tfjs failed to load.");
    }

    console.log(`TF Backend: ${tf.getBackend()}`);
    console.log("\nTEST: TRAINING...");

    const model = tf.sequential();
    model.add(tf.layers.dense({
        inputShape: [1],
        units: 1,
    }));
    model.compile({
        loss: "meanSquaredError",
        optimizer: "sgd",
    });

    const xArr = new Float32Array(6);
    let i = 0;
    [-1, 0, 1, 2, 3, 4].forEach(elem => {
        xArr[i++] = Number(elem);
    });

    const yArr = new Float32Array([-3, -1, 1, 3, 5, 7]);
github tensorflow / tfjs-examples / webcam-transfer-learning / index.js View on Github external
async function train() {
  if (controllerDataset.xs == null) {
    throw new Error('Add some examples before training!');
  }

  // Creates a 2-layer fully connected model. By creating a separate model,
  // rather than adding layers to the mobilenet model, we "freeze" the weights
  // of the mobilenet model, and only train weights from the new model.
  model = tf.sequential({
    layers: [
      // Flattens the input to a vector so we can use it in a dense layer. While
      // technically a layer, this only performs a reshape (and has no training
      // parameters).
      tf.layers.flatten(
          {inputShape: truncatedMobileNet.outputs[0].shape.slice(1)}),
      // Layer 1.
      tf.layers.dense({
        units: ui.getDenseUnits(),
        activation: 'relu',
        kernelInitializer: 'varianceScaling',
        useBias: true
      }),
      // Layer 2. The number of units of the last layer should correspond
      // to the number of classes we want to predict.
      tf.layers.dense({
github radi-cho / tfjs-firebase / functions / src / linear_model / index.js View on Github external
exports.runLinearModel = functions.https.onRequest((request, response) => {
  // Get x_test value from the request body
  const x_test = Number(request.body.x);

  // Check if the x value is number. Otherwise request a valid one and terminate the function.
  if (typeof x_test !== "number" || isNaN(x_test))
    response.send("Error! Please format your request body.");

  // Define a model for linear regression.
  const linearModel = tf.sequential();
  linearModel.add(
    tf.layers.dense({
      units: 1,
      inputShape: [1]
    })
  );

  // Prepare the model for training: Specify the loss and the optimizer.
  linearModel.compile({
    loss: "meanSquaredError",
    optimizer: "sgd"
  });

  // Process the Firestore data
  db.collection("linear-values")
    .get()
github driescroons / snaike / src / brain / brain.ts View on Github external
private createModel() {
    const model = tf.sequential();
    const hiddenOne = tf.layers.dense({
      units: this.hiddenNodes,
      inputShape: [this.inputNodes],
      activation: "relu"
    });
    model.add(hiddenOne);
    // const hiddenTwo = tf.layers.dense({
    // 	units: 15,
    // 	activation: 'relu',
    // })
    // model.add(hiddenTwo)
    const output = tf.layers.dense({
      units: this.outputNodes,
      activation: "softmax"
    });
    model.add(output);
github piximi / application / src / classifierBackup.js View on Github external
'indexeddb://classifier'
  );

  //get some intermediate layer
  const layer = preLoadedmodel.getLayer('conv_pw_13_relu');

  let tmpModel = tensorflow.model({
    inputs: preLoadedmodel.inputs,
    outputs: layer.output
  });

  for (let i = 0; i < tmpModel.layers.length; i++) {
    tmpModel.layers[i].trainable = false;
  }

  const model = tensorflow.sequential({
    layers: [
      // Flattens the input to a vector so we can use it in a dense layer. While
      // technically a layer, this only performs a reshape (and has no training
      // parameters).
      tensorflow.layers.flatten({
        inputShape: [
          tmpModel.output.shape[1],
          tmpModel.output.shape[2],
          tmpModel.output.shape[3]
        ]
      }),
      tensorflow.layers.dense({
        units: 100,
        activation: 'relu',
        kernelInitializer: 'varianceScaling',
        useBias: true
github tensorflow / tfjs-models / speech-commands / training / browser-fft / train.ts View on Github external
export function createBrowserFFTModel(
    inputShape: tf.Shape, numClasses: number): tf.Model {
  const model = tf.sequential();
  model.add(tf.layers.conv2d(
      {filters: 8, kernelSize: [2, 8], activation: 'relu', inputShape}));
  model.add(tf.layers.maxPooling2d({poolSize: [2, 2], strides: [2, 2]}));
  model.add(
      tf.layers.conv2d({filters: 32, kernelSize: [2, 4], activation: 'relu'}));
  model.add(tf.layers.maxPooling2d({poolSize: [2, 2], strides: [2, 2]}));
  model.add(
      tf.layers.conv2d({filters: 32, kernelSize: [2, 4], activation: 'relu'}));
  model.add(tf.layers.maxPooling2d({poolSize: [2, 2], strides: [2, 2]}));
  model.add(
      tf.layers.conv2d({filters: 32, kernelSize: [2, 4], activation: 'relu'}));
  model.add(tf.layers.maxPooling2d({poolSize: [2, 2], strides: [1, 2]}));
  model.add(tf.layers.flatten({}));
  model.add(tf.layers.dropout({rate: 0.25}));
  model.add(tf.layers.dense({units: 2000, activation: 'relu'}));
  model.add(tf.layers.dropout({rate: 0.5}));
github tensorflow / tfjs-examples / lstm-text-generation / index.js View on Github external
createModel(lstmLayerSizes) {
    if (!Array.isArray(lstmLayerSizes)) {
      lstmLayerSizes = [lstmLayerSizes];
    }

    this.model = tf.sequential();
    for (let i = 0; i < lstmLayerSizes.length; ++i) {
      const lstmLayerSize = lstmLayerSizes[i];
      this.model.add(tf.layers.lstm({
        units: lstmLayerSize,
        returnSequences: i < lstmLayerSizes.length - 1,
        inputShape: i === 0 ? [this.sampleLen_, this.charSetSize_] : undefined
      }));
    }
    this.model.add(
        tf.layers.dense({units: this.charSetSize_, activation: 'softmax'}));
  }
github tensorflow / tfjs / demos / pacman / pacman.ts View on Github external
async function train() {
  trainStatus.innerHTML = 'Training...';
  await tf.nextFrame();
  await tf.nextFrame();

  isPredicting = false;
  model = tf.sequential({
    layers: [
      tf.layers.flatten({inputShape: [7, 7, 256]}), tf.layers.dense({
        units: getDenseUnits(),
        activation: 'relu',
        kernelInitializer: 'VarianceScaling',
        kernelRegularizer: 'L1L2',
        useBias: true,
        inputShape: [1000]
      }),
      tf.layers.dense({
        units: NUM_CLASSES,
        kernelInitializer: 'VarianceScaling',
        kernelRegularizer: 'L1L2',
        useBias: false,
        activation: 'softmax'
      })
github PAIR-code / federated-learning / demo / decision_boundary / src / server.js View on Github external
function setupModel() {
  const model = tf.sequential();
  model.add(tf.layers.dense({units: 10, inputShape: [2], activation: 'sigmoid'}));
  model.add(tf.layers.dense({units: 10, activation: 'sigmoid'}));
  model.add(tf.layers.dense({units: 2, activation: 'softmax'}));
  return model;
}