# Cross-entropy

In information theory, the cross-entropy between two probability distributions $p$ and $q$, over the same underlying set of events, measures the average number of bits needed to identify an event drawn from the set when the coding scheme used for the set is optimized for an estimated probability distribution $q$, rather than the true distribution $p$.

## Definition

The cross-entropy of the distribution $q$ relative to a distribution $p$ over a given set is defined as follows:
$H(p,q)=-\operatorname {E} _{p}[\log q],$
where $E_{p}[\cdot ]$ is the expected value operator with respect to the distribution $p$.
The definition may be formulated using the Kullback–Leibler divergence $D_{\mathrm {KL} }(p\parallel q)$, divergence of $p$ from $q$ (also known as the relative entropy of $p$ with respect to $q$).
$H(p,q)=H(p)+D_{\mathrm {KL} }(p\parallel q),$
where $H(p)$ is the entropy of $p$.
For discrete probability distributions $p$ and $q$ with the same support ${\mathcal {X}}$, this means
$H(p,q)=-\sum _{x\in {\mathcal {X}}}p(x)\,\log q(x).$ (Eq.1)
The situation for continuous distributions is analogous. We have to assume that $p$ and $q$ are absolutely continuous with respect to some reference measure $r$ (usually $r$ is a Lebesgue measure on a Borel σ-algebra). Let $P$ and $Q$ be probability density functions of $p$ and $q$ with respect to $r$. Then
$-\int _{\mathcal {X}}P(x)\,\log Q(x)\,\mathrm {d} x=\operatorname {E} _{p}[-\log Q],$
and therefore
$H(p,q)=-\int _{\mathcal {X}}P(x)\,\log Q(x)\,\mathrm {d} x.$ (Eq.2)
NB: The notation $H(p,q)$ is also used for a different concept, the joint entropy of $p$ and $q$.

## Motivation

In information theory, the Kraft–McMillan theorem establishes that any directly decodable coding scheme for coding a message to identify one value $x_{i}$ out of a set of possibilities $\{x_{1},\ldots ,x_{n}\}$ can be seen as representing an implicit probability distribution $q(x_{i})=\left({\frac {1}{2}}\right)^{\ell _{i}}$ over $\{x_{1},\ldots ,x_{n}\}$, where $\ell _{i}$ is the length of the code for $x_{i}$ in bits. Therefore, cross-entropy can be interpreted as the expected message-length per datum when a wrong distribution $q$ is assumed while the data actually follows a distribution $p$. That is why the expectation is taken over the true probability distribution $p$ and not $q.$ Indeed the expected message-length under the true distribution $p$ is
$\operatorname {E} _{p}[\ell ]=-\operatorname {E} _{p}\left[{\frac {\ln {q(x)}}{\ln(2)}}\right]$ $=-\operatorname {E} _{p}\left[\log _{2}{q(x)}\right]=-\sum _{x_{i}}p(x_{i})\,\log _{2}q(x_{i})$ $=-\sum _{x}p(x)\,\log _{2}q(x)=H(p,q).$

## Estimation

There are many situations where cross-entropy needs to be measured but the distribution of $p$ is unknown. An example is language modeling, where a model is created based on a training set $T$, and then its cross-entropy is measured on a test set to assess how accurate the model is in predicting the test data. In this example, $p$ is the true distribution of words in any corpus, and $q$ is the distribution of words as predicted by the model. Since the true distribution is unknown, cross-entropy cannot be directly calculated. In these cases, an estimate of cross-entropy is calculated using the following formula:
$H(T,q)=-\sum _{i=1}^{N}{\frac {1}{N}}\log _{2}q(x_{i})$
where $N$ is the size of the test set, and $q(x)$ is the probability of event $x$ estimated from the training set. In other words, $q(x_{i})$ is the probability estimate of the model that the i-th word of the text is $x_{i}$. The sum is averaged over the $N$ words of the test. This is a Monte Carlo estimate of the true cross-entropy, where the test set is treated as samples from $p(x)$.

## Relation to maximum likelihood

