Evaluation Metrics in TensorFlow
Last Updated :
23 Jul, 2025
Evaluation metrics accesses the performance of machine learning models.
In TensorFlow, these metrics help quantify how well the model is performing during training and after it has been trained. TensorFlow provides a wide variety of built-in metrics for both classification and regression tasks, allowing you to choose the most appropriate one for your specific problem.
1. Accuracy
Accuracy is one of the most widely used evaluation metrics, particularly in classification problems. It measures the percentage of correct predictions out of all predictions made. It’s suitable for balanced datasets but may not be the best choice for imbalanced datasets, as it can give misleading results.
Function: tf.keras.metrics.Accuracy()
TensorFlow Code:
Python
import tensorflow as tf
# Example model
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(32,)),
tf.keras.layers.Dense(10, activation='softmax')
])
# Compile model with Accuracy metric
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=[tf.keras.metrics.Accuracy()])
# Train the model
model.fit(x_train, y_train)
2. Precision
Precision is a metric used in classification tasks that measures how many of the predicted positive labels were actually positive. It’s particularly useful when the cost of false positives is high.
Function: tf.keras.metrics.Precision()
Example Code in TensorFlow:
Python
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(32,)),
tf.keras.layers.Dense(1, activation='sigmoid') # For binary classification
])
# Compile model with Precision metric
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=[tf.keras.metrics.Precision()])
model.fit(x_train, y_train)
3. Recall
Recall is another important metric in classification, especially in situations where false negatives are more costly than false positives. It measures how many of the actual positive labels were correctly identified by the model.
Function: tf.keras.metrics.Recall()
Example Code in TensorFlow:
Python
import tensorflow as tf
# Example model
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(32,)),
tf.keras.layers.Dense(1, activation='sigmoid') # For binary classification
])
# Compile model with Recall metric
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=[tf.keras.metrics.Recall()])
# Train the model
model.fit(x_train, y_train)
4. F1 Score
F1 Score is the harmonic mean of precision and recall, providing a balanced evaluation metric for classification tasks. It is particularly useful when you need to balance both false positives and false negatives.
Function: TensorFlow doesn’t have a built-in F1 score metric, but you can compute it using precision and recall.
5. Mean Squared Error (MSE)
MSE is commonly used for regression tasks. It measures the average squared difference between the predicted and actual values. A lower MSE indicates better model performance.
Function: tf.keras.metrics.MeanSquaredError()
Example Code in TensorFlow:
Python
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(32,)),
tf.keras.layers.Dense(1)
])
# Compile model with Mean Squared Error metric
model.compile(optimizer='adam',
loss='mean_squared_error',
metrics=[tf.keras.metrics.MeanSquaredError()])
model.fit(x_train, y_train)
6. Mean Absolute Error (MAE)
Mean Absolute Error is another metric commonly used in regression. It measures the average absolute differences between the predicted and actual values. Unlike MSE, MAE doesn’t penalize large errors as much, making it more robust to outliers.
Function: tf.keras.metrics.MeanAbsoluteError()
Example Code in TensorFlow:
Python
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(32,)),
tf.keras.layers.Dense(1) # For regression
])
# Compile model with Mean Absolute Error metric
model.compile(optimizer='adam',
loss='mean_absolute_error',
metrics=[tf.keras.metrics.MeanAbsoluteError()])
model.fit(x_train, y_train)
7. AUC (Area Under the Curve)
AUC measures the area under the receiver operating characteristic (ROC) curve. It is a valuable metric for binary classification tasks, indicating the model’s ability to distinguish between classes. A higher AUC value indicates a better performing model.
Function: tf.keras.metrics.AUC()
8. Cosine Similarity
Cosine similarity measures the cosine of the angle between the predicted and actual vectors. It is commonly used in text-related tasks, such as document similarity, or in cases where the direction of the vector is more important than its magnitude.
Function: tf.keras.metrics.CosineSimilarity()
Example Code in TensorFlow:
Python
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(32,)),
tf.keras.layers.Dense(1, activation='sigmoid') # For binary classification
])
# Compile model with Cosine Similarity metric
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=[tf.keras.metrics.CosineSimilarity()])
model.fit(x_train, y_train)
Evaluation metrics are vital tools for assessing the performance of your machine learning models. TensorFlow provides a comprehensive suite of built-in metrics that cater to both classification and regression tasks.
By understanding and using the appropriate metrics in TensorFlow, you can better tune your models and achieve optimal performance.
Similar Reads
Deep Learning Tutorial Deep Learning is a subset of Artificial Intelligence (AI) that helps machines to learn from large datasets using multi-layered neural networks. It automatically finds patterns and makes predictions and eliminates the need for manual feature extraction. Deep Learning tutorial covers the basics to adv
5 min read
Deep Learning Basics
Introduction to Deep LearningDeep Learning is transforming the way machines understand, learn and interact with complex data. Deep learning mimics neural networks of the human brain, it enables computers to autonomously uncover patterns and make informed decisions from vast amounts of unstructured data. How Deep Learning Works?
7 min read
Artificial intelligence vs Machine Learning vs Deep LearningNowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are
4 min read
Deep Learning Examples: Practical Applications in Real LifeDeep learning is a branch of artificial intelligence (AI) that uses algorithms inspired by how the human brain works. It helps computers learn from large amounts of data and make smart decisions. Deep learning is behind many technologies we use every day like voice assistants and medical tools.This
3 min read
Challenges in Deep LearningDeep learning, a branch of artificial intelligence, uses neural networks to analyze and learn from large datasets. It powers advancements in image recognition, natural language processing, and autonomous systems. Despite its impressive capabilities, deep learning is not without its challenges. It in
7 min read
Why Deep Learning is ImportantDeep learning has emerged as one of the most transformative technologies of our time, revolutionizing numerous fields from computer vision to natural language processing. Its significance extends far beyond just improving predictive accuracy; it has reshaped entire industries and opened up new possi
5 min read
Neural Networks Basics
What is a Neural Network?Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamental
12 min read
Types of Neural NetworksNeural networks are computational models that mimic the way biological neural networks in the human brain process information. They consist of layers of neurons that transform the input data into meaningful outputs through a series of mathematical operations. In this article, we are going to explore
7 min read
Layers in Artificial Neural Networks (ANN)In Artificial Neural Networks (ANNs), data flows from the input layer to the output layer through one or more hidden layers. Each layer consists of neurons that receive input, process it, and pass the output to the next layer. The layers work together to extract features, transform data, and make pr
4 min read
Activation functions in Neural NetworksWhile building a neural network, one key decision is selecting the Activation Function for both the hidden layer and the output layer. It is a mathematical function applied to the output of a neuron. It introduces non-linearity into the model, allowing the network to learn and represent complex patt
8 min read
Feedforward Neural NetworkFeedforward Neural Network (FNN) is a type of artificial neural network in which information flows in a single direction i.e from the input layer through hidden layers to the output layer without loops or feedback. It is mainly used for pattern recognition tasks like image and speech classification.
6 min read
Backpropagation in Neural NetworkBack Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Deep Learning Models
Deep Learning Frameworks
TensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
2 min read
Keras TutorialKeras high-level neural networks APIs that provide easy and efficient design and training of deep learning models. It is built on top of powerful frameworks like TensorFlow, making it both highly flexible and accessible. Keras has a simple and user-friendly interface, making it ideal for both beginn
3 min read
PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an
7 min read
Caffe : Deep Learning FrameworkCaffe (Convolutional Architecture for Fast Feature Embedding) is an open-source deep learning framework developed by the Berkeley Vision and Learning Center (BVLC) to assist developers in creating, training, testing, and deploying deep neural networks. It provides a valuable medium for enhancing com
8 min read
Apache MXNet: The Scalable and Flexible Deep Learning FrameworkIn the ever-evolving landscape of artificial intelligence and deep learning, selecting the right framework for building and deploying models is crucial for performance, scalability, and ease of development. Apache MXNet, an open-source deep learning framework, stands out by offering flexibility, sca
6 min read
Theano in PythonTheano is a Python library that allows us to evaluate mathematical operations including multi-dimensional arrays efficiently. It is mostly used in building Deep Learning Projects. Theano works way faster on the Graphics Processing Unit (GPU) rather than on the CPU. This article will help you to unde
4 min read
Model Evaluation
Deep Learning Projects