Tensorflow.js tf.losses.meanSquaredError() Function

31 May, 2021
Tensorflow.js is an open-source JavaScript library developed by Google for running and training machine learning models and deep learning neural networks in browser and node.js environment.
Mean squared error is the average of squared differences between the predicted and the actual values. The result is always positive and 0.0 in case but never becomes negative. In tensorflow.js library, we use tf.losses.meanSquaredError() function to compute the mean squared error between two tensors. 
Syntax: 
tf.losses.meanSquaredError(labels, predictions, weights?, reduction?)
Parameters:
labels: This is the real output tensor with respect to which the difference in prediction is calculated. It can be tf.tensor, typedArray or a normal array.
predictions: This is the predicted output tensor with the same dimensions as labels. It is either tf.tensor or typedArray or normal array.
weights: This can be a tensor of rank either equal to that of labels so that it can be broadcastable or 0. It is optional.
reduction: Applying reduction to the loss. It is optional.
Return Value: tf.Tensor which is calculated by meansquaredError function.
Example 1: In this example we will take two 2 dimensional tensors on as label and the other as prediction and then find the mean squared error of these two.
Javascript
// Importing the tensorflow.js libraryconst tf = require("@tensorflow/tfjs");  // Defining label tensorconst y_true = tf.tensor2d([    [0., 1., 0.],     [0., 0., 0.]]);  // Defining prediction tensorconst y_pred = tf.tensor2d([    [1., 1., 0.],     [1., 0., 0 ]]);  // Calculating mean squared errorconst mse = tf.losses.meanSquaredError(y_true,y_pred)  // Printing the outputmse.print()
Output:
Tensor
    0.3333
  Example 2: Similarly, we take another example in which we take the weights of rank as of labels in the meanSquaredError function and then calculate the mean squared error.
Javascript
// Importing the tensorflow.js libraryconst tf = require("@tensorflow/tfjs");  // Defining label tensorconst y_true = tf.tensor2d(    [0., 1., 0., 0., 0., 0., 1.,     0., 1., 1., 0., 1.], [4, 3]);  // Defining predicted tensorconst y_pred = tf.tensor2d(    [1., 1., 0., 1., 0., 0., 1.,     1., 1., 0., 0., 1.], [4, 3]);  // Calculating meansquared errorconst mse = tf.losses.meanSquaredError(        y_true, y_pred, [0.7, 0.3, 0.2],)  mse.print()
Output:
Tensor
    0.2000
Example 3: In compile function of designing the model, we use ‘mean squared error’ as the loss parameter. Following is a simple neural network where we do the computation.
Javascript
// Importing the tensorflow.js libraryconst tf = require("@tensorflow/tfjs");  // Define the modelconst model = tf.sequential({    layers: [tf.layers.dense({         units: 1, inputShape: [12]     })],});  // In model compilation we pass// meanSquaredError as the parameter  model.compile(    { optimizer: "adam", loss: "meanSquaredError" },    (metrics = ["accuracy"]));  // Evaluate the model which was compiled above// computation is done in batches of size 4const result = model.evaluate(    tf.ones([10, 12]), tf.ones([10, 1]), {        batchSize: 4,    });  // Print the resultresult.print();
Output:
Tensor
    0.4817
 Reference: https://js.tensorflow.org/api/3.6.0/#metrics.meanSquaredError
Picked
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.