Open In App

Tensorflow.js tf.layers addLoss() Method

Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.

The .addLoss() function is used to attach losses to the stated layer. Moreover, the loss might be probably conditional on a few input tensors, for example operation losses are dependent on the inputs of the stated layers.



Syntax:

addLoss(losses)

Parameters:



Return Value: It returns void.

Example 1:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating a model
const model = tf.sequential();
  
// Adding a layer
model.add(tf.layers.dense({units: 1, inputShape: [3]}));
  
// Defining input
const input = tf.tensor1d([1, 2, 3, 4]);
  
// Calling addLoss() method with its 
// parameter
const res = model.layers[0].addLoss([tf.abs(input)]);
  
// Printing output
console.log(JSON.stringify(input));
model.layers[0].getWeights()[0].print();

Output:

{"kept":false,"isDisposedInternal":false,"shape":[4],"dtype":"float32",
"size":4,"strides":[],"dataId":{"id":82},"id":124,"rankType":"1","scopeId":61}
Tensor
    [[0.143441  ],
     [-0.58002  ],
     [-0.5836995]]

Example 2:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating a model
const model = tf.sequential();
  
// Adding layers
model.add(tf.layers.dense({units: 1, inputShape: [3]}));
model.add(tf.layers.dense({units: 4}));
model.add(tf.layers.dense({units: 9, inputShape: [11]}));
  
// Defining inputs
const input1 = tf.tensor1d([0.5, 0.2, -33, null]);
const input2 = tf.tensor1d([0.33, 0.5, -1]);
const input3 = tf.tensor1d([1, 0.44]);
  
// Calling addLoss() method with its 
// parameter
const res1 = model.layers[0].addLoss([tf.cos(input1)]);
const res2 = model.layers[0].addLoss([tf.sin(input2)]);
const res3 = model.layers[0].addLoss([tf.tan(input3)]);
  
// Printing outputs
console.log(JSON.stringify(input1));
console.log(JSON.stringify(input2));
console.log(JSON.stringify(input3));
model.layers[0].getWeights()[0].print();

Output:

 {"kept":false,"isDisposedInternal":false,"shape":[4],"dtype":"float32",
 "size":4,"strides":[],"dataId":{"id":169},"id":261,"rankType":"1","scopeId":112}
{"kept":false,"isDisposedInternal":false,"shape":[3],"dtype":"float32",
"size":3,"strides":[],"dataId":{"id":170},"id":262,"rankType":"1","scopeId":112}
{"kept":false,"isDisposedInternal":false,"shape":[2],"dtype":"float32",
"size":2,"strides":[],"dataId":{"id":171},"id":263,"rankType":"1","scopeId":112}
Tensor
    [[-0.0062826],
     [0.0883235 ],
     [-1.0633234]]

Reference: https://js.tensorflow.org/api/latest/#tf.layers.Layer.addLoss


Article Tags :