• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript deeplearn.tensor1d函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中deeplearn.tensor1d函数的典型用法代码示例。如果您正苦于以下问题:TypeScript tensor1d函数的具体用法?TypeScript tensor1d怎么用?TypeScript tensor1d使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了tensor1d函数的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: infer

    dl.tidy(async () => {
      console.log(`Evaluation set: n=${data.images.length}.`);

      let numCorrect = 0;
      for (let i = 0; i < data.images.length; i++) {
        const x = dl.tensor1d(data.images[i]);

        // Infer through the model to get a prediction.
        const predictedLabel = Math.round(await infer(x, vars).val());
        console.log(`Item ${i}, predicted label ${predictedLabel}.`);

        // Aggregate correctness to show accuracy.
        const label = data.labels[i];
        if (label === predictedLabel) {
          numCorrect++;
        }

        // Show the image.
        const result =
            renderResults(dl.tensor1d(data.images[i]), label, predictedLabel);
        document.body.appendChild(result);
      }

      // Compute final accuracy.
      const accuracy = numCorrect * 100 / data.images.length;
      document.getElementById('accuracy').innerHTML = `${accuracy}%`;
    });
开发者ID:ScapeQin,项目名称:deeplearnjs,代码行数:27,代码来源:mnist.ts


示例2:

 return dl.tidy(() => {
   if (!conditioned) {
     // TODO(nsthorat): figure out why we have to cast these shapes to numbers.
     // The linter is complaining, though VSCode can infer the types.
     const size = 1 + (noteDensityEncoding.shape[0] as number) +
         (pitchHistogramEncoding.shape[0] as number);
     const conditioning: dl.Tensor1D =
         dl.oneHot(dl.tensor1d([0]), size).as1D();
     return conditioning;
   } else {
     const axis = 0;
     const conditioningValues =
         noteDensityEncoding.concat(pitchHistogramEncoding, axis);
     return dl.tensor1d([0]).concat(conditioningValues, axis);
   }
 });
开发者ID:ScapeQin,项目名称:deeplearnjs,代码行数:16,代码来源:performance_rnn.ts


示例3:

  await dl.tidy(async () => {
    const forgetBias = dl.scalar(1.0);
    const lstm1 = (data: dl.Tensor2D, c: dl.Tensor2D, h: dl.Tensor2D) =>
        dl.basicLSTMCell(forgetBias, lstmKernel1, lstmBias1, data, c, h);
    const lstm2 = (data: dl.Tensor2D, c: dl.Tensor2D, h: dl.Tensor2D) =>
        dl.basicLSTMCell(forgetBias, lstmKernel2, lstmBias2, data, c, h);

    let c: dl.Tensor2D[] = [
      dl.zeros([1, lstmBias1.shape[0] / 4]),
      dl.zeros([1, lstmBias2.shape[0] / 4])
    ];
    let h: dl.Tensor2D[] = [
      dl.zeros([1, lstmBias1.shape[0] / 4]),
      dl.zeros([1, lstmBias2.shape[0] / 4])
    ];

    let input = primerData;
    for (let i = 0; i < expected.length; i++) {
      const onehot = dl.oneHot(dl.tensor1d([input]), 10);

      const output = dl.multiRNNCell([lstm1, lstm2], onehot, c, h);

      c = output[0];
      h = output[1];

      const outputH = h[1];
      const logits =
          outputH.matMul(fullyConnectedWeights).add(fullyConnectedBiases);

      const result = await dl.argMax(logits).val();
      results.push(result);
      input = result;
    }
  });
开发者ID:ScapeQin,项目名称:deeplearnjs,代码行数:34,代码来源:lstm.ts


示例4: run

  async run(size: number) {
    dl.setBackend('webgl');

    const x: dl.Tensor3D = dl.randomUniform([size, size, 8], -1, 1);
    const mean = dl.tensor1d([0]);
    const variance = dl.tensor1d([1]);
    const varianceEpsilon = .001;

    const benchmark = () =>
        x.batchNormalization(mean, variance, varianceEpsilon);

    const time = await benchmark_util.warmupAndBenchmarkGPU(benchmark);

    x.dispose();
    mean.dispose();
    variance.dispose();

    return time;
  }
开发者ID:kodamatomohiro,项目名称:tfjs-core,代码行数:19,代码来源:batchnormalization3d_benchmark.ts