The cross entropy arises in classification problems when introducing a logarithm in the guise of the log-likelihood function.
The section is concerned with the subject of estimation of the probability of different possible discrete outcomes. To this end, denote a parametrized family of distributions by $q_{\theta }$, with $\theta$ subject to the optimization effort. Consider a given finite sequence of $N$ values $x_{i}$ from a training set, obtained from conditionally independent sampling. The likelihood assigned to any considered parameter $\theta$ of the model is then given by the product over all probabilities $q_{\theta }(X=x_{i})$. Repeated occurrences are possible, leading to equal factors in the product. If the count of occurrences of the value equal to $x_{i}$ (for some index $i$) is denoted by $\#x_{i}$, then the frequency of that value equals $\#x_{i}/N$. Denote the latter by $p(X=x_{i})$, as it may be understood as empirical approximation to the probability distribution underlying the scenario. Further denote by $PP:={\mathrm {e} }^{H(p,q_{\theta })}$ the perplexity, which can be seen to equal ∏$_{xi}$q$_θ$(X=x$_i$)$^{−p(X=xi)}${\textstyle \prod _{x_{i}}q_{\theta }(X=x_{i})^{-p(X=x_{i})}} by the calculation rules for the logarithm, and where the product is over the values without double counting. So ${\mathcal {L}}(\theta ;{\mathbf {x} })=\prod _{i}q_{\theta }(X=x_{i})=\prod _{x_{i}}q_{\theta }(X=x_{i})^{\#x_{i}}=PP^{-N}={\mathrm {e} }^{-N\cdot H(p,q_{\theta })}$ or $\log {\mathcal {L}}(\theta ;{\mathbf {x} })=-N\cdot H(p,q_{\theta }).$ Since the logarithm is a monotonically increasing function, it does not affect extremization. So observe that the likelihood maximization amounts to minimization of the cross-entropy.

## Cross-entropy minimization

Cross-entropy minimization is frequently used in optimization and rare-event probability estimation. When comparing a distribution $q$ against a fixed reference distribution $p$, cross-entropy and KL divergence are identical up to an additive constant (since $p$ is fixed): According to the Gibbs' inequality, both take on their minimal values when $p=q$, which is $0$ for KL divergence, and $\mathrm {H} (p)$ for cross-entropy. In the engineering literature, the principle of minimizing KL divergence (Kullback's "Principle of Minimum Discrimination Information") is often called the Principle of Minimum Cross-Entropy (MCE), or Minxent.
However, as discussed in the article Kullback–Leibler divergence, sometimes the distribution $q$ is the fixed prior reference distribution, and the distribution $p$ is optimized to be as close to $q$ as possible, subject to some constraint. In this case the two minimizations are not equivalent. This has led to some ambiguity in the literature, with some authors attempting to resolve the inconsistency by restating cross-entropy to be $D_{\mathrm {KL} }(p\parallel q)$, rather than $H(p,q)$. In fact, cross-entropy is another name for relative entropy; see Cover and Thomas and Good. On the other hand, $H(p,q)$ does not agree with the literature and can be misleading.

## Cross-entropy loss function and logistic regression

Cross-entropy can be used to define a loss function in machine learning and optimization. Mao, Mohri, and Zhong (2023) give an extensive analysis of the properties of the family of cross-entropy loss functions in machine learning, including theoretical learning guarantees and extensions to adversarial learning. The true probability $p_{i}$ is the true label, and the given distribution $q_{i}$ is the predicted value of the current model. This is also known as the log loss (or logarithmic loss or logistic loss); the terms "log loss" and "cross-entropy loss" are used interchangeably.
More specifically, consider a binary regression model which can be used to classify observations into two possible classes (often simply labelled $0$ and $1$). The output of the model for a given observation, given a vector of input features $x$, can be interpreted as a probability, which serves as the basis for classifying the observation. In logistic regression, the probability is modeled using the logistic function $g(z)=1/(1+e^{-z})$ where $z$ is some function of the input vector $x$, commonly just a linear function. The probability of the output $y=1$ is given by $q_{y=1}={\hat {y}}\equiv g(\mathbf {w} \cdot \mathbf {x} )={\frac {1}{1+e^{-\mathbf {w} \cdot \mathbf {x} }}},$ where the vector of weights $\mathbf {w}$ is optimized through some appropriate algorithm such as gradient descent. Similarly, the complementary probability of finding the output $y=0$ is simply given by $q_{y=0}=1-{\hat {y}}.$
Having set up our notation, $p\in \{y,1-y\}$ and $q\in \{{\hat {y}},1-{\hat {y}}\}$, we can use cross-entropy to get a measure of dissimilarity between $p$ and $q$: $H(p,q)\ =\ -\sum _{i}p_{i}\log q_{i}\ =\ -y\log {\hat {y}}-(1-y)\log(1-{\hat {y}}).$
    Plot shows different loss functions that can be used to train a binary classifier. Only the case where the target output is 1 is shown. It is observed that the loss is zero when the target is equal to the output and increases as the output becomes increasingly incorrect.
