How to use the @tensorflow/tfjs.tensor2d 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 victordibia / anomagram / app / src / components / train / Train.jsx View on Github external
for (let row in this.trainData) {
            let val = this.trainData[row]
            if (val.target + "" === 1 + "") { 
                if (trainEcg.length < this.state.trainDataSize) {
                    trainEcg.push(val)
                } else {
                    break
                }
            }  
        }

        // console.log(maxAbnormalCount, "abnormal samples",  abnormalCount, "Total", trainEcg.length);
        

        // Create train tensor from json array
        this.xsTrain = tf.tensor2d(trainEcg.map(item => item.data
        ), [trainEcg.length, trainEcg[0].data.length])
        this.setState({ trainDataShape: this.xsTrain.shape })


        // Create test data TENSOR from test data json array 
        let testData = this.testData.slice(0, this.state.testDataSize)
        this.xsTest = tf.tensor2d(testData.map(item => item.data
        ), [testData.length, testData[0].data.length])

        // Create yLabel Tensor
        this.yTest = testData.map(item => item.target + "" === 1 + "" ? 0 : 1)

        this.setState({ testDataShape: this.xsTest.shape })

    }
github studentinsights / studentinsights / app / assets / javascripts / student_profile / LightNotesDetails.js View on Github external
// const input = tf.tensor2d(sequence, [1, 13000]);
    log('starting...');

    // const input = tf.tensor2d(sequence);
    // const paddedSequence = padSequences([sequence], 13000);
    // log('paddedSequence', paddedSequence);
    // sequence.forEach(index => paddedSequence[index] = 1);
    // log('ones', _.flatMap(paddedSequence, (val, i) => val === 1 ? [i] : []));
    const paddedSequence = _.range(0, 13000).map(index => {
      return (sequence.indexOf(index) !== -1) ? 1 : 0;
    });
    log('ones', _.flatMap(paddedSequence, (val, i) => val === 1 ? [i] : []));

    // do prediction
    const input = tf.tensor2d(paddedSequence, [1, 13000]);
    log('input', input);
    const prediction = model.predict(input);
    log('prediction', prediction);
    const score = prediction.dataSync()[0];
    log('score', score);
    prediction.dispose();
    return score;
  } catch(err) {
    console.error('caught');
    console.error(err);
    return null;
  }
}
github tensorflow / magenta-js / music / src / transcription / transcription_utils.ts View on Github external
const actualBatchLength = batchLength + 2 * RF_PAD;
  const firstBatch =
      tf.tensor2d(input.slice(0, actualBatchLength)).expandDims(0) as
      tf.Tensor3D;
  const lastBatch = tf.tensor2d(input.slice(input.length - actualBatchLength))
                        .expandDims(0) as tf.Tensor3D;

  if (batchSize === 2) {
    return tf.concat([firstBatch, lastBatch], 0);
  }

  // Add zero padding to make the length divisible by the
  // this.batchLength. Don't worry about receptive field padding for now.
  let naivePaddedBatches;
  if (batchRemainder) {
    naivePaddedBatches = tf.tensor2d(input)
                             .pad([[0, batchLength - batchRemainder], [0, 0]])
                             .as3D(batchSize, batchLength, -1);
  } else {
    naivePaddedBatches =
        tf.tensor2d(input.slice(0, input.length - mergedRemainder))
            .as3D(batchSize, batchLength, -1);
  }
  // Slice out the receptive field padding we will need for all but the
  // first and last batch.
  const leftPad = tf.slice(
      naivePaddedBatches, [0, batchLength - RF_PAD], [batchSize - 2, -1]);
  const rightPad = tf.slice(naivePaddedBatches, [2, 0], [-1, RF_PAD]);
  // Pad the middle (not first and last) to cover the receptive field.
  const midBatches = tf.concat(
      [leftPad, naivePaddedBatches.slice(1, batchSize - 2), rightPad], 1);
github zy445566 / tfjs-tutorials-zh / tutorials / code / core-concepts / operations.js View on Github external
const tf = require('@tensorflow/tfjs');

// Load the binding:
// 这里可以解锁cpu性能,不安装的话命令行会有一行提示,但这个包需要翻墙,可能对初学者会有一些困难
// 安装了的话,直接解除注释即可使用
// require('@tensorflow/tfjs-node');
// 这里可以解锁gpu性能,和上面一致,不多说,电脑性能好的,可以二选一使用
// Use '@tensorflow/tfjs-node-gpu' if running with GPU.

const d = tf.tensor2d([[1.0, 2.0], [3.0, 4.0]]);
const d_squared = d.square();
d_squared.print();
// Output: [[1, 4 ],
//          [9, 16]]

