[TensorFlowJS只如初見]實戰三·使用TensorFlowJS擬合曲線
阿新 • • 發佈:2018-12-01
[TensorFlowJS只如初見]實戰三·使用TensorFlowJS擬合曲線
-
問題描述
擬合y= x*x -2x +3 + 0.1(-1到1的隨機值) 曲線
給定x範圍(0,3) -
問題分析
在直線擬合部落格中,我們使用最簡單的y=wx+b的模型成功擬合了一條直線,現在我們在進一步進行曲線的擬合。簡單的y=wx+b模型已經無法滿足我們的需求,需要利用更多的神經元來解決問題了。 -
程式碼
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs" >
</script>
</head>
<body>
<button class="btn btn-primary" onclick="fnRun0();">開始0</button>
<div id="p0Id">out0</div>
<button class="btn btn-primary" onclick="fnRun1();">開始1</button>
<div id="p1Id">out1</div>
<button class=" btn btn-primary" onclick="fnRun2();">開始2</button>
<div id="p2Id">out2</div>
</body>
<script>
function get_ys(xs) {
var ys = new Array();
for (var i = 0; i < xs.length; i++) {
ys[i] = xs[i] * xs[i] - 2 * xs[i] + 3 + (0.001 * (2 * Math.random() - 1));
}
return (ys);
}
var xs = new Array();
for (var i = 0; i < 200; i++) {
xs[i] = 0.01 * i;
}
var ys = get_ys(xs);
const xst = tf.tensor(xs, [xs.length, 1]);
const yst = tf.tensor(ys, [ys.length, 1]);
const a = tf.variable(tf.scalar(Math.random()));
const b = tf.variable(tf.scalar(Math.random()));
const c = tf.variable(tf.scalar(Math.random()));
function predict(x) {
return tf.tidy(() => {
return a.mul(x.square())
.add(b.mul(x))
.add(c);
});
}
function loss(prediction, labels) {
const error = prediction.sub(labels).square().mean();
return error;
}
const numIterations = 1000;
const learningRate = 0.12;
const optimizer = tf.train.sgd(learningRate);
function train(xst, yst, numIterations) {
for (var iter = 0; iter < numIterations+1; iter++) {
optimizer.minimize(() => {
const predsYs = predict(xst);
if(iter%100==0){
console.log(iter+" steps loss is "+loss(predsYs, yst));
}
return loss(predsYs, yst);
});
}
const test_xs = tf.tensor([0.5,1,1.5],[3,1]);
predict(test_xs).print();
}
train(xst,yst,numIterations);
</script>
</html>
- 輸出結果
進行1000輪訓練以後,我們輸入[0.5,1,1.5]進行預測,得到結果為
[[2.2503195],
[2.0105994],
[2.2543631]]
較好地擬合了曲線。
log
"0 steps loss is Tensor
1.7456094026565552"
"100 steps loss is Tensor
0.08455191552639008"
"200 steps loss is Tensor
0.040247201919555664"
"300 steps loss is Tensor
0.0191580131649971"
"400 steps loss is Tensor
0.009119458496570587"
"500 steps loss is Tensor
0.004341088235378265"
"600 steps loss is Tensor
0.0020665652118623257"
"700 steps loss is Tensor
0.0009838765254244208"
"800 steps loss is Tensor
0.0004685141902882606"
"900 steps loss is Tensor
0.00022319876006804407"
"1000 steps loss is Tensor
0.00010642936103977263"
"Tensor
[[2.2503195],
[2.0105994],
[2.2543631]]"