试了一下 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],]
这差了太多了。这是完全不懂,刚开始学习,照例子写了一下,慢慢学习看看哪里有问题