Share Brilliantly
tensor flow
let f = function(x){
return x.add(tf.scalar(2)).pow(tf.scalar(2, 'int32'))
}
function minimize(epochs){
//x is a variable with initial value of 2
let x = tf.variable(tf.scalar(2));
let learningRate = 0.1;
const optim = tf.train.adam(learningRate); //gadient descent algorithm
for(let i = 0 ; i < epochs ; i++) {
optim.minimize(() => f(x));
}
return x;
}
//load tensor flow library
await $src('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest');
// f is the function (x+2)^2
//the minimum should be x=-2
let f = function(x){
return x.add(tf.scalar(2)).pow(tf.scalar(2, 'int32'))
}
function minimize(epochs){
//x is a variable with initial value of 2
let x = tf.variable(tf.scalar(2));
let learningRate = 0.1;
const optim = tf.train.adam(learningRate); //gadient descent algorithm
for(let i = 0 ; i < epochs ; i++) {
optim.minimize(() => f(x));
}
return x;
}
let result = minimize(100);
Try it!