Logistic regression typically optimizes the log loss for all the observations on which it is trained, which is the same as optimizing the average cross-entropy in the sample. Other loss functions that penalize errors differently can be also used for training, resulting in models with different final test accuracy. For example, suppose we have $N$ samples with each sample indexed by $n=1,\dots ,N$. The average of the loss function is then given by:
$J(\mathbf {w} )\ =\ {\frac {1}{N}}\sum _{n=1}^{N}H(p_{n},q_{n})\ =\ -{\frac {1}{N}}\sum _{n=1}^{N}\ {\biggy_{n}\log {\hat {y}}_{n}+(1-y_{n})\log(1-{\hat {y}}_{n}){\bigg ]}\,,$
where ${\hat {y}}_{n}\equiv g(\mathbf {w} \cdot \mathbf {x} _{n})=1/(1+e^{-\mathbf {w} \cdot \mathbf {x} _{n}})$, with $g(z)$ the logistic function as before.
The logistic loss is sometimes called cross-entropy loss. It is also known as log loss. (In this case, the binary label is often denoted by {−1,+1}.)
Remark: The gradient of the cross-entropy loss for logistic regression is the same as the gradient of the squared-error loss for linear regression. That is, define
$X^{\mathsf {T}}={\begin{pmatrix}1&x_{11}&\dots &x_{1p}\\1&x_{21}&\cdots &x_{2p}\\\vdots &\vdots &&\vdots \\1&x_{n1}&\cdots &x_{np}\\\end{pmatrix}}\in \mathbb {R} ^{n\times (p+1)},$ ${\hat {y_{i}}}={\hat {f}}(x_{i1},\dots ,x_{ip})={\frac {1}{1+\exp(-\beta _{0}-\beta _{1}x_{i1}-\dots -\beta _{p}x_{ip})}},$ $L({\boldsymbol {\beta }})=-\sum _{i=1}^{N}\left[y_{i}\log {\hat {y}}_{i}+(1-y_{i})\log(1-{\hat {y}}_{i})\right].$
Then we have the result
${\frac {\partial }{\partial {\boldsymbol {\beta }}}}L({\boldsymbol {\beta }})=X^{T}({\hat {Y}}-Y).$
The proof is as follows. For any ${\hat {y}}_{i}$, we have
${\frac {\partial }{\partial \beta _{0}}}\ln {\frac {1}{1+e^{-\beta _{0}+k_{0}}}}={\frac {e^{-\beta _{0}+k_{0}}}{1+e^{-\beta _{0}+k_{0}}}},$ ${\frac {\partial }{\partial \beta _{0}}}\ln \left(1-{\frac {1}{1+e^{-\beta _{0}+k_{0}}}}\right)={\frac {-1}{1+e^{-\beta _{0}+k_{0}}}},$ ${\begin{aligned}{\frac {\partial }{\partial \beta _{0}}}L({\boldsymbol {\beta }})&=-\sum _{i=1}^{N}\left[{\frac {y_{i}\cdot e^{-\beta _{0}+k_{0}}}{1+e^{-\beta _{0}+k_{0}}}}-(1-y_{i}){\frac {1}{1+e^{-\beta _{0}+k_{0}}}}\right]\\&=-\sum _{i=1}^{N}\left[y_{i}-{\hat {y}}_{i}\right]=\sum _{i=1}^{N}({\hat {y}}_{i}-y_{i}),\end{aligned}}$ ${\frac {\partial }{\partial \beta _{1}}}\ln {\frac {1}{1+e^{-\beta _{1}x_{i1}+k_{1}}}}={\frac {x_{i1}e^{k_{1}}}{e^{\beta _{1}x_{i1}}+e^{k_{1}}}},$ ${\frac {\partial }{\partial \beta _{1}}}\ln \left[1-{\frac {1}{1+e^{-\beta _{1}x_{i1}+k_{1}}}}\right]={\frac {-x_{i1}e^{\beta _{1}x_{i1}}}{e^{\beta _{1}x_{i1}}+e^{k_{1}}}},$ ${\frac {\partial }{\partial \beta _{1}}}L({\boldsymbol {\beta }})=-\sum _{i=1}^{N}x_{i1}(y_{i}-{\hat {y}}_{i})=\sum _{i=1}^{N}x_{i1}({\hat {y}}_{i}-y_{i}).$
In a similar way, we eventually obtain the desired result.

## Amended cross-entropy

It may be beneficial to train an ensemble of models that have diversity, such that when they are combined, their predictive accuracy is augmented. Assuming a simple ensemble of $K$ classifiers is assembled via averaging the outputs, then the amended cross-entropy is given by $e^{k}=H(p,q^{k})-{\frac {\lambda }{K}}\sum _{j\neq k}H(q^{j},q^{k})$ where $e^{k}$ is the cost function of the $k^{th}$ classifier, $q^{k}$ is the output probability of the $k^{th}$ classifier, $p$ is the true probability to be estimated, and $\lambda$ is a parameter between 0 and 1 that defines the 'diversity' that we would like to establish among the ensemble. When $\lambda =0$ we want each classifier to do its best regardless of the ensemble and when $\lambda =1$ we would like the classifier to be as diverse as possible.