{"id":2716,"date":"2019-10-20T18:00:36","date_gmt":"2019-10-20T18:00:36","guid":{"rendered":"https:\/\/www.aiproblog.com\/index.php\/2019\/10\/20\/a-gentle-introduction-to-cross-entropy-for-machine-learning\/"},"modified":"2019-10-20T18:00:36","modified_gmt":"2019-10-20T18:00:36","slug":"a-gentle-introduction-to-cross-entropy-for-machine-learning","status":"publish","type":"post","link":"https:\/\/www.aiproblog.com\/index.php\/2019\/10\/20\/a-gentle-introduction-to-cross-entropy-for-machine-learning\/","title":{"rendered":"A Gentle Introduction to Cross-Entropy for Machine Learning"},"content":{"rendered":"<p>Author: Jason Brownlee<\/p>\n<div>\n<p>Cross-entropy is commonly used in machine learning as a loss function.<\/p>\n<p>Cross-entropy is a measure from the field of information theory, building upon entropy and generally calculating the difference between two probability distributions. It is closely related to but is different from KL divergence that calculates the relative entropy between two probability distributions, whereas cross-entropy can be thought to calculate the total entropy between the distributions.<\/p>\n<p>Cross-entropy is also related to and often confused with logistic loss, called log loss. Although the two measures are derived from a different source, when used as loss functions for classification models, both measures calculate the same quantity and can be used interchangeably.<\/p>\n<p>In this tutorial, you will discover cross-entropy for machine learning.<\/p>\n<p>After completing this tutorial, you will know:<\/p>\n<ul>\n<li>How to calculate cross-entropy from scratch and using standard machine learning libraries.<\/li>\n<li>Cross-entropy can be used as a loss function when optimizing classification models like logistic regression and artificial neural networks.<\/li>\n<li>Cross-entropy is different from KL divergence but can be calculated using KL divergence, and is different from log loss but calculates the same quantity when used as a loss function.<\/li>\n<\/ul>\n<p>Discover bayes opimization, naive bayes, maximum likelihood, distributions, cross entropy, and much more <a href=\"https:\/\/machinelearningmastery.com\/probability-for-machine-learning\/\" rel=\"nofollow\">in my new book<\/a>, with 28 step-by-step tutorials and full Python source code.<\/p>\n<p>Let\u2019s get started.<\/p>\n<div id=\"attachment_8886\" style=\"width: 650px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-8886\" class=\"size-full wp-image-8886\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/10\/A-Gentle-Introduction-to-Cross-Entropy-for-Machine-Learning.jpg\" alt=\"A Gentle Introduction to Cross-Entropy for Machine Learning\" width=\"640\" height=\"480\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/10\/A-Gentle-Introduction-to-Cross-Entropy-for-Machine-Learning.jpg 640w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/10\/A-Gentle-Introduction-to-Cross-Entropy-for-Machine-Learning-300x225.jpg 300w\" sizes=\"(max-width: 640px) 100vw, 640px\"><\/p>\n<p id=\"caption-attachment-8886\" class=\"wp-caption-text\">A Gentle Introduction to Cross-Entropy for Machine Learning<br \/>Photo by <a href=\"https:\/\/www.flickr.com\/photos\/girolame\/3819120378\/\">Jerome Bon<\/a>, some rights reserved.<\/p>\n<\/div>\n<h2>Tutorial Overview<\/h2>\n<p>This tutorial is divided into five parts; they are:<\/p>\n<ol>\n<li>What Is Cross-Entropy?<\/li>\n<li>Difference Between Cross-Entropy and KL Divergence<\/li>\n<li>How to Calculate Cross-Entropy?<\/li>\n<li>Cross-Entropy as a Loss Function<\/li>\n<li>Difference Between Cross-Entropy and Log Loss<\/li>\n<\/ol>\n<h2>What Is Cross-Entropy?<\/h2>\n<p>Cross-entropy is a measure of the difference between two probability distributions for a given random variable or set of events.<\/p>\n<p>Specifically, it builds upon the idea of entropy from information theory and calculates the average number of bits required to represent or transmit an event from one distribution compared to the other distribution.<\/p>\n<blockquote>\n<p>\u2026 the cross entropy is the average number of bits needed to encode data coming from a source with distribution p when we use model q \u2026<\/p>\n<\/blockquote>\n<p>\u2014 Page 57, <a href=\"https:\/\/amzn.to\/2xKSTCP\">Machine Learning: A Probabilistic Perspective<\/a>, 2012.<\/p>\n<p>The intuition for this definition comes if we consider a target or underlying probability distribution P and an approximation of the target distribution Q, then the cross-entropy of Q from P is the number of additional bits to represent an event using Q instead of P.<\/p>\n<p>The cross-entropy between two probability distributions, such as Q from P, can be stated formally as:<\/p>\n<ul>\n<li>H(P, Q)<\/li>\n<\/ul>\n<p>Where H() is the cross-entropy function, P may be the target distribution and Q is the approximation of the target distribution.<\/p>\n<p>Cross-entropy can be calculated using the probabilities of the events from P and Q, as follows:<\/p>\n<ul>\n<li>H(P, Q) = \u2013 sum x in X P(x) * log(Q(x))<\/li>\n<\/ul>\n<p>Where P(x) is the probability of the event x in P, Q(x) is the probability of event x in Q and log is the base-2 logarithm, meaning that the results are in bits. If the base-e or natural logarithm is used instead, the result will have the units called nats.<\/p>\n<p>This calculation is for discrete probability distributions, although a similar calculation can be used for continuous probability distributions using the integral across the events instead of the sum.<\/p>\n<p>The result will be a positive number measured in bits and 0 if the two probability distributions are identical.<\/p>\n<p><strong>Note<\/strong>: this notation looks a lot like the joint probability, or more specifically, the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Joint_entropy\">joint entropy<\/a> between P and Q. This is misleading as we are scoring the difference between probability distributions with cross-entropy. Whereas, joint entropy is a different concept that uses the same notation and instead calculates the uncertainty across two (or more) random variables.<\/p>\n<div class=\"woo-sc-hr\"><\/div>\n<p><center><\/p>\n<h3>Want to Learn Probability for Machine Learning<\/h3>\n<p>Take my free 7-day email crash course now (with sample code).<\/p>\n<p>Click to sign-up and also get a free PDF Ebook version of the course.<\/p>\n<p><a href=\"https:\/\/machinelearningmastery.lpages.co\/leadbox\/16cf92561172a2%3A164f8be4f346dc\/4623731828588544\/\" target=\"_blank\" style=\"background: rgb(255, 206, 10); color: rgb(255, 255, 255); text-decoration: none; font-family: Helvetica, Arial, sans-serif; font-weight: bold; font-size: 16px; line-height: 20px; padding: 10px; display: inline-block; max-width: 300px; border-radius: 5px; text-shadow: rgba(0, 0, 0, 0.25) 0px -1px 1px; box-shadow: rgba(255, 255, 255, 0.5) 0px 1px 3px inset, rgba(0, 0, 0, 0.5) 0px 1px 3px;\" rel=\"noopener noreferrer\">Download Your FREE Mini-Course<\/a><script data-leadbox=\"16cf92561172a2:164f8be4f346dc\" data-url=\"https:\/\/machinelearningmastery.lpages.co\/leadbox\/16cf92561172a2%3A164f8be4f346dc\/4623731828588544\/\" data-config=\"%7B%7D\" type=\"text\/javascript\" src=\"https:\/\/machinelearningmastery.lpages.co\/leadbox-1568216021.js\"><\/script><\/p>\n<p><\/center><\/p>\n<div class=\"woo-sc-hr\"><\/div>\n<h2>Difference Between Cross-Entropy and KL Divergence<\/h2>\n<p>Cross-entropy is not KL Divergence.<\/p>\n<p>Cross-entropy is related to divergence measures, such as the Kullback-Leibler, or KL, Divergence that quantifies how much one distribution differs from another.<\/p>\n<p>Specifically, the KL divergence measures a very similar quantity to cross-entropy. It measures the average number of extra bits required to represent a message with Q instead of P, not the total number of bits.<\/p>\n<blockquote>\n<p>In other words, the KL divergence is the average number of extra bits needed to encode the data, due to the fact that we used distribution q to encode the data instead of the true distribution p.<\/p>\n<\/blockquote>\n<p>\u2014 Page 58, <a href=\"https:\/\/amzn.to\/2xKSTCP\">Machine Learning: A Probabilistic Perspective<\/a>, 2012.<\/p>\n<p>As such, the KL divergence is often referred to as the \u201c<em>relative entropy<\/em>.\u201d<\/p>\n<ul>\n<li><strong>Cross-Entropy<\/strong>: Average number of total bits to represent an event from Q instead of P.<\/li>\n<li><strong>Relative Entropy<\/strong> (<em>KL Divergence<\/em>): Average number of extra bits to represent an event from Q instead of P.<\/li>\n<\/ul>\n<p>KL divergence can be calculated as the negative sum of probability of each event in P multiples by the log of the probability of the event in Q over the probability of the event in P. Typically, log base-2 so that the result is measured in bits.<\/p>\n<ul>\n<li>KL(P || Q) = \u2013 sum x in X P(x) * log(Q(x) \/ P(x))<\/li>\n<\/ul>\n<p>The value within the sum is the divergence for a given event.<\/p>\n<p>As such, we can calculate the cross-entropy by adding the entropy of the distribution plus the additional entropy calculated by the KL divergence. This is intuitive, given the definition of both calculations; for example:<\/p>\n<ul>\n<li>H(P, Q) = H(P) + KL(P || Q)<\/li>\n<\/ul>\n<p>Where H(P, Q) is the cross-entropy of Q from P, H(P) is the entropy of P and KL(P || Q) is the divergence of Q from P.<\/p>\n<p>Entropy can be calculated for a probability distribution as the negative sum of the probability for each event multiplied by the log of the probability for the event, where log is base-2 to ensure the result is in bits.<\/p>\n<ul>\n<li>H(P) = \u2013 sum x on X p(x) * log(p(x))<\/li>\n<\/ul>\n<p>Like KL divergence, cross-entropy is not symmetrical, meaning that:<\/p>\n<ul>\n<li>H(P, Q) != H(Q, P)<\/li>\n<\/ul>\n<h2>How to Calculate Cross-Entropy<\/h2>\n<p>We can make the calculation of cross-entropy concrete with a small example.<\/p>\n<p>Consider a random variable with three events as different colors. We may have two different probability distributions for this variable; for example:<\/p>\n<pre class=\"crayon-plain-tag\">...\r\n# define distributions\r\nevents = ['red', 'green', 'blue']\r\np = [0.10, 0.40, 0.50]\r\nq = [0.80, 0.15, 0.05]<\/pre>\n<p>We can plot a bar chart of these probabilities to compare them directly as probability histograms.<\/p>\n<p>The complete example is listed below.<\/p>\n<pre class=\"crayon-plain-tag\"># plot of distributions\r\nfrom matplotlib import pyplot\r\n# define distributions\r\nevents = ['red', 'green', 'blue']\r\np = [0.10, 0.40, 0.50]\r\nq = [0.80, 0.15, 0.05]\r\nprint('P=%.3f Q=%.3f' % (sum(p), sum(q)))\r\n# plot first distribution\r\npyplot.subplot(2,1,1)\r\npyplot.bar(events, p)\r\n# plot second distribution\r\npyplot.subplot(2,1,2)\r\npyplot.bar(events, q)\r\n# show the plot\r\npyplot.show()<\/pre>\n<p>Running the example creates a histogram for each probability distribution, allowing the probabilities for each event to be directly compared.<\/p>\n<p>We can see that indeed the distributions are different.<\/p>\n<div id=\"attachment_8884\" style=\"width: 1290px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-8884\" class=\"size-full wp-image-8884\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2019\/08\/Histogram-of-Two-Different-Probability-Distributions-for-the-same-Random-Variable-1.png\" alt=\"Histogram of Two Different Probability Distributions for the Same Random Variable\" width=\"1280\" height=\"960\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/08\/Histogram-of-Two-Different-Probability-Distributions-for-the-same-Random-Variable-1.png 1280w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/08\/Histogram-of-Two-Different-Probability-Distributions-for-the-same-Random-Variable-1-300x225.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/08\/Histogram-of-Two-Different-Probability-Distributions-for-the-same-Random-Variable-1-768x576.png 768w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2019\/08\/Histogram-of-Two-Different-Probability-Distributions-for-the-same-Random-Variable-1-1024x768.png 1024w\" sizes=\"(max-width: 1280px) 100vw, 1280px\"><\/p>\n<p id=\"caption-attachment-8884\" class=\"wp-caption-text\">Histogram of Two Different Probability Distributions for the Same Random Variable<\/p>\n<\/div>\n<p>Next, we can develop a function to calculate the cross-entropy between the two distributions.<\/p>\n<p>We will use log base-2 to ensure the result has units in bits.<\/p>\n<pre class=\"crayon-plain-tag\"># calculate cross entropy\r\ndef cross_entropy(p, q):\r\n\treturn -sum([p[i]*log2(q[i]) for i in range(len(p))])<\/pre>\n<p>We can then use this function to calculate the cross-entropy of P from Q, as well as the reverse, Q from P.<\/p>\n<pre class=\"crayon-plain-tag\">...\r\n# calculate cross entropy H(P, Q)\r\nce_pq = cross_entropy(p, q)\r\nprint('H(P, Q): %.3f bits' % ce_pq)\r\n# calculate cross entropy H(Q, P)\r\nce_qp = cross_entropy(q, p)\r\nprint('H(Q, P): %.3f bits' % ce_qp)<\/pre>\n<p>Tying this all together, the complete example is listed below.<\/p>\n<pre class=\"crayon-plain-tag\"># example of calculating cross entropy\r\nfrom math import log2\r\n\r\n# calculate cross entropy\r\ndef cross_entropy(p, q):\r\n\treturn -sum([p[i]*log2(q[i]) for i in range(len(p))])\r\n\r\n# define data\r\np = [0.10, 0.40, 0.50]\r\nq = [0.80, 0.15, 0.05]\r\n# calculate cross entropy H(P, Q)\r\nce_pq = cross_entropy(p, q)\r\nprint('H(P, Q): %.3f bits' % ce_pq)\r\n# calculate cross entropy H(Q, P)\r\nce_qp = cross_entropy(q, p)\r\nprint('H(Q, P): %.3f bits' % ce_qp)<\/pre>\n<p>Running the example first calculates the cross-entropy of Q from P as just over 3 bits, then P from Q as just under 3 bits.<\/p>\n<pre class=\"crayon-plain-tag\">H(P, Q): 3.288 bits\r\nH(Q, P): 2.906 bits<\/pre>\n<p>We can also calculate the cross-entropy using the KL divergence.<\/p>\n<p>The cross-entropy calculated with KL divergence should be identical, and it may be interesting to calculate the KL divergence between the distributions as well to see the relative entropy or additional bits required instead of the total bits calculated by the cross-entropy.<\/p>\n<p>First, we can define a function to calculate the KL divergence between the distributions using log base-2 to ensure the result is also in bits.<\/p>\n<pre class=\"crayon-plain-tag\"># calculate the kl divergence KL(P || Q)\r\ndef kl_divergence(p, q):\r\n\treturn sum(p[i] * log2(p[i]\/q[i]) for i in range(len(p)))<\/pre>\n<p>Next, we can define a function to calculate the entropy for a given probability distribution.<\/p>\n<pre class=\"crayon-plain-tag\"># calculate entropy H(P)\r\ndef entropy(p):\r\n\treturn -sum([p[i] * log2(p[i]) for i in range(len(p))])<\/pre>\n<p>Finally, we can calculate the cross-entropy using the <em>entropy()<\/em> and <em>kl_divergence()<\/em> functions.<\/p>\n<pre class=\"crayon-plain-tag\"># calculate cross entropy H(P, Q)\r\ndef cross_entropy(p, q):\r\n\treturn entropy(p) + kl_divergence(p, q)<\/pre>\n<p>To keep the example simple, we can compare the cross-entropy for H(P, Q) to the KL divergence KL(P || Q) and the entropy H(P).<\/p>\n<p>The complete example is listed below.<\/p>\n<pre class=\"crayon-plain-tag\"># example of calculating cross entropy with kl divergence\r\nfrom math import log2\r\n\r\n# calculate the kl divergence KL(P || Q)\r\ndef kl_divergence(p, q):\r\n\treturn sum(p[i] * log2(p[i]\/q[i]) for i in range(len(p)))\r\n\r\n# calculate entropy H(P)\r\ndef entropy(p):\r\n\treturn -sum([p[i] * log2(p[i]) for i in range(len(p))])\r\n\r\n# calculate cross entropy H(P, Q)\r\ndef cross_entropy(p, q):\r\n\treturn entropy(p) + kl_divergence(p, q)\r\n\r\n# define data\r\np = [0.10, 0.40, 0.50]\r\nq = [0.80, 0.15, 0.05]\r\n# calculate H(P)\r\nen_p = entropy(p)\r\nprint('H(P): %.3f bits' % en_p)\r\n# calculate kl divergence KL(P || Q)\r\nkl_pq = kl_divergence(p, q)\r\nprint('KL(P || Q): %.3f bits' % kl_pq)\r\n# calculate cross entropy H(P, Q)\r\nce_pq = cross_entropy(p, q)\r\nprint('H(P, Q): %.3f bits' % ce_pq)<\/pre>\n<p>Running the example, we can see that the cross-entropy score of 3.288 bits is comprised of the entropy of P 1.361 and the additional 1.927 bits calculated by the KL divergence.<\/p>\n<p>This is a useful example that clearly illustrates the relationship between all three calculations.<\/p>\n<pre class=\"crayon-plain-tag\">H(P): 1.361 bits\r\nKL(P || Q): 1.927 bits\r\nH(P, Q): 3.288 bits<\/pre>\n<\/p>\n<h2>Cross-Entropy as a Loss Function<\/h2>\n<p>Cross-entropy is widely used as a loss function when optimizing classification models.<\/p>\n<p>Two examples that you may encounter include the logistic regression algorithm (a linear classification algorithm), and artificial neural networks that can be used for classification tasks.<\/p>\n<blockquote>\n<p>\u2026 using the cross-entropy error function instead of the sum-of-squares for a classification problem leads to faster training as well as improved generalization.<\/p>\n<\/blockquote>\n<p>\u2014 Page 235, <a href=\"https:\/\/amzn.to\/2JwHE7I\">Pattern Recognition and Machine Learning<\/a>, 2006.<\/p>\n<p>Classification problems are those that involve one or more input variables and the prediction of a class label. Classification tasks that have just two labels for the output variable are referred to as binary classification problems, whereas those problems with more than two labels are referred to as categorical or multi-class classification problems.<\/p>\n<ul>\n<li><strong>Binary Classification<\/strong>: Task of predicting one of two class labels for a given example.<\/li>\n<li><strong>Multi-Class Classification<\/strong>: Task of predicting one of more than two class labels for a given example.<\/li>\n<\/ul>\n<p>We can see that the idea of cross-entropy may be useful for optimizing a classification model: that is, in calculating the difference between the probability distribution of class labels in the dataset and those predicted by the model.<\/p>\n<p>In classification tasks, we do not have the target probability distribution P; instead, we must estimate it from the dataset. The predictions from the model represent the approximation of the target probability distribution Q. In the language of classification, these are the actual and the predicted probabilities, or y and yhat.<\/p>\n<ul>\n<li><strong>Expected Probability<\/strong> (<em>y<\/em>): The probability of class labels taken from the dataset (P).<\/li>\n<li><strong>Predicted Probability<\/strong> (<em>yhat<\/em>): The probability of class labels predicted by the model (Q).<\/li>\n<\/ul>\n<p>We can, therefore, estimate the cross-entropy for a single prediction using the cross-entropy calculation described above; for example.<\/p>\n<ul>\n<li>H(P, Q) = \u2013 sum x in X P(x) * log(Q(x))<\/li>\n<\/ul>\n<p>Where each x in X is a class label that could be assigned to the example, and P(x) will be 1 for the known label and 0 for all other labels.<\/p>\n<p>If there are just two class labels, e.g. binary classification, then the probability for class 0 is predicted directly, and the probability for class 1 is given as one minus the probability. As such, the cross-entropy for a single example in a binary classification task can be stated by unrolling the sum operation as follows:<\/p>\n<ul>\n<li>H(P, Q) = \u2013 (P(class0) * log(Q(class0)) + P(class1) * log(Q(class1)))<\/li>\n<\/ul>\n<p>You may see this form of calculating cross-entropy cited in textbooks.<\/p>\n<p>When calculating cross-entropy for classification tasks, the base-e or natural logarithm is used. This means that the units are in nats, not bits.<\/p>\n<p>We are often interested in minimizing the cross-entropy for the model across the entire training dataset. This is calculated by calculating the average cross-entropy across all training examples. As such, a cross-entropy of 0.0 indicates that the predicted probabilities from the model are identical to the probabilities in the training dataset, e.g. zero loss. In practice, a cross-entropy loss of 0.0 often indicates that the model has overfit the training dataset.<\/p>\n<p>The use of cross-entropy for classification often gives different specific names based on the number of classes, mirroring the name of the classification task; for example:<\/p>\n<ul>\n<li><strong>Binary Cross-Entropy<\/strong>: Cross-entropy as a loss function for a binary classification task.<\/li>\n<li><strong>Categorical Cross-Entropy<\/strong>: Cross-entropy as a loss function for a multi-class classification task.<\/li>\n<\/ul>\n<p>We can make the use of cross-entropy as a loss function concrete with a worked example.<\/p>\n<p>Consider a binary classification task with the following 10 actual class labels (P) and predicted class labels (Q).<\/p>\n<pre class=\"crayon-plain-tag\">...\r\n# define classification data\r\np = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]\r\nq = [0.8, 0.9, 0.9, 0.6, 0.8, 0.1, 0.4, 0.2, 0.1, 0.3]<\/pre>\n<p>We can enumerate these probabilities and calculate the cross-entropy for each using the cross-entropy function developed in the previous section using <em>log()<\/em> (natural logarithm) instead of <em>log2()<\/em>.<\/p>\n<pre class=\"crayon-plain-tag\"># calculate cross entropy\r\ndef cross_entropy(p, q):\r\n\treturn -sum([p[i]*log(q[i]) for i in range(len(p))])<\/pre>\n<p>For each actual and predicted probability, we must convert the prediction into a distribution of probabilities across each state, in this case, the states {0, 1} as the probability and 1-probability.<\/p>\n<p>We can then calculate the cross-entropy and repeat the process for all examples.<\/p>\n<pre class=\"crayon-plain-tag\">...\r\n# calculate cross entropy for each example\r\nresults = list()\r\nfor i in range(len(p)):\r\n\t# create the distribution for each event {0, 1}\r\n\texpected = [p[i], 1.0 - p[i]]\r\n\tpredicted = [q[i], 1.0 - q[i]]\r\n\t# calculate cross entropy for the two events\r\n\tce = cross_entropy(expected, predicted)\r\n\tprint('>[y=%.1f, yhat=%.1f] ce: %.3f nats' % (p[i], q[i], ce))\r\n\tresults.append(ce)<\/pre>\n<p>Finally, we can calculate the average cross-entropy across the dataset and report it as the cross-entropy loss for the model on the dataset.<\/p>\n<pre class=\"crayon-plain-tag\">...\r\n# calculate the average cross entropy\r\nmean_ce = mean(results)\r\nprint('Average Cross Entropy: %.3f nats' % mean_ce)<\/pre>\n<p>Tying this all together, the complete example is listed below.<\/p>\n<pre class=\"crayon-plain-tag\"># calculate cross entropy for classification problem\r\nfrom math import log\r\nfrom numpy import mean\r\n\r\n# calculate cross entropy\r\ndef cross_entropy(p, q):\r\n\treturn -sum([p[i]*log(q[i]) for i in range(len(p))])\r\n\r\n# define classification data\r\np = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]\r\nq = [0.8, 0.9, 0.9, 0.6, 0.8, 0.1, 0.4, 0.2, 0.1, 0.3]\r\n# calculate cross entropy for each example\r\nresults = list()\r\nfor i in range(len(p)):\r\n\t# create the distribution for each event {0, 1}\r\n\texpected = [p[i], 1.0 - p[i]]\r\n\tpredicted = [q[i], 1.0 - q[i]]\r\n\t# calculate cross entropy for the two events\r\n\tce = cross_entropy(expected, predicted)\r\n\tprint('>[y=%.1f, yhat=%.1f] ce: %.3f nats' % (p[i], q[i], ce))\r\n\tresults.append(ce)\r\n\r\n# calculate the average cross entropy\r\nmean_ce = mean(results)\r\nprint('Average Cross Entropy: %.3f nats' % mean_ce)<\/pre>\n<p>Running the example prints the actual and predicted probabilities for each example and the cross-entropy in nats.<\/p>\n<p>The final average cross-entropy loss across all examples is reported, in this case, as 0.247 nats.<\/p>\n<pre class=\"crayon-plain-tag\">>[y=1.0, yhat=0.8] ce: 0.223 nats\r\n>[y=1.0, yhat=0.9] ce: 0.105 nats\r\n>[y=1.0, yhat=0.9] ce: 0.105 nats\r\n>[y=1.0, yhat=0.6] ce: 0.511 nats\r\n>[y=1.0, yhat=0.8] ce: 0.223 nats\r\n>[y=0.0, yhat=0.1] ce: 0.105 nats\r\n>[y=0.0, yhat=0.4] ce: 0.511 nats\r\n>[y=0.0, yhat=0.2] ce: 0.223 nats\r\n>[y=0.0, yhat=0.1] ce: 0.105 nats\r\n>[y=0.0, yhat=0.3] ce: 0.357 nats\r\nAverage Cross Entropy: 0.247 nats<\/pre>\n<p>This is how cross-entropy loss is calculated when optimizing a logistic regression model or a neural network model under a cross-entropy loss function.<\/p>\n<p>We can confirm this by using the <em>binary_crossentropy()<\/em> function from the <a href=\"https:\/\/keras.io\/losses\/\">Keras deep learning API<\/a> to calculate the cross-entropy loss for our small dataset.<\/p>\n<p>The complete example is listed below.<\/p>\n<p><strong>Note<\/strong>: This example assumes that you have the <a href=\"https:\/\/machinelearningmastery.com\/tutorial-first-neural-network-python-keras\/\">Keras library<\/a> installed and configured with a backend library such as TensorFlow. If not, you can skip running this example.<\/p>\n<pre class=\"crayon-plain-tag\"># calculate cross entropy with keras\r\nfrom numpy import asarray\r\nfrom keras import backend\r\nfrom keras.losses import binary_crossentropy\r\n# prepare classification data\r\np = asarray([1, 1, 1, 1, 1, 0, 0, 0, 0, 0])\r\nq = asarray([0.8, 0.9, 0.9, 0.6, 0.8, 0.1, 0.4, 0.2, 0.1, 0.3])\r\n# convert to keras variables\r\ny_true = backend.variable(p)\r\ny_pred = backend.variable(q)\r\n# calculate the average cross-entropy\r\nmean_ce = backend.eval(binary_crossentropy(y_true, y_pred))\r\nprint('Average Cross Entropy: %.3f nats' % mean_ce)<\/pre>\n<p>Running the example, we can see that the same average cross-entropy loss of 0.247 nats is reported.<\/p>\n<p>This confirms the correct manual calculation of cross-entropy.<\/p>\n<pre class=\"crayon-plain-tag\">Average Cross Entropy: 0.247 nats<\/pre>\n<p>We can see that we could just as easily minimize the KL divergence as a loss function instead of the cross-entropy. The specific values would be different, but the effect would be the same as the two values are proportional to each other (e.g. minus the constant of the entropy for P).<\/p>\n<blockquote>\n<p>Minimizing this KL divergence corresponds exactly to minimizing the cross-entropy between the distributions.<\/p>\n<\/blockquote>\n<p>\u2014 Page 132, <a href=\"https:\/\/amzn.to\/2lnc3vL\">Deep Learning<\/a>, 2016.<\/p>\n<h2>Difference Between Cross-Entropy and Log Loss<\/h2>\n<p>Cross-Entropy is not Log Loss, but they calculate the same quantity when used as loss functions for binary classification problems.<\/p>\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Loss_functions_for_classification#Logistic_loss\">Logistic loss<\/a> refers to the loss function commonly used to optimize a logistic regression model.<\/p>\n<p>It may also be referred to as logarithmic loss (which is confusing) or simply log loss.<\/p>\n<p>Many models are optimized under a probabilistic framework called the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Maximum_likelihood_estimation\">maximum likelihood estimation<\/a>, or MLE, that involves finding a set of parameters that best explain the observed data.<\/p>\n<p>This involves selecting a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Likelihood_function\">likelihood function<\/a> that defines how likely a set of observations (data) are given model parameters. When a log likelihood function is used (which is common), it is often referred to as optimizing the log likelihood for the model. Because it is more common to minimize a function than to maximize it in practice, the log likelihood function is inverted by adding a negative sign to the front. This transforms it into a Negative Log Likelihood function or NLL for short.<\/p>\n<p>In deriving the log likelihood function under a framework of maximum likelihood estimation for Bernoulli probability distribution functions (two classes), the calculation comes out to be:<\/p>\n<ul>\n<li>negative log-likelihood(P, Q) = -(P(class0) * log(Q(class0)) + P(class1) * log(Q(class1)))<\/li>\n<\/ul>\n<p>This quantity can be averaged over all training examples by calculating the average of the log of the likelihood function.<\/p>\n<p>Negative log-likelihood for binary classification problems is often shortened to simply \u201clog loss\u201d as the loss function derived for logistic regression.<\/p>\n<ul>\n<li>log loss = negative log-likelihood, under a Bernoulli probability distribution<\/li>\n<\/ul>\n<p>We can see that the negative log-likelihood is the same calculation as is used for the cross-entropy for Bernoulli probability distribution functions (two events or classes). In fact, the negative log-likelihood for Multinoulli distributions (multi-class classification) also matches the calculation for cross-entropy.<\/p>\n<p>For binary classification problems, \u201c<em>log loss<\/em>\u201c, \u201c<em>cross-entropy<\/em>\u201d and \u201c<em>negative log-likelihood<\/em>\u201d are used interchangeably.<\/p>\n<p>More generally, the terms \u201c<em>cross-entropy<\/em>\u201d and \u201c<em>negative log-likelihood<\/em>\u201d are used interchangeably in the context of loss functions for classification models.<\/p>\n<blockquote>\n<p>The negative log-likelihood for logistic regression is given by [\u2026] This is also called the cross-entropy error function.<\/p>\n<\/blockquote>\n<p>\u2014 Page 246, <a href=\"https:\/\/amzn.to\/2xKSTCP\">Machine Learning: A Probabilistic Perspective<\/a>, 2012.<\/p>\n<p>Therefore, calculating log loss will give the same quantity as calculating the cross-entropy for Bernoulli probability distribution. We can confirm this by calculating the log loss using the <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.metrics.log_loss.html\">log_loss() function<\/a> from the scikit-learn API.<\/p>\n<p>Calculating the average log loss on the same set of actual and predicted probabilities from the previous section should give the same result as calculating the average cross-entropy.<\/p>\n<p>The complete example is listed below.<\/p>\n<pre class=\"crayon-plain-tag\"># calculate log loss for classification problem with scikit-learn\r\nfrom sklearn.metrics import log_loss\r\nfrom numpy import asarray\r\n# define classification data\r\np = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]\r\nq = [0.8, 0.9, 0.9, 0.6, 0.8, 0.1, 0.4, 0.2, 0.1, 0.3]\r\n# define data as expected, e.g. probability for each event {0, 1}\r\ny_true = asarray([[v, 1-v] for v in p])\r\ny_pred = asarray([[v, 1-v] for v in q])\r\n# calculate the average log loss\r\nll = log_loss(y_true, y_pred)\r\nprint('Average Log Loss: %.3f' % ll)<\/pre>\n<p>Running the example gives the expected result of 0.247 log loss, which matches 0.247 nats when calculated using the average cross-entropy.<\/p>\n<pre class=\"crayon-plain-tag\">Average Log Loss: 0.247<\/pre>\n<p>This does not mean that log loss calculates cross-entropy or cross-entropy calculates log loss.<\/p>\n<p>Instead, they are different quantities, arrived at from different fields of study, that under the conditions of calculating a loss function for a classification task, result in an equivalent calculation and result. Specifically, a cross-entropy loss function is equivalent to a maximum likelihood function under a Bernoulli or Multinoulli probability distribution.<\/p>\n<p>More generally, a cross-entropy for a continuous probability distribution such as a Gaussian is equivalent to the mean squared error likelihood function.<\/p>\n<blockquote>\n<p>Any loss consisting of a negative log-likelihood is a cross- entropy between the empirical distribution defined by the training set and the probability distribution defined by model. For example, mean squared error is the cross-entropy between the empirical distribution and a Gaussian model.<\/p>\n<\/blockquote>\n<p>\u2014 Page 132, <a href=\"https:\/\/amzn.to\/2lnc3vL\">Deep Learning<\/a>, 2016.<\/p>\n<h2>Further Reading<\/h2>\n<p>This section provides more resources on the topic if you are looking to go deeper.<\/p>\n<h3>Posts<\/h3>\n<ul>\n<li><a href=\"https:\/\/machinelearningmastery.com\/how-to-choose-loss-functions-when-training-deep-learning-neural-networks\/\">How to Choose Loss Functions When Training Deep Learning Neural Networks<\/a><\/li>\n<li><a href=\"https:\/\/machinelearningmastery.com\/loss-and-loss-functions-for-training-deep-learning-neural-networks\/\">Loss and Loss Functions for Training Deep Learning Neural Networks<\/a><\/li>\n<\/ul>\n<h3>Books<\/h3>\n<ul>\n<li><a href=\"https:\/\/amzn.to\/2xKSTCP\">Machine Learning: A Probabilistic Perspective<\/a>, 2012.<\/li>\n<li><a href=\"https:\/\/amzn.to\/2JwHE7I\">Pattern Recognition and Machine Learning<\/a>, 2006.<\/li>\n<li><a href=\"https:\/\/amzn.to\/2lnc3vL\">Deep Learning<\/a>, 2016.<\/li>\n<\/ul>\n<h3>API<\/h3>\n<ul>\n<li><a href=\"https:\/\/keras.io\/losses\/\">Usage of loss functions, Keras API<\/a>.<\/li>\n<li><a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.metrics.log_loss.html\">sklearn.metrics.log_loss API<\/a>.<\/li>\n<\/ul>\n<h3>Articles<\/h3>\n<ul>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Kullback%E2%80%93Leibler_divergence\">Kullback-Leibler divergence, Wikipedia<\/a>.<\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Cross_entropy\">Cross entropy, Wikipedia<\/a>.<\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Joint_entropy\">Joint Entropy, Wikipedia<\/a>.<\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Loss_functions_for_classification\">Loss functions for classification, Wikipedia.<\/a><\/li>\n<\/ul>\n<h2>Summary<\/h2>\n<p>In this tutorial, you discovered cross-entropy for machine learning.<\/p>\n<p>Specifically, you learned:<\/p>\n<ul>\n<li>How to calculate cross-entropy from scratch and using standard machine learning libraries.<\/li>\n<li>Cross-entropy can be used as a loss function when optimizing classification models like logistic regression and artificial neural networks.<\/li>\n<li>Cross-entropy is different from KL divergence but can be calculated using KL divergence, and is different from log loss but calculates the same quantity when used as a loss function.<\/li>\n<\/ul>\n<p>Do you have any questions?<br \/>\nAsk your questions in the comments below and I will do my best to answer.<\/p>\n<p>The post <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/cross-entropy-for-machine-learning\/\">A Gentle Introduction to Cross-Entropy for Machine Learning<\/a> appeared first on <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/\">Machine Learning Mastery<\/a>.<\/p>\n<\/div>\n<p><a href=\"https:\/\/machinelearningmastery.com\/cross-entropy-for-machine-learning\/\">Go to Source<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Author: Jason Brownlee Cross-entropy is commonly used in machine learning as a loss function. Cross-entropy is a measure from the field of information theory, building [&hellip;] <span class=\"read-more-link\"><a class=\"read-more\" href=\"https:\/\/www.aiproblog.com\/index.php\/2019\/10\/20\/a-gentle-introduction-to-cross-entropy-for-machine-learning\/\">Read More<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":2717,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"footnotes":""},"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/2716"}],"collection":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/comments?post=2716"}],"version-history":[{"count":0,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/2716\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media\/2717"}],"wp:attachment":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media?parent=2716"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/categories?post=2716"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/tags?post=2716"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}