JS Tensorflow 首次尝试

试了一下 tensorflow 的 js版本,就使用的官网的示例代码,感觉结果差很多啊。

目标是 Y = 2*X -1;但结果感觉相差十万八千里。

代码:

<!DOCTYPE html>
<html>
<head>
    <title>JS Tensorflow</title>
    <!-- <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script> -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"></script>
    <!-- <script src="https://cdn.bootcss.com/tensorflow/0.11.2/tf.min.js"></script> -->
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
    // Define a model for linear regression.
const model = tf.sequential();
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.
// y = 2*X-1
var x = [], y=[], len = 20;
for (var i = 0; i < len; i++) {
    let v = Math.floor(Math.random()*100)-50;
    x.push(v);
    y.push((v<<1)-1);
}
// console.log(x);
// console.log(y);
const xs = tf.tensor2d(x, [len, 1]);
// xs.print();
const ys = tf.tensor2d(y, [len, 1]);
// ys.print();

// 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
  model.predict(tf.tensor2d([10], [1, 1])).print();
  // document.getElementById('output').innerHTML = model.predict( tf.tensor2d([10], [1, 1]) );
});
      
</script>
</html>

结果:

 Tensor
     [[281.0496216],]

这差了太多了。这是完全不懂,刚开始学习,照例子写了一下,慢慢学习看看哪里有问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值