示例5: run

  async run(size: number) {
    const safeMode = false;
    const math = new dl.NDArrayMath('webgl', safeMode);
    dl.ENV.setMath(math);

    const x: dl.Tensor3D = dl.randomUniform([size, size, 8], -1, 1);
    const mean = dl.tensor1d([0]);
    const variance = dl.tensor1d([1]);
    const varianceEpsilon = .001;

    const benchmark = () =>
        x.batchNormalization(mean, variance, varianceEpsilon);

    const time = await benchmark_util.warmupAndBenchmarkGPU(benchmark);

    x.dispose();
    mean.dispose();
    variance.dispose();
    math.dispose();

    return time;
  }
开发者ID:ScapeQin,项目名称:deeplearnjs,代码行数:22,代码来源:batchnormalization3d_benchmark.ts


示例6: updateConditioningParams

function updateConditioningParams() {
  const pitchHistogram = pitchHistogramElements.map(e => {
    return parseInt(e.value, 10) || 0;
  });
  updateDisplayHistogram(pitchHistogram);

  if (noteDensityEncoding != null) {
    noteDensityEncoding.dispose();
    noteDensityEncoding = null;
  }

  window.location.assign(
      '#' + densityControl.value + '|' + pitchHistogram.join(',') + '|' +
      preset1.join(',') + '|' + preset2.join(',') + '|' +
      (conditioned ? 'true' : 'false'));

  const noteDensityIdx = parseInt(densityControl.value, 10) || 0;
  const noteDensity = DENSITY_BIN_RANGES[noteDensityIdx];
  densityDisplay.innerHTML = noteDensity.toString();
  noteDensityEncoding =
      dl.oneHot(
            dl.tensor1d([noteDensityIdx + 1]), DENSITY_BIN_RANGES.length + 1)
          .as1D();

  if (pitchHistogramEncoding != null) {
    pitchHistogramEncoding.dispose();
    pitchHistogramEncoding = null;
  }
  const buffer = dl.buffer<dl.Rank.R1>([PITCH_HISTOGRAM_SIZE], 'float32');
  const pitchHistogramTotal = pitchHistogram.reduce((prev, val) => {
    return prev + val;
  });
  for (let i = 0; i < PITCH_HISTOGRAM_SIZE; i++) {
    buffer.set(pitchHistogram[i] / pitchHistogramTotal, i);
  }
  pitchHistogramEncoding = buffer.toTensor();
}
开发者ID:ScapeQin,项目名称:deeplearnjs,代码行数:37,代码来源:performance_rnn.ts


示例7: intro

// This file parallels (some of) the code in the introduction tutorial.

/**
 * 'Math with WebGL backend' section of tutorial
 */
async function intro() {
  const a = dl.tensor2d([1.0, 2.0, 3.0, 4.0], [2, 2]);
  const b = dl.tensor2d([0.0, 2.0, 4.0, 6.0], [2, 2]);

  const size = dl.scalar(a.size);

  // Non-blocking math calls.
  const average = a.sub(b).square().sum().div(size);

  console.log(`mean squared difference: ${await average.val()}`);

  /**
   * 'Graphs and Tensors' section of tutorial
   */

  const g = new dl.Graph();

  // Placeholders are input containers. This is the container for where we
  // will feed an input Tensor when we execute the graph.
  const inputShape = [3];
  const inputTensor = g.placeholder('input', inputShape);

  const labelShape = [1];
  const labelTensor = g.placeholder('label', labelShape);

  // Variables are containers that hold a value that can be updated from
  // training.
  // Here we initialize the multiplier variable randomly.
  const multiplier = g.variable('multiplier', dl.randomNormal([1, 3]));

  // Top level graph methods take Tensors and return Tensors.
  const outputTensor = g.matmul(multiplier, inputTensor);
  const costTensor = g.meanSquaredCost(labelTensor, outputTensor);

  // Tensors, like Tensors, have a shape attribute.
  console.log(outputTensor.shape);

  /**
   * 'dl.Session and dl.FeedEntry' section of the tutorial.
   */

  const learningRate = .00001;
  const batchSize = 3;

  const session = new dl.Session(g, dl.ENV.math);
  const optimizer = dl.train.sgd(learningRate);

  const inputs: dl.Tensor1D[] = [
    dl.tensor1d([1.0, 2.0, 3.0]), dl.tensor1d([10.0, 20.0, 30.0]),
    dl.tensor1d([100.0, 200.0, 300.0])
  ];

  const labels: dl.Tensor1D[] =
      [dl.tensor1d([4.0]), dl.tensor1d([40.0]), dl.tensor1d([400.0])];

  // Shuffles inputs and labels and keeps them mutually in sync.
  const shuffledInputProviderBuilder =
      new dl.InCPUMemoryShuffledInputProviderBuilder([inputs, labels]);
  const [inputProvider, labelProvider] =
      shuffledInputProviderBuilder.getInputProviders();

  // Maps tensors to InputProviders.
  const feedEntries: dl.FeedEntry[] = [
    {tensor: inputTensor, data: inputProvider},
    {tensor: labelTensor, data: labelProvider}
  ];

  const NUM_BATCHES = 10;
  for (let i = 0; i < NUM_BATCHES; i++) {
    // Wrap session.train in a scope so the cost gets cleaned up
    // automatically.
    await dl.tidy(async () => {
      // Train takes a cost tensor to minimize. Trains one batch. Returns the
      // average cost as a dl.Scalar.
      const cost = session.train(
          costTensor, feedEntries, batchSize, optimizer, dl.CostReduction.MEAN);

      console.log(`last average cost (${i}): ${await cost.val()}`);
    });
  }

  const testInput = dl.tensor1d([0.1, 0.2, 0.3]);

  // session.eval can take Tensors as input data.
  const testFeedEntries: dl.FeedEntry[] =
      [{tensor: inputTensor, data: testInput}];

  const testOutput = session.eval(outputTensor, testFeedEntries);

  console.log('---inference output---');
  console.log(`shape: ${testOutput.shape}`);
  console.log(`value: ${await testOutput.val(0)}`);
}
开发者ID:ScapeQin,项目名称:deeplearnjs,代码行数:98,代码来源:intro.ts


