The Wayback Machine - https://web.archive.org/web/20240920042131/https://www.geeksforgeeks.org/how-to-measure-the-binary-cross-entropy-between-the-target-and-the-input-probabilities-in-pytorch/
Open In App

How to Measure the Binary Cross Entropy Between the Target and the Input Probabilities in PyTorch?

Last Updated : 02 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to see how to Measure the Binary Cross Entropy between the target and the input probabilities in PyTorch using Python. We can measure this by using the BCELoss() method of torch.nn module.

BCELoss() method

The BCELoss() method measures the Binary Cross Entropy between the target and the input probabilities by creating a criterion. This method is used for measuring the error of reconstruction, an auto-encoder is a good example of it. The input and target must be tensors of any number of dimensions and the target should be between 0 to 1. before moving further let’s see the syntax of the given method.

Syntax: torch.nn.BCELoss()

Example 1:

In this example, we measure the Binary Cross Entropy between the target and the input probabilities of the 1D tensor.

Python




# Import required library
import torch
import torch.nn as nn
  
# define input and target tensor
input_tens = torch.tensor(
    [0.4498, 0.9845, 0.4576, 0.3494, 0.2434],
    requires_grad=True)
target_tens = torch.tensor([0.2345, 0.5565,
                            0.3468, 0.1444,
                            0.3546])
  
# display input and target tensor
print('\n input tensor: ', input_tens)
print('\n target tensor: ', target_tens)
  
# define criterion to measure binary 
# cross entropy
bce_loss = nn.BCELoss()
  
# compute the binary cross entropy
output = bce_loss(input_tens, target_tens)
output.backward()
  
# display result
print('\n Binary Cross Entropy Loss: ', output)


Output:

 

Example 2:

In this example, we measure the Binary Cross Entropy between the target and the input probabilities of the 2D tensor.

Python




# Import required library
import torch
import torch.nn as nn
  
# define input and target tensor
input_tens = torch.tensor([[0.4576, 0.6496, 0.6783],
                           [0.4895, 0.9454, 0.5443],
                           [0.9491, 0.3825, 0.7235]],
                          requires_grad=True)
  
target_tens = torch.tensor([[0.2432, 0.1579, 0.0325],
                            [0.3464, 0.2442, 0.3847],
                            [0.4528, 0.0876, 0.0499], ])
  
# display input and target tensor
print('\n input tensor: \n', input_tens)
print('\n target tensor: \n', target_tens)
  
# define criterion to measure binary cross entropy
bce_loss = nn.BCELoss()
  
# compute the binary cross entropy
output = bce_loss(input_tens, target_tens)
output.backward()
  
# display result
print('\n Binary Cross Entropy Loss: \n', output)


Output:

 



Similar Reads