const e = tf.tensor2d([[1.0, 2.0], [3.0, 4.0]]);
const f = tf.tensor2d([[5.0, 6.0], [7.0, 8.0]]);

const e_plus_f = e.add(f);
e_plus_f.print();
// Output: [[6 , 8 ],
//          [10, 12]]
github tensorflow / magenta-js / music / src / transcription / transcription_utils.ts View on Github external
.expandDims(0) as tf.Tensor3D;

  if (batchSize === 2) {
    return tf.concat([firstBatch, lastBatch], 0);
  }

  // Add zero padding to make the length divisible by the
  // this.batchLength. Don't worry about receptive field padding for now.
  let naivePaddedBatches;
  if (batchRemainder) {
    naivePaddedBatches = tf.tensor2d(input)
                             .pad([[0, batchLength - batchRemainder], [0, 0]])
                             .as3D(batchSize, batchLength, -1);
  } else {
    naivePaddedBatches =
        tf.tensor2d(input.slice(0, input.length - mergedRemainder))
            .as3D(batchSize, batchLength, -1);
  }
  // Slice out the receptive field padding we will need for all but the
  // first and last batch.
  const leftPad = tf.slice(
      naivePaddedBatches, [0, batchLength - RF_PAD], [batchSize - 2, -1]);
  const rightPad = tf.slice(naivePaddedBatches, [2, 0], [-1, RF_PAD]);
  // Pad the middle (not first and last) to cover the receptive field.
  const midBatches = tf.concat(
      [leftPad, naivePaddedBatches.slice(1, batchSize - 2), rightPad], 1);

  return tf.concat([firstBatch, midBatches, lastBatch], 0);
}
github tensorflow / tfjs-examples / iris-fitDataset / index.js View on Github external
tf.tidy(() => {
    // Prepare input data as a 2D `tf.Tensor`.
    const inputData = ui.getManualInputData();
    const input = tf.tensor2d([inputData], [1, 4]);

    // Call `model.predict` to get the prediction output as probabilities for
    // the Iris flower categories.

    const predictOut = model.predict(input);
    const logits = Array.from(predictOut.dataSync());
    const winner = data.IRIS_CLASSES[predictOut.argMax(-1).dataSync()[0]];
    ui.setManualInputWinnerMessage(winner);
    ui.renderLogitsForManualInput(logits);
  });
}
github machinelearnjs / machinelearnjs / src / lib / linear_model / linear_regression.ts View on Github external
private calculateMultiVariateCoeff(X, y): number[] {
    const [q, r] = tf.linalg.qr(tf.tensor2d(X));
    const rawR = reshape(Array.from(r.dataSync()), r.shape);
    const validatedR = validateMatrix2D(rawR);
    const weights = tf
      .tensor(numeric.inv(validatedR))
      .dot(q.transpose())
      .dot(tf.tensor(y))
      .dataSync();
    return Array.from(weights);
  }
}
github tensorflow / tfjs-examples / mnist / data.js View on Github external
getTrainData() {
    const xs = tf.tensor4d(
        this.trainImages,
        [this.trainImages.length / IMAGE_SIZE, IMAGE_H, IMAGE_W, 1]);
    const labels = tf.tensor2d(
        this.trainLabels, [this.trainLabels.length / NUM_CLASSES, NUM_CLASSES]);
    return {xs, labels};
  }
github tensorflow / tfjs-examples / polynomial-regression / index.js View on Github external
xPowerStddevs.push(xPowerStddev);
    const normalizedXPower = normalizeVector(xPower, xPowerMean, xPowerStddev);
    normalizedXPowers.push(normalizedXPower);
  }
  const xArrayData = [];
  for (let i = 0; i < xData.length; ++i) {
    for (let j = 0; j < order + 1; ++j) {
      if (j === 0) {
        xArrayData.push(1);
      } else {
        xArrayData.push(normalizedXPowers[j - 1][i]);
      }
    }
  }
  return [
    xPowerMeans, xPowerStddevs, tf.tensor2d(xArrayData, [batchSize, order + 1]),
    yMean, yStddev, tf.tensor2d(yNormalized, [batchSize, 1])
  ];
}
github machinelearnjs / machinelearnjs / src / lib / naive_bayes / gaussian.ts View on Github external
const momentStack = classCategories.map((category: T) => {
      const classFeatures: tf.Tensor = tf.tensor2d(
        separatedByCategory[category.toString()] as number[][],
        null,
        'float32',
      ) as tf.Tensor;
      return tf.moments(classFeatures, [0]);
    });