将结果转换为变量 [英] Getting the result into a variable

查看:101
本文介绍了将结果转换为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例代码。我可以通过打印功能在控制台中看到正确的结果。

I have the following example code. I'm able to see the correct result in the console from the print function.

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

  model.add(tf.layers.dense({units: 1, inputShape: [1]}));  

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

  // Generate some synthetic data for training.
  const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
  const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

  // Train the model using the data.
  model.fit(xs, ys).then(() => {
    // Use the model to do inference on a data point the model hasn't seen before:
    // Open the browser devtools to see the output
    answer = model.predict(tf.tensor2d([3], [1, 1]));
    answer.print()

  });

我希望能够做的是将答案放入数字var中以便我可以在别处使用它。我得到的答案是:

What I'd like to be able to do is to put answer into a number var so that I can use it elsewhere. The answer I get is:

Tensor [[4.9999123],]

但是我想把4.9999变成一个变量,这样我就可以把它四舍五入并在屏幕上打印(用html格式)。

But I'd like to get the 4.9999 into a variable so that I can round it up to 5 and print it on screen (in html).

推荐答案

我发现答案是:

    answer.data().then((d)=>{
      console.log(d[0])
    })

answer有一个返回promise的数据方法。您可以从承诺中获取数据。

answer has a data method which returns a promise. You can get the data from the promise.

我搜索了stackoverflow,这引出了我这个问题:
从张量流量js获取2D张量数据

I searched stackoverflow which lead me to this question: Get data from 2D tensor with tensorflow js

Rocksetta亲切地发布了一个链接他们在以下网站上的代码:

Rocksetta kindly posted a link to their code on the following site:

https://hpssjellis.github.io/beginner-tensorflowjs-examples-in-javascript/beginner-examples/tfjs02-basics.html

这篇关于将结果转换为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