· Use TensorFlowJS to fit curves (similar to TensorFlow native implementation method)
- Y = x* x-2x +3 + 0.1(random value from -1 to 1) curve given x range (0,3)
- In the straight line fitting blog, we successfully fitted a straight line using the simplest y=wx+b model, and now we are further fitting the curve. The simple y=wx+ B model can no longer meet our needs, and more neurons are needed to solve the problem.
- code
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs">
</script>
</head>
<body>
<button class="btn btn-primary" onclick="fnRun0();">Began to 0</button>
<div id="p0Id">out0</div>
<button class="btn btn-primary" onclick="fnRun1();">Began to 1</button>
<div id="p1Id">out1</div>
<button class="btn btn-primary" onclick="learnLinear();">Start 2</button>
<div id="p2Id">out2</div>
</body>
<script>
//document.getElementById("p0Id").innerHTML = 0;
function get_ys(xs) {
var ys = new Array(a);for (var i = 0; i < xs.length; i++) {
ys[i] = xs[i] * xs[i] - 2 * xs[i] + 3 + (0.1 * (2 * Math.random() - 1));
}
return (ys);
}
var xs = new Array(a);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]);
function get_weights(shape) {
return (tf.variable(tf.randomNormal(shape)));
}
function get_bais(shape) {
return (tf.variable(tf.fill(shape, 0.1)));
}
const w1 = get_weights([1.10]);
const w2 = get_weights([10.1]);
const b1 = get_bais([1.10]);
const b2 = get_bais([1.1]);
function predict(x) {
return tf.tidy(() = > {
const l1 = tf.elu(tf.add(tf.matMul(x, w1), b1)); Operator overload tf.add() cannot be written as +
const y = tf.add(tf.matMul(l1, w2), b2);
return y;
});
}
function loss(predictions, labels) {
// Abstracts labels (the actual values)
// Then get the average.
return tf.tidy(() = > {
const meanSquareError = tf.mean(tf.square(tf.sub(predictions, labels)));
return meanSquareError;
});
}
const learningRate = 1;
const optimizer = tf.train.adagrad(learningRate);
const numIterations = 1001;
function training() {
for (var iter = 0; iter < numIterations; iter++) {
optimizer.minimize(() = > {
const loss_var = loss(predict(xst), yst);
if(iter % 100= =0)
loss_var.print();
return loss_var;
})
}
}
training();
const text_xs = tf.tensor([0.1.3], [3.1]);
predict(text_xs).print();
</script>
</html>
Copy the code
- Output results after 1000 rounds of training, we input [0,1,3] for prediction, and the obtained results are [[2.9647527], [1.9793538], [3.9484348]], which fit the curve well.
log
"Tensor 4.915620803833008" Tensor 0.018092654645442963" Tensor 0.01064694207161665" Tensor 0.008950537070631981 "Tensor 0.008051211014389992" "Tensor 0.007439687382429838" "Tensor 0.006973605137318373" "Tensor 0.006602670066058636" "Tensor 0.006299363449215889" "Tensor 0.0060538649559021" "Tensor 0.005853266455233097" "Tensor [[2.9647527], [1.9793538], [3.9484348]]. ""Copy the code