[TensorFlowJS只如初見]實戰二·使用TensorFlowJS擬合直線
阿新 • • 發佈:2018-12-01
[TensorFlowJS只如初見]實戰二·使用TensorFlowJS擬合直線
- 問題描述
擬合直線 y =(2x -1) + 0.1(-1到1的隨機值)
給定x範圍(0,3)
可以使用學習框架
建議使用
y = w * x + b 網路模型 - 程式碼
1、通過操作(ops)來直接完成模型
<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>
//train(xst, yst, numIterations);
function get_ys(xs) {
var ys = new Array();
for (var i = 0; i < xs.length; i++) {
ys[i] = 2 * xs[i] - 1 + (0.1 * (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 w1 = tf.variable(tf.scalar(Math.random()));
const b1 = tf.variable(tf.scalar(Math.random()));
const f = x => w1.mul(x).add(b1);
const numIterations = 200;
const learningRate = 1;
const optimizer = tf.train.adam(learningRate);
const loss = (pred, label) => pred.sub(label).square().mean();
for (let iter = 0; iter < numIterations; iter++) {
optimizer.minimize(() => {
const loss_var = loss(f(xst), yst);
loss_var.print();
return loss_var;
})
}
</script>
</html>
2、通過高階API tf.model
<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] = 2 * xs[i] - 1 + (0.1 * (2 * Math.random() - 1));
}
return (ys);
}
async function learnLinear() {
var xs = new Array();
for (var i = 0; i < 100; i++) {
xs[i] = 0.02 * i;
}
var ys = get_ys(xs);
const xst = tf.tensor(xs, [xs.length, 1]);
const yst = tf.tensor(ys, [ys.length, 1]);
const model = tf.sequential();
model.add(tf.layers.dense({
units: 1,
inputShape: [1]
}));
model.compile({
loss: 'meanSquaredError',
optimizer: 'sgd'
});
await model.fit(xst, yst, {
epochs: 100
});
model.predict(tf.tensor2d([1.1,1.2,1.3,1.4,1.5], [5, 1])).print();
}
learnLinear();
</script>
</html>
- 結果
當輸入x為:[1.1,1.2,1.3,1.4,1.5],輸出為
[[1.2097658],
[1.3917543],
[1.5737425],
[1.755731 ],
[1.9377195]]
可見系統較好的擬合了直線 y =(2x -1)
"Tensor
[[1.2097658],
[1.3917543],
[1.5737425],
[1.755731 ],
[1.9377195]]"