How to Implement Softmax and Cross-Entropy in Python and PyTorch
Multiclass classification is an application of deep learning/machine learning where the model is given input and renders a categorical output corresponding to one of the labels that form the output. For example, providing a set of images of animals and classifying it among cats, dogs, horses, etc. For this purpose, where the model outputs multiple
7 min read
How to compute element-wise entropy of an input tensor in PyTorch
In this article, we are going to discuss how to compute the element-wise entropy of an input tensor in PyTorch, we can compute this by using torch.special.entr() method. torch.special.entr() method torch.special.entr() method computes the element-wise entropy, This method accepts a tensor as input and returns a tensor with the element-wise entropy
2 min read
Sigmoid Cross Entropy function of TensorFlow
TensorFlow is an open-source Machine Learning framework used to develop models. While developing models we use many functions to check the model's accuracy and loss. For a model to be in good condition, loss calculation is a must since loss acts like a penalty. The lower the loss better will be the working of the model. There are many kinds of loss
3 min read
How to measure the mean absolute error (MAE) in PyTorch?
In this article, we are going to see how to measure the Mean Absolute Error (MAE) in PyTorch. [Tex]\text{MAE} = \sum\limits_{i = 1}^n {\left| {{y_i} - \widehat {{y_i}}} \right|}[/Tex] The Mean absolute error (MAE) is computed as the mean of the sum of absolute differences between the input and target values. This is an objective function in many of
3 min read
PyTorch vs PyTorch Lightning
The PyTorch research team at Facebook AI Research (FAIR) introduced PyTorch Lightning to address these challenges and provide a more organized and standardized approach. In this article, we will see the major differences between PyTorch Lightning and Pytorch. Table of Content PytorchPytorch Lightning: Advanced Framework of PytorchPytorch vs Pytorch
9 min read
How to disable GPU in PyTorch (force Pytorch to use CPU instead of GPU)?
PyTorch is a deep learning framework that offers GPU acceleration. This enables the users to utilize the GPU's processing power. The main goal is to accelerate the training and interference processes of deep learning models. PyTorch automatically utilizes the GPU for operations and this leads to quicker computation times. Using the GPU for PyTorch
5 min read
Python | Scipy stats.halfgennorm.entropy() method
With the help of stats.halfgennorm.entropy() method, we can get the value of entropy of random variate by using stats.halfgennorm.entropy() method. Syntax : stats.halfgennorm.entropy(beta) Return : Return the value of entropy of random variate. Example #1 : In this example we can see that by using stats.halfgennorm.entropy() method, we are able to
1 min read
Python | Scipy stats.hypsecant.entropy() method
With the help of stats.hypsecant.entropy() method, we can get the value of entropy of random variate by using stats.hypsecant.entropy() method. Syntax : stats.hypsecant.entropy(beta) Return : Return the value of entropy of random variate. Example #1 : In this example we can see that by using stats.hypsecant.entropy() method, we are able to get the
1 min read
Calculate Undirected Graph's Orientation Entropy Using OSMnx Bearing Module
The measure of entropy describes the heterogeneity of data. For street network modeling, the entropy reveals a city's street order and disorder. Cities with high orientation entropy show that the streets are spread out as much as possible. While low orientation entropy means that the streets are nearly concentrated to a point. In this article, we w
4 min read
Measure similarity between images using Python-OpenCV
Prerequisites: Python OpenCVSuppose we have two data images and a test image. Let's find out which data image is more similar to the test image using python and OpenCV library in Python.Let's first load the image and find out the histogram of images.Importing library import cv2 Importing image data image = cv2.imread('test.jpg') Converting to gray
2 min read
How to compute the element-wise angle of given input tensor in PyTorch?
In this article, we are going to see how to compute the element-wise angle of a given input tensor in PyTorch. torch.angle() method Pytorch is an open-source deep learning framework available with a Python and C++ interface. Pytorch resides inside the torch module. In PyTorch, we will use torch.angle() method to compute the element-wise angle, the
3 min read
How to Pad the Input Tensor Boundaries with Zero in PyTorch
In this article, we will discuss how to pad the input tensor boundaries with zero in Python using PyTorch. torch.nn.ZeroPad2D() method This method has accepted the size of padding as input and returns a new tensor with boundaries. The boundaries may be the same or different from all sides (left, right, top, bottom). we can increase the height and w
2 min read
How to Pad the Input Tensor Boundaries With a Constant Value in PyTorch?
In this article, we will discuss How to Pad the Input Tensor Boundaries With a Constant Value in PyTorch. We can pad the input tensor boundaries with a constant value by using torch.nn.ConstantPad2D() method. torch.nn.ConstantPad2D() method We can pad the boundaries of 3D and 4D tensors and the shape of the input tensor is [C, H, W] and [N, C, H, W
3 min read
How to Compute the Heaviside Step Function for Each Element in Input in PyTorch?
In this article, we are going to cover how to compute the Heaviside step function for each element in input in PyTorch using Python. We can compute this with the help of torch.heaviside() method. torch.heaviside() method The torch.heaviside() method is used to compute the Heaviside step function for each element. This method accepts input and value
2 min read
How to compute element-wise remainder of given input tensor in PyTorch?
In this article, we are going to see how to compute the element-wise remainder in PyTorch. we have two methods to compute element-wise reminders one is torch.remainder() and the other one is torch.fmod() let's go discuss both of them one by one. torch.remainder() method The PyTorch remainder() method computes the element-wise remainder of the divis
3 min read
How to Flatten Input in nn.Sequential in PyTorch
One of the essential operations in neural networks, especially when transitioning from convolutional layers to fully connected layers, is flattening. Flattening transforms a multi-dimensional tensor into a one-dimensional tensor, making it compatible with linear layers. This article explores how to flatten input within nn.Sequential in PyTorch, pro
4 min read
Statistical Functions in Python | Set 1 (Averages and Measure of Central Location)
Python has the ability to manipulate some statistical data and calculate results of various statistical operations using the file "statistics", useful in domain of mathematics. Important Average and measure of central location functions : 1. mean() :- This function returns the mean or average of the data passed in its arguments. If passed argument
3 min read
Katz Centrality (Centrality Measure)
In graph theory, the Katz centrality of a node is a measure of centrality in a network. It was introduced by Leo Katz in 1953 and is used to measure the relative degree of influence of an actor (or node) within a social network. Unlike typical centrality measures which consider only the shortest path (the geodesic) between a pair of actors, Katz ce
7 min read
Percolation Centrality (Centrality Measure)
A slew of centrality measures exist to determine the ‘importance’ of a single node in a complex network. However, these measures quantify the importance of a node in purely topological terms, and the value of the node does not depend on the ‘state’ of the node in any way. It remains constant regardless of network dynamics. This is true even for the
3 min read
How to measure elapsed time in Python?
In Python, we can measure the elapsed time on executing a code segment or a Python script using some built-in Python modules. Here we will cover the usage of time, timeit and datetime module. Using Python timeit Module to measure elapsed time in Python Python timeit module is often used to measure the execution time of small code snippets. We can a
6 min read
Measure Size of an Object Using Python OpenCV
In this article, we will learn about how to measure the size of an object using OpenCV which is implemented in Python. It is implemented by finding the contours around it. This can be done by first loading an image of an object, converting it to grayscale, and applying a threshold to separate the object from the background. It then finds the object
3 min read
Statistical Functions in Python | Set 2 ( Measure of Spread)
Statistical Functions in Python | Set 1(Averages and Measure of Central Location) Measure of spread functions of statistics are discussed in this article. 1. variance() :- This function calculates the variance i.e measure of deviation of data, more the value of variance, more the data values are spread. Sample variance is computed in this function,
2 min read
Betweenness Centrality (Centrality Measure)
In graph theory, betweenness centrality is a measure of centrality in a graph based on shortest paths. For every pair of vertices in a connected graph, there exists at least one shortest path between the vertices such that either the number of edges that the path passes through (for unweighted graphs) or the sum of the weights of the edges (for wei
6 min read
Degree Centrality (Centrality Measure)
Degree In graph theory, the degree (or valency) of a vertex of a graph is the number of edges incident to the vertex, with loops counted twice.[1] The degree of a vertex [Tex] v[/Tex] is denoted [Tex] \deg(v)[/Tex] or [Tex] \deg v[/Tex]. The maximum degree of a graph G, denoted by [Tex]\Delta [/Tex](G), and the minimum degree of a graph, denoted by
5 min read
How to Draw Binary Random Numbers (0 or 1) from a Bernoulli Distribution in PyTorch?
In this article, we discuss how to draw Binary Random Numbers (0 or 1) from a Bernoulli Distribution in PyTorch. torch.bernoulli() method torch.bernoulli() method is used to draw binary random numbers (0 or 1) from a Bernoulli distribution. This method accepts a tensor as a parameter, and this input tensor is the probability of drawing 1. The value
2 min read
Difference between Tensor and Variable in Pytorch
In this article, we are going to see the difference between a Tensor and a variable in Pytorch. Pytorch is an open-source Machine learning library used for computer vision, Natural language processing, and deep neural network processing. It is a torch-based library. It contains a fundamental set of features that allow numerical computation, deploym
3 min read
Difference between PyTorch and TensorFlow
There are various deep learning libraries but the two most famous libraries are PyTorch and Tensorflow. Though both are open source libraries but sometime it becomes difficult to figure out the difference between the two. They are extensively used in commercial code and academic research. PyTorch: It is an open-source library used in machine learni
3 min read
What's the Difference Between PyTorch and TensorFlow Fold?
Answer: PyTorch is a deep learning library that focuses on dynamic computation graphs, while TensorFlow Fold is an extension of TensorFlow designed for dynamic and recursive neural networks.PyTorch and TensorFlow Fold are both deep learning frameworks, but they have different design philosophies and approaches to dynamic computation graphs. Feature
3 min read
What's the Difference Between Reshape and View in PyTorch?
PyTorch, a popular deep learning framework, offers two methods for reshaping tensors: torch.reshape and torch.view. While both methods can be used to change the shape of tensors, they have distinct differences in their behavior, constraints, and implications for memory usage. This article delves into the technical details of these methods, highligh
5 min read
Difference Between detach() and with torch.no_grad() in PyTorch
In PyTorch, managing gradients is crucial for optimizing models and ensuring efficient computations. Two commonly used methods to control gradient tracking are detach() and with torch.no_grad(). Understanding the differences between these two approaches is essential for effectively managing computational graphs and optimizing performance. This arti
6 min read
Article Tags :
Practice Tags :