w3resource

Defining a mean squared error (MSE) loss function in TensorFlow

Python TensorFlow Building and Training a Simple Model: Exercise-6 with Solution

Write a Python program that defines a mean squared error (MSE) loss function using TensorFlow for a regression task.

From Wikipedia -
In statistics, the mean squared error (MSE) or mean squared deviation (MSD) of an estimator (a procedure for estimating an unobserved quantity) measures the average of the squares of the errors-that is, the average squared difference between the estimated values and the actual value. MSE is a risk function, corresponding to the expected value of the squared error loss.

Sample Solution:

Python Code:

import tensorflow as tf

# Simulated ground truth and predicted values (for demonstration)
y_true = tf.constant([3.0, 4.0, 5.0, 6.0], dtype=tf.float32)
y_pred = tf.constant([2.5, 3.8, 4.2, 5.5], dtype=tf.float32)

# Calculate the mean squared error
mse = tf.reduce_mean(tf.square(y_true - y_pred))

# Print the MSE value
print("Mean Squared Error (MSE):", mse.numpy())

Output:

Mean Squared Error (MSE): 0.29500008

Explanation:

Import the necessary modules.

  • Create two tensors "y_true" and "y_pred" to represent ground truth values and predicted values, respectively. These tensors are provided for demonstration purposes. In practice, you would replace these tensors with your actual data.
  • Calculate the mean squared error (MSE) using TensorFlow operations. The MSE is computed as the average of the squared differences between ground truth and predicted values. The tf.square function squares the differences, and tf.reduce_mean calculates the mean of these squared differences.
  • Finally, we print the computed MSE value using mse.numpy(). The .numpy() method extracts the numerical value from the TensorFlow tensor.

Python Code Editor:


Previous: Creating a TensorFlow placeholder for 3D Images.
Next: Implementing a categorical cross-entropy loss function in TensorFlow.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/machine-learning/tensorflow/python-tensorflow-building-and-training-exercise-6.php