示例8: async

export const learnXOR = async () => {
  const iterations = getRandomIntegerInRange(800, 1000);
  const timeStart: number = performance.now();
  let loss: number;
  let cost: dl.Scalar;

  const graph = new dl.Graph();

  const input = graph.placeholder('input', [2]);
  const y = graph.placeholder('y', [1]);

  const hiddenLayer = graph.layers.dense(
      'hiddenLayer', input, 10, (x: dl.SymbolicTensor) => graph.relu(x), true);
  const output = graph.layers.dense(
      'outputLayer', hiddenLayer, 1, (x: dl.SymbolicTensor) => graph.sigmoid(x),
      true);

  const costTensor = graph.reduceSum(graph.add(
      graph.multiply(
          graph.constant([-1]),
          graph.multiply(
              y, graph.log(graph.add(output, graph.constant([EPSILON]))))),
      graph.multiply(
          graph.constant([-1]),
          graph.multiply(
              graph.subtract(graph.constant([1]), y),
              graph.log(graph.add(
                  graph.subtract(graph.constant([1]), output),
                  graph.constant([EPSILON])))))));

  const session = new dl.Session(graph, dl.ENV.math);
  const optimizer = new dl.SGDOptimizer(0.2);

  const inputArray = [
    dl.tensor1d([0, 0]), dl.tensor1d([0, 1]), dl.tensor1d([1, 0]),
    dl.tensor1d([1, 1])
  ];

  const targetArray =
      [dl.tensor1d([0]), dl.tensor1d([1]), dl.tensor1d([1]), dl.tensor1d([0])];

  const shuffledInputProviderBuilder =
      new dl.InCPUMemoryShuffledInputProviderBuilder([inputArray, targetArray]);

  const [inputProvider, targetProvider] =
      shuffledInputProviderBuilder.getInputProviders();

  const feedEntries =
      [{tensor: input, data: inputProvider}, {tensor: y, data: targetProvider}];

  /**
   * Train the model
   */
  await dl.tidy(async () => {
    for (let i = 0; i < iterations; i += 1) {
      cost = session.train(
          costTensor, feedEntries, 4, optimizer, dl.CostReduction.MEAN);
    }
    loss = await cost.val();
  });

  const result = [];

  /**
   * Test the model
   */
  for (let i = 0; i < 4; i += 1) {
    const inputData = inputArray[i];
    const expectedOutput = targetArray[i];

    const val = session.eval(output, [{tensor: input, data: inputData}]);

    result.push({
      input: await inputData.data(),
      expected: await expectedOutput.data(),
      output: await val.data()
    });
  }

  const timeEnd: number = performance.now();
  const time = timeEnd - timeStart;

  return {iterations, loss, time, result};
};
开发者ID:ScapeQin,项目名称:deeplearnjs,代码行数:84,代码来源:learn-xor.ts



注:本文中的deeplearn.tensor1d函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript deeplearn.tidy函数代码示例发布时间:2022-05-25
下一篇:
TypeScript deeplearn.setBackend函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap