Search code examples
javascripttensorflowtensorflow.jsnonlinear-optimization

Is there a way to get the value from a tensorflow.js variable without .dataSync()?


the title is a bit self-explanatory. I need to get the value of a variable before each iteration of the optimisation process of fitting a function to experimental data. The variables are c0 and k, which are just scalars. Using .dataSync() I get an error as follows:

Can not find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().

The code is as follows:

const c0_tensor = tf.scalar(c0).variable(), k_tensor = tf.scalar(k).variable();
// y = c0*e^(k*x)
const fun = (t) => t.mul(k_tensor).exp().mul(c0_tensor);
const cost = (pred, label) => pred.sub(label).square().mean();
const learning_rate = 0.1;
const optimizer = tf.train.adagrad(learning_rate);
// Train the model.
for (let i = 0; i < 500; i++) {
optimizer.minimize(() => cost(fun(x_tensor), y_tensor));
}; 

My question is, is there any other way to catch the value of c0 and k on each iteration into a new JS variable without using .dataSync()?


Solution

  • Please find the explanation directly in the code

    let list_k = []
    for (let i = 0; i < 500; i++) {
      // if you want to get all the values of k as the optimizations continues
      // push k in the array
      // however, the values downloaded from the backend could also be pushed
      // ie list_k.push(...k.dataSync())
      list_k.push(k)
      // do likewise for the other parameters
      optimizer.minimize(() => cost(fun(x), y));
    }
    
    // after the optimizations the k(s) values can be accessed here
    // for example print them
    tf.stack(list_k).print()