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:
- losses: It is the stated losses. It can be of type RegularizerFn or RegularizerFn[].
Return Value: It returns void.
Example 1:
Javascript
import * as tf from "@tensorflow/tfjs"
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [3]}));
const input = tf.tensor1d([1, 2, 3, 4]);
const res = model.layers[0].addLoss([tf.abs(input)]);
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:
Javascript
import * as tf from "@tensorflow/tfjs"
const model = tf.sequential();
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]}));
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]);
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)]);
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
Last Updated :
22 Apr, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...