<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michael Köpf on Medium]]></title>
        <description><![CDATA[Stories by Michael Köpf on Medium]]></description>
        <link>https://medium.com/@michael.koepf?source=rss-b8da9a0e12d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*vMWKKYsD2I_OVB7mA0jXqQ.jpeg</url>
            <title>Stories by Michael Köpf on Medium</title>
            <link>https://medium.com/@michael.koepf?source=rss-b8da9a0e12d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:29:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michael.koepf/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[We are not evil]]></title>
            <link>https://medium.com/data-science/we-are-not-evil-4c294a1e743e?source=rss-b8da9a0e12d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c294a1e743e</guid>
            <category><![CDATA[ethics]]></category>
            <category><![CDATA[ethical-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Michael Köpf]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 16:35:16 GMT</pubDate>
            <atom:updated>2020-06-19T16:35:16.246Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI and its creators are making the world better, not worse.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcAHiD2rrF8lQDJywaaeaw.png" /><figcaption>We are not evil. (Source: The author)</figcaption></figure><p>AI is driven by a joint worldwide effort of programmers, data scientists, and mathematicians. Overall, this particular global subculture, to which I count myself, is mostly optimistic, believing in progress, and ultimately wanting to improve the world through technology.</p><p>Following the news, you might get a different picture of AI and the people behind it. When the Banjo story broke [1], we learned that major figures throughout AI history have been White supremacists [2]. Since the COMPAS scandal [3] we read about gender and racial bias in just about any major AI system out there. Just a few days ago, IBM, Amazon, and Google desperately pulled the plug on their facial recognition Softwares [4–6], seeing no other way to prevent unfair treatment of minorities. Even worse, statistics, the very mathematical discipline behind all modern Machine Learning and Data Science, has now itself been suspected of being racist, as it has been developed, in large parts, by eugenicists [7, 8].</p><p>Although statistics, like science in general, is certainly full of ethical contamination (to use a term by Ron Howard [9]), it is, by itself, hardly evil. Neither are we, the vast majority of passionate data scientists and Machine Learning engineers from all around the world, who rely on statistics in everything we do.</p><p>No, statistics is not the problem, it is vital to the solution. It is the one necessary tool to reveal discrimination and injustice anywhere.<br>Only by means of systematic data analysis and statistics, can the unfair practices prevalent in today’s companies and institutions be at all revealed. Statistics allows us to quantify injustice and to monitor whether we are making progress reducing it.</p><p>How did ProPublica uncover the COMPAS scandal? By use of statistics and Data Science, <a href="https://www.propublica.org/datastore/dataset/compas-recidivism-risk-score-data-and-analysis">as you can see from their code</a>. How do we know that AI research and development has a diversity problem? By looking at — you guessed it — statistics [10]. How could <a href="https://de.wikipedia.org/wiki/Cathy_O%E2%80%99Neil">Cathy O’Neil</a> write “Weapons of Math Destruction”? By drawing on her knowledge and experience as a mathematician and Data Scientist. She’s one of the many of us who actually care.</p><blockquote>The problem is not the AI that learned your unethical behavior. The problem is that you behaved unethically, in the first place!</blockquote><p>True, incidents such as the COMPAS scandal show that AI makes unethical decisions. But, dear companies and institutions, the problem is not the AI that learned your unethical behavior. The problem is that you behaved unethically, in the first place!</p><p>A lot of work is done, to identify and correct this. Ethical AI has become an active field of research, resulting in new tools, methods, and best practices to achieve data transparency and algorithmic explainability. And yes, the era of explainable AI is going to be uncomfortable for some corporations and institutions because with increased transparency comes additional scrutiny. <br>Ultimately, though, there is no alternative. It will be through the contribution of statistics that inequality is detected, measured, and fought systematically.</p><p>And we, you and I, will be the ones to bring this about.</p><h3>References</h3><p>[1] M. Stroud, <a href="https://onezero.medium.com/ceo-of-surveillance-firm-banjo-once-helped-kkk-leader-shoot-up-synagogue-fdba4ad32829">CEO of Surveillance Firm Banjo Once Helped KKK Leader Shoot Up a Synagogue</a> (2020), OneZero</p><p>[2] S. Myers West, <a href="https://medium.com/@AINowInstitute/ai-and-the-far-right-a-history-we-cant-ignore-f81375c3cc57">AI and the Far Right: A History We Can’t Ignore</a> (2020)</p><p>[3] Julia Angwin et al., <a href="https://www.propublica.org/article/machine-bias-risk-assessments-in-criminal-sentencing">Machine Bias</a> (2016), ProPublica</p><p>[4] L. Hirsch, <a href="https://www.cnbc.com/2020/06/08/ibm-gets-out-of-facial-recognition-business-calls-on-congress-to-advance-policies-tackling-racial-injustice.html">IBM gets out of facial recognition business, calls on Congress to advance policies tackling racial injustice</a> (2020), CNBC</p><p>[5] A. Levy, <a href="https://www.cnbc.com/2020/06/11/microsoft-says-will-not-sell-facial-recognition-software-to-police.html">Microsoft says it won’t sell facial recognition software to police until there’s a national law ‘grounded in human rights’</a>, (2020), CNBC</p><p>[6] K. Weise and N. Singer, <a href="https://www.nytimes.com/2020/06/10/technology/amazon-facial-recognition-backlash.html">Amazon Pauses Police Use of Its Facial Recognition Software</a>, (2020), The New York Times</p><p>[7] K. Evans, <a href="https://medium.com/@mkevinevans/is-statistics-racist-a8f29b188b6e">Is Statistics Racist?</a></p><p>[8] D. Cleather, <a href="https://medium.com/swlh/is-statistics-racist-59cd4ddb5fa9">Is Statistics Racist?</a>, (2020), The Startup</p><p>[9] S. Raha, <a href="https://medium.com/@somikr/ethical-contamination-34dc9e98ad5b">Ethical Contamination</a></p><p>[10] K. Paul, <a href="https://www.theguardian.com/technology/2019/apr/16/artificial-intelligence-lack-diversity-new-york-university-study">‘Disastrous’ lack of diversity in AI industry perpetuates bias, study finds</a> (2019), The Guardian</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTYos5cRlnIp55XC0g0z4Q.png" /><figcaption>(Source: The author)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c294a1e743e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/we-are-not-evil-4c294a1e743e">We are not evil</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ROC vs. TOC]]></title>
            <link>https://medium.com/data-science/roc-vs-toc-bccb7d70ef07?source=rss-b8da9a0e12d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bccb7d70ef07</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[metrics]]></category>
            <dc:creator><![CDATA[Michael Köpf]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 18:04:15 GMT</pubDate>
            <atom:updated>2020-06-15T13:36:48.013Z</atom:updated>
            <content:encoded><![CDATA[<h4>Two ways to visually analyze a binary classifier</h4><figure><img alt="ROC vs. TOC" src="https://cdn-images-1.medium.com/max/924/1*A06ELnZHAyTK_9P9yjvelw.png" /><figcaption>It’s on. (Source: The author)</figcaption></figure><p>Recently, while writing an article on <a href="https://towardsdatascience.com/how-to-operate-an-ai-optimally-is-a-matter-of-perspective-d1d1d28f74ec">how to optimally configure a binary classifier</a> involving, among other factors, ROC analysis, I came across a promising alternative known as TOC analysis. In this post, I will introduce you to the concepts behind both visual tools and discuss their similarities and differences.</p><h3>Motivation</h3><p>When it comes to evaluating the performance of binary predictors, the <em>receiver operating characteristic </em>(ROC) curve has been a staple for decades and actually long predates the Machine Learning era (for an early example from the 1950s, see Peterson et al. [1]). It allows us to evaluate and compare the performance of classifiers and is, therefore, a useful tool for model selection.</p><p>That a classifier can at all be fully characterized by a curve drawn in two-dimensional space, that is, on your monitor or a piece of paper, is based on the fact that the two-by-two confusion matrix has only two degrees of freedom for any given test set. Each point on a ROC curve determines the corresponding confusion matrix if and only if you know your test set’s composition, that is, you know how many positive and negative samples it contains. However, the ROC graph itself does <em>not</em> contain the composition as visual information.</p><p>Given the long history of ROC analysis, this shortcoming has rather recently been addressed by the introduction of the <a href="https://en.wikipedia.org/wiki/Total_operating_characteristic"><em>total operating characteristic</em></a> (TOC) through Pontius and Si in 2014 [2]. A TOC diagram contains the full ROC information and additionally allows you to read off the total information, that is, the test set’s composition and all four entries of the confusion matrix, for each point on the curve.</p><p>Before we see how that works, let us quickly review the basic concepts and notation of binary classification.</p><h3>Binary classification basics</h3><p>In <a href="https://en.wikipedia.org/wiki/Binary_classification">binary classification</a>, model performance is commonly evaluated by comparing its predictions for data points from the test set to the known correct results, that is, to the labels of your test set. The prediction for each data point falls into either of four categories: true positive (TP), true negative (TN), false positive (TP), or false negatives (FN) and the number of samples in each category is represented in the <a href="https://en.wikipedia.org/wiki/Confusion_matrix"><em>confusion matrix</em></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*qdKAbIPP-XBM_I8wBRGQkw@2x.png" /></figure><p>Although the confusion matrix has 4 components, only two are actually independent. This is because each actual test set has a certain fixed number P of samples that are actually positive and a certain number N of samples that are actually negative. Therefore, irrespective of a particular classifier’s performance, in the end, we always have TP + FN = P and TN + FP = N.<br>That makes two equations with four unknowns and leaves us with two degrees of freedom. A common way (but not the only one) to parameterize these degrees of freedom is by means of the <em>true positive rate</em> (TPR) and the <em>false positive rate</em> (FPR). Mathematically, they are defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*U9n3pEAFvqDf_cFXy23qNg@2x.png" /></figure><p>Starting from these definitions, you can easily convince yourself with very little algebra that TPR and FPR are enough to determine all four TP, FP, FN, and TN, by noting that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*a4TxcgQW-iG7tpoOCcdF9g@2x.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*A4t0iswwO-3v7uPHrbDFOw@2x.png" /></figure><p>In many cases, classifiers are based on probabilistic classification. This means they compute probabilities for each class from the features of a data point x. In the case of binary classification, these are the two probabilities p(1|x) and p(0|x). Since the sample has to be in either of the two classes, that is, p(1|x)+p(0|x)=1, it suffices to look at one of the two probabilities, say, p(1|x). To obtain a binary prediction, a discrimination threshold is used to discretize the continuous probability p(1|x) into either of the two classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*twwsC-r8wUx74XifvKj4fw@2x.png" /></figure><p>Thus, TPR and FPR, and with them, all four numbers in the confusion matrix depend on the threshold value. This dependence is what both, ROC and TOC graphs, are designed to visualize.</p><h3>ROC and TOC graphs</h3><p>Both, ROC and TOC graphs are tools to visualize classifier performance for all possible threshold choices in a single graph. However, they are based on two different coordinate systems.</p><p>A ROC curve is plotted into an FPR-TPR coordinate system, that is, you plot (FPR(threshold), TPR(threshold)) for all threshold values between 0% and 100%. A TOC graph, on the other hand, is plotted into a (TP+FP)-TP coordinate system, that is, you plot the points (TP(threshold) + FP(threshold), TP(threshold)) for each threshold value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*v5o4S8YaSSj6Jjiw1OKeRQ.png" /><figcaption><strong>Figure 1:</strong> The ROC curves of two classifiers (blue and green lines) and the curve representing uninformed (random) classifiers (orange dots).</figcaption></figure><p>The TOC graph’s main appeal is that you can read off the complete confusion matrix for every point in TOC space. This is achieved by not only plotting the curve, but also a surrounding parallelogram-shaped box with the corners (0, 0), (N, 0), (N+P, P), (P, P).</p><p>We will discuss the nature of this parallelogram in more detail, below, but for now, we note that the distance from any point on the TOC curve to the box’s left boundary corresponds to FP, the distance to the right boundary to TN, the distance to the top to FN and the distance to the bottom to TP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVlhdT4UTLg6qpdsmLO7nA.png" /><figcaption><strong>Figure 2:</strong> For every point on a TOC curve, you can read off all four components, TP, FP, FN, and TN, of the confusion matrix, while having all information from a ROC graph available, as well. (Source: The author)</figcaption></figure><p>Unlike a ROC graph that does not allow to reconstruct the confusion matrix without knowledge of P and N, which are not contained in the graph itself, a TOC graph contains the confusion matrix <em>for every given threshold choice</em>. Furthermore, you can easily read of the test set’s size and composition, revealing, for example, skewness in your data that would remain “hidden” in a ROC graph.</p><h3>ROC space vs. TOC space</h3><p>The ROC curve is bound to a square region known as <em>ROC space</em>, whose points correspond to all possible values of TPR and FPR between 0 and 1 [3].<br>This square is cut in half by the diagonal from TPR=FPR=0 to TPR=FPR=1.<br>The points on this diagonal represent so-called <em>uninformed</em> classifiers.<br>Such a classifier simply categorizes data points at random, completely disregarding its actual feature values. An uninformed classifier at TPR=FPR=0.7, for example, would classify 7 out of 10 data points as positive and 3 out of 10 as negative.</p><p>The extreme ends of this diagonal are home to two very special deciders.<br>In the lower-left, at TPR=FPR=0, we have a classifier that simply categorizes every single data point as negative. The classifier across, in the upper-right corner of ROC space, categorizes every single data point as positive.</p><p>The other two corners of the ROC space are equally interesting. In the upper-left, we have the perfect classifier. It assigns the correct category to every single data point of the test set, corresponding to a diagonal confusion matrix with TP=P, TN=N, and FP=FN=0, that is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*4HBuEuL8An4976gxGmCStg@2x.png" /></figure><p>You could render the perfect classifier perfectly imperfect by flipping each of its responses. This worst possible classifier assigns the wrong category to each data point, resulting in the confusion matrix TP=TN=0, FP=N, and FN=P, that is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*KbqkUxzWfMzFQDSKGR_Mfg@2x.png" /></figure><p>In ROC space, this corresponds to the lower-right corner, TPR=0, FPR=1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DPcKuRH2CqhYlM1LQZZP5A.png" /><figcaption><strong>Figure 3:</strong> A ROC curve (blue) in comparison to the performance of uninformed (random) classifiers (orange diagonal). The four extreme corners of ROC space are: (1) the perfect classifier, (2) the all-positive classifier, (3) the worst possible classifier, and (4) the all-negative classifier. (Source: The author)</figcaption></figure><p>TOC space differs from ROC space in two fundamental ways. First, it is not a square but a parallelogram, and, second, its shape depends on the test set’s composition. This is a direct consequence of the choice of axes because unlike the rates TPR and FPR, the absolute numbers TP and FP are not contained to the range from 0 to 1. To understand the parallelogram, choose any fixed value of TP. Your choice is then automatically a lower bound of TP+FP, the TOC graph’s abscissa (aka x-axis), since FP is a count and thus never negative. The upper bound of TP+FP is determined by your choice, as well. It is TP+N, as FP cannot be greater than N. These lower and upper bounds of TP+FP form the inclined left and right boundaries of the parallelogram. TP itself is also a count and limited to the range from 0 to P, determining the lower and upper boundaries of the parallelogram, respectively. Consequently, the whole TOC space can be embedded in an N+P by P rectangle.</p><p>Despite all differences, TOC space is just a (non-uniformly) <a href="https://en.wikipedia.org/wiki/Scaling_(geometry)">scaled</a> and <a href="https://en.wikipedia.org/wiki/Shearing_(physics)">sheared</a> version of ROC space. Any point in ROC space can be mapped to TOC space using the linear transformation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*dYiA6msLeawamwvdDk69RQ@2x.png" /></figure><p>This transformation is a composition of scaling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*-Klwrlt-7HS7kQvNfMrlgA@2x.png" /></figure><p>and shearing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*hjNsCLcHdkcTaeVJyYKNSg@2x.png" /></figure><p>Therefore, we can go from ROC space to TOC space by use of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*u7DcBgG9NBihNfNiyvCelQ@2x.png" /></figure><p>Due to the simple nature of this transformation, the essential geometric structure of ROC space is carried over to TOC space. Thus, just like ROC space, TOC space is also halved by the diagonal representing uninformed classifiers. The corners of TOC space preserve their meaning from ROC space, as well: perfect classifier in the upper left, worst possible classifier in the lower right, all-positive classifier in the top right, and all-negative classifier in the lower left (see Figure 4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVaUbdZU23JTzQEkeRv2xA.png" /><figcaption><strong>Figure 4:</strong> The four extreme corners of TOC space are (1) the perfect classifier, (2) the all-positive classifier, (3) the worst possible classifier, and (4) the all negative classifier. At point (5), the prevalence (number of positives) is estimated correctly. Left of (5) (gray area) TP+FP&lt;P, so that the prevalence is underestimated, right of (5) TP+FP&gt;FP, so that the prevalence is overestimated. (Source: The author)</figcaption></figure><p>Other derived properties stay intact under the transformation, as well. Let’s consider, for example, the area under the ROC curve (AUROCC), a typical metric to describe the ROC curve as a whole using a single number. The area under the TOC curve (AUTOCC) is directly proportional to the area under the ROC curve (AUROCC) and can be interpreted the same way. We have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*Kbn3ckBA13LTwVeF51XYig@2x.png" /></figure><p>so that the fraction of ROC space (the 1-by-1 square) under the ROC curve is the same as the fraction of TOC space (the N-by-P parallelogram) under the TOC curve.</p><p>There is a lengthy proof of this relation in the original publication of Pontius and Si [2] but I find it more straightforward to consider that only<br>ϕₛcₐₗₑ affects the area (ϕₛₕₑₐᵣ is area-preserving) and its <a href="https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant">Jacobian</a> is N⋅P, so that it is evident that AUROCC is enlarged accordingly, under the transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJqRZgMt98mZc0qHJxWDsg.png" /><figcaption><strong>Figure 5:</strong> The fraction of the parallelogram under the TOC curve (blue area) compared to the whole parallelogram’s area (blue+orange part) equals the area under the ROC curve. Compare the colored areas in the ROC graph shown in Figure 3. (Source: The author)</figcaption></figure><p>There is one noteworthy point in TOC space that cannot be identified in ROC space. It is the point (P, TP), shown as point (5) in Figure 4. It is the point on the curve directly under the upper end of the left boundary of the parallelogram. A classifier operating at this point produces precisely the same ratio of positive to negative predictions as there are positive and negative samples in the test set. Such a classifier can be said to correctly represent the actual <a href="https://en.wikipedia.org/wiki/Prevalence">prevalence</a>. All classifiers left of this point are underestimating the ratio of positives while all classifiers to its right are overestimating it.</p><h3>The shape of TOC space</h3><p>While ROC space remains geometrically static under variation of test set composition, TOC space changes strongly. Pontius and Si propose “to enhance visual clarity” by rescaling the graph so that on paper (or your monitor), both, the TP axis and the TP+FP axis have the same length [2].<br>However, it helps to understand the concept of TOC space to draw the TP and TP+FP-axes with the same scale and watch how TOC space unfolds and collapses with changing test set composition.</p><p>For any non-empty test set, there are five possible situations:</p><p>1. 0=N&lt;P<br>2. 0&lt;N&lt;P<br>3. 0&lt;P=N<br>4. 0&lt;P&lt;N<br>5. 0=P&lt;N</p><p>For illustration, let us consider a toy classifier trained on the “Adult” data set [4] and compile a master test set with equally many positive and negative samples. We can then create all five possible situations by controlled subsetting of this set. In particular, we start at N=0, P=1552 (situation 1), increase N (situation 2) until we reach N=P=1552 (situation 3). From there, we decrease P (situation 4) until we eventually reach P=0, N=1552 (situation 5). Figure 6 illustrates how TOC space changes its shape due to these changes in test set composition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sIyRnFPsRugLaHfm-99JdQ.gif" /><figcaption><strong>Figure 6: </strong>Animation showing the shape of TOC space for various test set compositions. Note the collapse from two to one dimension in the two extreme cases N=0 and P=0. (Source: The author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*_F96h5Hd47pluDO9Brwtwg.png" /><figcaption><strong>Figure 7: </strong>For 0=N&lt;P (Situation 1), TOC space is one-dimensional. It corresponds to the diagonal from (0, 0) to (P, P). (Source: The author)</figcaption></figure><p>Let us discuss situations 1 through 5 in more detail.</p><p>For N=0 &lt; P, TOC space is one-dimensional! Its left and right boundaries collapse into a single diagonal line from (0, 0) to (P, P) (see Figure 7).</p><p>Although this might seem strange at first glance, it is sensible, since in absence of negatives, the performance of a classifier is in fact one-dimensional, completely determined by a single parameter, its TPR.</p><p>Going away from this extreme situation, we increase the number of negatives in the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMtlUaLoihYq-ns9bfVlGQ.png" /><figcaption><strong>Figure 8</strong>: For 0&lt;N&lt;P (Situation 2), TOC space is a rather narrow diagonal strip. (Source: The author)</figcaption></figure><p>The diagonal separates into a left and right boundary, opening up a finite area, the “normal” two-dimensional TOC space.</p><p>However, TOC space retains the shape of a rather narrow diagonal strip, because its right boundary starts at TP+FP=N, far to the left of TP+FP=P, where its left boundary ends (see Figure 8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNeTcmcIUnBBUiQyEC4GaA.png" /><figcaption><strong>Figure 9:</strong> For 0&lt;N=P the left boundary ends directly above the starting point of the right boundary. (Source: The author)</figcaption></figure><p>Increasing the proportion of negatives further, we then approach the situation where P=N, that is, negatives and positives are perfectly balanced in the test set.</p><p>Now, the right TOC space boundary starts directly underneath the endpoint of its left boundary (see Figure 9).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-moXCczP_lgDHPi_qUhXw.png" /><figcaption><strong>Figure 10: </strong>For 0&lt;P&lt;N, TOC space is rather broad. (Source: The author)</figcaption></figure><p>When we increase the number of negatives beyond this point, we come to a situation where the left and right boundary diagonals are no longer above each other and there is a rectangular area between (P, 0), (N, 0), (N, P), and (P, P).</p><p>Consequently, TOC space now appears rather broad (see Figure 10).</p><p>Eventually, we approach another extreme: The whole test set is filled exclusively with negatives. Again, two boundaries of TOC space collapse two a single line.</p><p>This time, it’s the upper and lower boundaries, so that TOC space becomes a horizontal line segment reaching from 0 to N (see Figure 11).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*NGuujRTfyA0J5LfHNQSLlQ.png" /><figcaption><strong>Figure 11: </strong>A 0=P&lt;N, TOC space is a one-dimensional line segment from 0 to N. (Source: The author)</figcaption></figure><p>Again, this collapse is sensible, as a classifier’s result is now purely made up of TN and FP and its performance is completely defined by a single parameter, its FPR.</p><p>We conclude our round-trip through TOC space by noting that for the (practically irrelevant but pathologically interesting) case of a completely empty test set with N=P=0, TOC space would collapse even further, becoming a single point.</p><h3>Discussion</h3><p>The TOC graph is a useful addition to the statistician’s toolbox. Readers used to ROC analysis can learn to interpret a TOC diagram quickly because both representations share many properties.</p><p>A TOC curve contains strictly more information than its ROC counterpart. However, the information sparseness of a ROC graph can also be seen as advantageous. As Fawcett puts it in his <em>Introduction to ROC analysis</em> [3]: “<em>One advantage of ROC graphs is that they enable visualizing and organizing classifier performance without regards to class distributions or error costs. This ability becomes very important when investigating learning with skewed distributions or cost-sensitive learning. A researcher can graph the performance of a set of classifiers, and that graph will remain invariant with respect to the operating conditions (class skew and error costs). As these conditions change, the region of interest may change, but the graph itself will not.</em>”</p><p>Therefore, ROC curves will remain relevant for certain purposes where TOC is not a suitable substitute.</p><p>When it comes to library support, the ROC curve has a clear advantage. While there are ready-to-use library functions for ROC analysis in any major Machine Learning or statistics library, the support for TOC is still rather limited, due to the relatively short time since its inception. There is a <a href="https://cran.r-project.org/web/packages/TOC/">TOC R package</a> curated by the authors of the original TOC publication. However, if you are willing to go the extra mile, a function to plot TOC diagrams from probabilities is quickly implemented in your favorite programming language.</p><p>Finally, one has to consider, that graphs are, in the end, a means of communication. In the statistics and Machine Learning communities, ROC analysis is a well-known standard, and ROC graphs are directly understood. In contrast, TOC analysis is still relatively young and might still perplex part of your audience. If you have a 10-minute time slot at an important conference, you would not want to spend 5 minutes explaining an unusual diagram type (TOC), in particular when there is an alternative (ROC) that your audience will get right away.</p><p>Although TOC analysis is still far away from being widely adopted, I hope this post convinced you that it is a tool worthwhile to try out when analyzing a classifier’s performance.</p><h3>References</h3><p>[1] W. Peterson, T. Birdsall, and W. Fox, The Theory of Signal Detectability (1954), Transactions of the IRE Professional Group on Information Theory, <strong>4 </strong>(4), pages 171–212.</p><p>[2] R. G. Pontius Jr and K. Si, <a href="http://dx.doi.org/10.1080/13658816.2013.862623">The total operating characteristic to measure diagnostic ability for multiple thresholds</a> (2014), International Journal of Geographical Information Science <strong>28</strong> (3), pages 570–583</p><p>[3] T. Fawcett, <a href="https://doi.org/10.1016/j.patrec.2005.10.010">An introduction to ROC analysis</a> (2006), Pattern Recognition Letters <strong>27</strong>, pages 861–874</p><p>[4] <a href="http://archive.ics.uci.edu/ml/datasets/Adult">Adult dataset</a> (1996), provided through Dua, D. and Graff, C. (2019), <a href="http://archive.ics.uci.edu/ml">UCI Machine Learning Repository</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bccb7d70ef07" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/roc-vs-toc-bccb7d70ef07">ROC vs. TOC</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to operate an AI optimally is a matter of perspective]]></title>
            <link>https://medium.com/data-science/how-to-operate-an-ai-optimally-is-a-matter-of-perspective-d1d1d28f74ec?source=rss-b8da9a0e12d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1d1d28f74ec</guid>
            <category><![CDATA[insurtech]]></category>
            <category><![CDATA[change-management]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[operations]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Michael Köpf]]></dc:creator>
            <pubDate>Sat, 06 Jun 2020 11:44:00 GMT</pubDate>
            <atom:updated>2020-06-11T11:46:42.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*La4AYChIuF5uehW5vShtUQ.jpeg" /><figcaption><em>Not every question can be answered by mathematics and algorithms. When it comes to operationalizing AI, perspective matters, and each stakeholder measures success differently. Then it is time for leadership to step up and C-level decisions are required. (Source: Shutterstock)</em></figcaption></figure><p>When you bring AI to businesses, math is the simple part. It is simple because it is objectively decidable using universally accepted standards. But a lot of important decisions do not fall into this category. When such decisions are about to be made, the debate is on: A dozen stakeholders bring as many opinions to the table, each backed by sensible arguments. To prevent unproductive chaos, this is the time when leadership has to step up and, sooner or later, these issues inevitably become C-level decisions.</p><p>For an AI project to become a success, mathematics, economics, strategy, and psychology all have to be taken into account. To illustrate how this can play out, we will in this post look at Machine Learning applications in the German car insurance sector.</p><p>Think of a Machine Learning system trained to validate car insurance claims. How car insurance works differs from country to country. In Germany, a claim is typically accompanied by a damage assessment from a certified expert, or a quotation or invoice from a repair shop. Based on these documents, the Machine Learning system classifies the claim into one of two categories: Either it recommends direct payout or, if the invoice seems to be in part or completely unjustified, technically incorrect, or problematic in any other way, it routes the case to a human subject-matter expert for further investigation.</p><p>As AXA and Controlexpert, to heavy-weights in the German car insurance business, report in a joint statement, the ratio of perfectly legitimate claims is about 40% [1]. Therefore, an AI that enables human experts to focus on the remaining 60% of <em>relevant</em> cases, promises a lot of saved time and money. To fully realize this benefit the system has to be configured to serve the user’s needs best.</p><p>And that’s where the problems start. What is best for the user?</p><p>One might be tempted to think that, surely, in the highly mathematical and quantitative world of Machine Learning, there must be this single magic metric that can be used to find the optimal configuration. There is not.</p><p>But before we see why, let us first start simple and see what <em>can</em> be objectively said.</p><h3>How to quantify classifier performance</h3><p>Of course, there <em>are</em> objective ways to evaluate the performance of Machine Learning models. In fact, a system such as our claims classifier is a particularly simple case, a so-called binary classifier. Binary, because it answers either-or-questions with two possible outcomes: yes or no, zero or one, thumps-up or thumps-down. Or, in our concrete scenario: Does the insurance claim look fishy or not?</p><p>A classifier is trained using historic case data. To evaluate its performance on new, <em>unknown</em> cases, you hold out a part of said data and do not use it for training. Instead, once the model is trained, you use it to test the model. From the model’s perspective this data is as unknown as completely new data would be, but you, the tester, know how each sample has been decided in the past by a human expert, so you know how it <em>should</em> be classified.</p><p>With this knowledge, you can group the classifier’s test set results into four categories.</p><p>1. If the classifier recommends the claim for further investigation and according to the record, the claim was indeed objectionable, then you have a <strong>true positive (TP)</strong>.<br> 2. If the classifier recommends the claim for direct payout, and according to the record the claim was fine, you have a <strong>true negative (TN)</strong>.<br> 3. If the classifier recommends investigation but the record shows the claim was fine, then this is a <strong>false positive (FP)</strong>.<br> 4. If the classifier recommends direct payout but the record shows the claim was objectionable, then this is a <strong>false negative (FN)</strong>.</p><p>The numbers in the four categories are commonly represented in the form of a two-by-two matrix, the so-called <a href="https://en.wikipedia.org/wiki/Confusion_matrix"><em>confusion matrix</em></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*qdKAbIPP-XBM_I8wBRGQkw@2x.png" /></figure><p>Although the confusion matrix consists of four numbers, TP, FP, FN, and TN, only two of them are actually independent. This is because the data itself, or more specifically the test set, has a certain number P of samples that are actually positive and a certain number N of samples that are actually negative. Therefore, no matter how well the classifier works, in the end, we always have TP + FN = P and TN + FP = N. Two equations with four unknowns leave us with two degrees of freedom. A common way (but not the only one) to parameterize these degrees of freedom is by means of the <strong>true positive rate (TPR)</strong> and the <strong>false positive rate (FPR)</strong>.</p><p>Mathematically, they are defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*U9n3pEAFvqDf_cFXy23qNg@2x.png" /></figure><p>Starting from these definitions, you can easily convince yourself with very little algebra that TPR and FPR are enough to determine all four TP, FP, FN, and TN, by noting that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*a4TxcgQW-iG7tpoOCcdF9g@2x.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*A4t0iswwO-3v7uPHrbDFOw@2x.png" /></figure><p>In reality, though, a case is hardly ever 100% clear. Instead, decisions are made with more or less confidence, depending on the evidence — but also on the personal inclination (read: bias) of the individual decision-maker.</p><p>Imagine that our classification task would have to be done by a human expert rather than an AI. Further, imagine there were two candidates for the job. On the one hand, there is the ultra-skeptical subject-matter expert. For her, no claim is above suspicion. Case details notwithstanding, she simply flags every single claim for further investigation. Interestingly, without even considering the evidence for one second, she is certain to get a definite proportion of cases right: She correctly recommends investigation of every single unjustified claim. At the same time, though, she wrongly recommends every single correct claim for closer examination, as well.</p><p>The second candidate is her exact opposite. His trust in the claimants knows no limit. Therefore, he recommends every single claim for direct payout. This expert also has <em>some</em> success to show, as he treats every justified claim correctly — but every unjustified claim wrongly.</p><p>Between the two extreme positions represented by these fictitious characters, one can imagine a full spectrum of more or less strict decision-makers. To represent this spectrum, we can introduce a „strictness parameter” p, more formally known as the <em>discrimination threshold</em>, whose value can be chosen between 0% and 100%. If, given the case data, a claim is fishy with probability 70%, then an expert with strictness p would recommend further investigation if <em>p</em>&lt;70% and direct payout if p&gt;=70%.</p><p>This is exactly how our classifier works internally. It computes a probability and translates it into a binary decision according to a configuration parameter p, the discrimination threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*v5o4S8YaSSj6Jjiw1OKeRQ.png" /><figcaption><strong>Figure 1.</strong> The classifier represented by the blue curve is superior to the classifier represented by the green curve. (Source: The author)</figcaption></figure><p>Thus, TPR and FPR, and with them, all four numbers in the confusion matrix depend on the threshold value. How TPR and FPR vary with changing threshold can be understood by looking at a <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic">ROC curve</a> [2]. You obtain this curve by plotting the points (FPR(p), TPR(p)) for all values of p between 0% and 100% into an FPR-TPR coordinate system.</p><p>The ROC curve can be used to compare two classifiers. In general, a classifier is better than another, if its TPR is greater than the other’s for every FPR. In the ROC graph, the superior classifier’s ROC curve is everywhere <em>above</em> the other classifier’s ROC curve (see Figure 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*JRuKpbAG1542Fpl7B0Qwcg.png" /><figcaption><strong>Figure 2.</strong> Two (or more) models can be combined to a single ROC curve corresponding to their individual ROC curves’ convex hull. (Source: The author)</figcaption></figure><p>So you can systematically compare various models until you found the one with the best ROC curve. It might turn out that the best curve does not come from a single classifier but from the combination of two or several different classifiers. What matters is that in the end, you will always have a single best ROC curve. (In the case of a classifier combination, this curve is the upper convex hull of the ROC curves of each individual classifier [3], see Figure 2.)</p><p>At this point, we are still in a simple world. You can objectively select the model whose ROC curve beats the competition and you are sure you brought the best player to the field.</p><p>Unfortunately, having selected the best classifier, you are far from done. You still have to choose the best <em>point</em> on the curve. The question then is: Which threshold serves the user best?</p><h3>The accuracy optimum</h3><p>(In the remainder of this post, we will show a ROC curve and other characteristics of a trained binary classification model. The model is to be understood as an illustration, only — it is <em>not</em> trained on actual insurance data but on the „Adult” dataset [4].)</p><p>At first glance, finding the best threshold value seems to be a trivial task. Just go for maximum accuracy, the point where as many predictions as possible are correct. Every other choice leads to more errors. Surely, we want to avoid that, right?</p><p>Accuracy is formally defined as the ratio of correct predictions among all predictions, that is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*_gryya7SSRWRxchIZs3e8g@2x.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*B2r9V4aPpdEq5CWueGkCYA.png" /><figcaption><strong>Figure 3.</strong> In our example, the best possible accuracy is 85%. (Source: The author)</figcaption></figure><p>When we calculate ACC for each point on the ROC curve of our example, we find a maximum accuracy of 85% (see Figures 3 and 4). Is that the best we can do?</p><p>It <em>could</em> be, but only in one particular case, that is, when both kinds of errors, false positives and false negatives, were equally painful from the user’s business perspective. In most cases, though, both errors have a significantly different impact, and, as we will see, our car insurance claims example is no exemption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*6imjUicXzcP4EY9X.gif" /><figcaption><strong>Figure 4. </strong>Accuracy, cost, and full confusion matrix along our example’s ROC curve. CST has been rescaled for enhanced visualization, so that the maximum possible cost is 1. (Source: The author)</figcaption></figure><h3>The cost optimum</h3><p>The damage resulting from wrong decisions is not always easy to quantify. Weighing false positives and false negatives against each other is a classical dilemma: Is condemning an innocent person to prison (false positive) worse than letting a murderer walk free (false negative)? By how much?</p><p>Fortunately, in the business world, things are not quite as dramatic and with some effort, the damage due to wrong decisions can be quantified in terms of money. This leads us to cost estimation. To assign price tags to the two possible errors, false positive and false negative, we have to examine, what exactly happens in case of each error.</p><p>In case of a false positive, a completely correct bill is unnecessarily sent to an expert, who then spends some of his valuable time trying to find an error where there is none. To simplify the calculation, let’s say this process takes him 12 minutes and the all-in costs of his labor are 100 € per hour. Then, each false positive wastes 20 €.</p><p>In case of a false negative, an invoice with unjustified items is paid out. That means, the insurer unnecessarily loses the corresponding monetary value of said items. The average value of unjustified claims can be calculated from the historic case data, that has been checked and corrected by human subject-matter experts. Let’s assume, it was 100 € per case.</p><p>Of course, this is an oversimplified representation of cost estimation, but it suffices to get the idea: In the end, you will have a definite monetary value of each error type. In our case it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*y4j5xT4CT-DZRXW4VRK-cQ@2x.png" /></figure><p>or, equivalently, in terms of TPR and FPR:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*lS2wZVdV8duNdYGUL_H7_g@2x.png" /></figure><p>Since FP and FN (or, equivalently, TPR and FPR) depend on the value of our threshold parameter p, we can plot the cost as a function of p, that is, CST(p). It is instructive, to plot cost and accuracy in the same diagram. To this end, we show cost not as an absolute value but as a percentage of the maximum possible cost (see Figure 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*fxmGOBGZME1DZjzs.gif" /><figcaption><strong>Figure 5.</strong> Accuracy and cost plotted against the discrimination threshold. For reference, the full confusion matrix is shown in the lower right. (Source: The author)</figcaption></figure><p>The operating point with optimal cost can also be determined geometrically from the ROC curve. From the above equation linking CST to TPR and FPR, we note that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*JFgF9Xtlcukly-g6fI2VGA@2x.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*LclbilOi-TNtDKwLsj8fEQ.png" /><figcaption><strong>Figure 6. </strong>Our example’s ROC curve (blue) with several iso-performance lines (yellow), each corresponding to a constant cost. Cost increases vertically to the iso-performance lines, from upper left to lower right. (Source: The author)</figcaption></figure><p>This means that points of equal cost are arranged on straight lines with slope 0.2⋅(N/P). These lines are known as <em>iso-performance lines </em>[3]. The cost increases with the error rate, that is, in the direction of the lower-right corner of the ROC diagram. Accordingly, the point of lowest cost is found where the ROC curve is tangent to the uppermost iso-performance line (see Figure 6).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*bAXGuB43mqBZotFcpwGXiw.png" /><figcaption><strong>Figure 7.</strong> The cost difference between the accuracy optimum and the cost optimum can lead to significant waste. (Source: The author)</figcaption></figure><p>We find the optimal cost of 29% at an accuracy level of 76%. In contrast, the cost at maximum accuracy 85% level is 40%. Thus, an increase in accuracy by 9 percentage points increases the cost per case by 11 percentage points (see Figure 7). Operating the system at the significantly higher optimal accuracy effectively <em>destroys</em> your client’s money!</p><p>Accuracy (and alternative scores such as F1 or Matthews correlation coefficient) have no value by themselves. Only when linked to actual costs, based on a thorough cost estimation, these metrics become meaningful.</p><h3>The strategic decision</h3><p>Now that the threshold value corresponding to the cost optimum has been found, should you configure the AI, accordingly? That depends on how such a configuration fits in with the user’s broader strategy. Consider, for example, the different viewpoints of two companies operating in the insurance business.</p><p>The first company is a classical insurer. Their potential benefit from the AI is increased cost-efficiency of the claims validation process. The second company is a service, providing subject-matter expertise <em>to</em> insurers.</p><p>Many German insurers have outsourced their expertise for various damage types to specialized companies such as CarExpert, ControlExpert, Dekra, Eucon, and others [5], paying them to identify unjustified claims. At first glance, it appears that an expert company could also simply apply the AI to maximize cost efficiency. However, they are bound to an additional constraint: Their clients do not care about unnecessary work on the expertise provider’s end (resulting from false positives), but they care <em>a lot</em> about lost money due to unjustified claims going undetected (resulting from false negatives). In terms of the metrics defined above, the insurer measures the provider’s service quality in terms of the TPR and is not willing to accept anything but a very high value. As we have seen above, the cost optimum’s TPR is somewhere around 90%. From the insurer’s viewpoint, that value is unacceptable, as it would imply that 10% of the unjustified claims went unnoticed.</p><p>Therefore, instead of simply operating at the cost optimum, the provider has to strike a balance between cost efficiency and delivering a sufficiently high TPR. This leaves them with two basic choices. They can prioritize the reduction of their operations cost and, at the same time, reduce the price of their services to stay attractive on the market despite lower TPR. Or they can deliberately prioritize product quality over price, for example, to maintain the reputation of a high-quality service and aim for long-term customer satisfaction. If they go for the latter choice, the Machine Learning solution has to be operated at a very high TPR (see Figure 8). This way, the provider can benefit from a moderate automation rate while maintaining a very low error rate, close to human-level performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gKH3X2FR-LiHaWxkyI2zcQ.png" /><figcaption><strong>Figure 8.</strong> Prioritizing TPR reduces false negatives but costs both, money and accuracy. (Source: The author)</figcaption></figure><p>On the downside, operating at high TPR leads to an increased cost per case and a reduced accuracy, in comparison to operating at the cost optimum. Practically all of this accuracy loss can be attributed to false positives, following the logic that more work for the human experts is acceptable, as long as most of the unjustified claims are found.</p><p>It is not possible to mathematically prove which choice is the right one. How to position yourself in the market is a decision beyond any formula. And the difficulties do not stop here. There is a long list of other factors to be taken into account, such as company strategy, compliance and regulatory issues, political and ethical considerations, and many more. What all these points have in common is that they are hard — if at all — to quantify. These difficulties cannot be resolved by mathematics alone and it takes strong and smart leadership to find the right way in this complex situation. This is the moment where experienced executives (and consultants at their side) can shine.</p><h3>Conclusion</h3><p>Reality is not as clear cut as a Kaggle competition and an AI’s performance in real-world applications cannot simply be auto-scored. Success along the strategic and human dimensions of the problem is beyond formulas. In this sense, AI is no different from any other major change in business operations. Implementing AI in real-world settings is a process involving a multitude of stakeholders who evaluate the success or failure of a solution based on very different metrics that often cannot be mathematically formalized. Indirect costs, resulting, for example, from dissatisfied employees or customers, can show up with months or years of delay, making the associated risks hard to quantify. For these reasons, technical performance metrics will often play an important but ultimately secondary role in the change management process.</p><h3>References</h3><p>[1] <a href="https://www.controlexpert.com/fileadmin/pdf/de-de/CE_Profile_2019_Teampower_DE.pdf">TEAM POWER, C€-Profile 2019</a>, p. 21, retrieved May 30, 2020</p><p>[2] T. Fawcett, <a href="https://doi.org/10.1016/j.patrec.2005.10.010">An introduction to ROC analysis</a> (2006), <em>Pattern Recognition Letters</em>, <strong>27</strong>, pages 861–874</p><p>[3] F. Provost and T. Fawcett, <a href="https://link.springer.com/article/10.1023/A:1007601015854">Robust Classification for Imprecise Environments</a> (2001), <em>Machine Learning</em>, <strong>42</strong>, pages 203–231 (also available on <a href="https://arxiv.org/abs/cs/0009007">arχiv</a>)</p><p>[4] <a href="http://archive.ics.uci.edu/ml/datasets/Adult">Adult dataset</a> (1996), provided through Dua, D. and Graff, C. (2019), <a href="http://archive.ics.uci.edu/ml">UCI Machine Learning Repository</a></p><p>[5] K. Braunwarth, <a href="https://opus.bibliothek.uni-augsburg.de/opus4/frontdoor/deliver/index/docId/1563/file/Dissertation_Braunwarth.pdf">Wertorientiertes Prozessmanagement von Dienstleistungsprozessen</a> (2009), Doctoral thesis, section II.B1–8</p><p><em>Originally published at </em><a href="https://consilica.de/blog/"><em>https://consilica.de</em></a><em> on June 6, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1d1d28f74ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-operate-an-ai-optimally-is-a-matter-of-perspective-d1d1d28f74ec">How to operate an AI optimally is a matter of perspective</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High-School Math for Machines: Differentiable Code]]></title>
            <link>https://medium.com/data-science/high-school-math-for-machines-differentiable-code-5f588140b148?source=rss-b8da9a0e12d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f588140b148</guid>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[automatic-differentiation]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Michael Köpf]]></dc:creator>
            <pubDate>Mon, 11 May 2020 13:54:26 GMT</pubDate>
            <atom:updated>2020-06-11T13:01:39.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>High-School Math for Machines: Differentiable Programming</h3><figure><img alt="Differentiable code symbolized by a huge gradient symbol (∇) framing a computer brain." src="https://cdn-images-1.medium.com/max/1024/1*MJQznxv0ciLmk3Ezgtyrpw.png" /><figcaption>The symbol of sub-symbolic AI: The gradient (∇) stands for derivatives with respect to all parameters of a Machine Learning system and is central to gradient descent algorithms. (Source: half-brain from <a href="https://pixabay.com/de/illustrations/k%C3%BCnstliche-intelligenz-ai-roboter-2228610/">Seanbatty (Pixabay)</a>, modified and framed by the Author)</figcaption></figure><p>Differentiable programming makes the Machine Learning world go round. PyTorch, TensorFlow, and any other modern Machine Learning framework all rely on it when it comes to the actual learning. Reason enough for anybody even remotely interested in AI to be acquainted with differentiable programming. We invite you to follow us through a two-part explanation of the conceptual framework that powers a large part of today’s AI industry. No Ph.D. required!</p><p>Differentiable programming is vital to Machine Learning because it is the basis of gradient descent, a family of optimization algorithms doing the grunt work in the training of Machine Learning models. The adjective <em>differentiable</em> comes from the noun <em>differentiation, </em>the mathematical process of computing derivatives. Yes, the good old derivatives from your high-school calculus class. Indeed, you get amazingly far with high-school math, when it comes to AI. For example, as we will see below, the <em>gradient</em> in the name <em>gradient descent</em> is essentially a collection of derivatives.</p><p>To train even a moderately sized deep neuronal network (DNN) using gradient descent, you have to compute <em>a lot</em> of derivatives. That’s why training efficiency depends on the ability to efficiently differentiate. Enters <em>automatic</em> differentiation (AD). AD is how computers calculate derivatives. AD, and in particular its so-called reverse-mode (aka backpropagation), is the algorithmic driver behind the current AI gold rush. Without it, serious Machine Learning applications would not be feasible — leave alone profitable — even on modern-day cloud infrastructure. In fact, if you see a deep neuronal network running <em>anywhere</em>, it has been trained using reverse-mode AD.</p><p>Today’s post will answer the following questions:</p><ul><li>What is Software 2.0 and why might the idea of differentiable programming be even bigger than Machine Learning?</li><li>How does my high-school calculus class relate to gradient descent, the work-horse of Machine Learning?</li><li>What’s does it mean to differentiate code? How can one possibly compute a derivative of a piece of, say, Python, Scala, or C code?</li><li>Why can and should differentiation be automated?</li></ul><h3>Software 2.0, or Fill-in-the-Blanks Programming</h3><p>With Machine Learning becoming the norm in the late 2010s, AI celebrities such as Yann LeCun or Andrej Karpathy popularized the idea of Software 2.0: If neuronal networks, a special kind of computer programs, can learn their optimal parameters based on sufficient training data, then why don’t we design <em>all</em> programs to optimize themselves based on data describing their correct behavior?</p><p>To illustrate this idea, imagine the space of all possible programs — the vast program space, where every possible computer program is represented by a single point. Software 2.0 is when you do not fix your entire program but rather select a subset of program space — a parameterizable class of possible programs — and leave it to the computer to find the optimal choice within this class. This is what Andrej Karpathy calls <a href="https://twitter.com/karpathy/status/1000488820372996096">„fill-in-the-blanks programming”</a>. You define the frame, Software 2.0 paints the picture.</p><figure><img alt="Differentiable code optimizes itself, thereby moving through a continuous subset of program space." src="https://cdn-images-1.medium.com/max/1024/0*GG1PsYpnouyaJv8w.gif" /><figcaption><em>Differentiable programs automatically optimize within a subset of program space. (Inspired by </em><a href="https://medium.com/@karpathy/software-2-0-a64152b37c35"><em>Software 2.0</em></a><em>, A. Karpathy, 2017) (Source: The author)</em></figcaption></figure><p>But how do you explain to a computer what exactly you consider <em>optimal</em>? Here, it turns out, computers are not that different from human software developers, after all. Rather than a vague verbal explanation of software requirements, most developers prefer objectively testable specifications, ready to be integrated into an automated test suite. So when we provide a large set of tests to our Software 2.0, the computer systematically tries out various concrete programs, tracing out its subset of program space. For each of these programs it measures how far it is away from an optimal program by how well it satisfies the test suite.</p><figure><img alt="A box with an inlet and an outlet. An input, x, is inserted into the inlet and comes out the outlet as f(x)." src="https://cdn-images-1.medium.com/max/600/1*zaOsrsXRphu5VQD9nhdUpQ.png" /><figcaption><em>The program from the tester’s viewpoint. (Source: The author)</em></figcaption></figure><p>To make this approach work, we have to help the computer a little bit by using a special kind of test, so-called <em>soft unit tests</em> (SUT). A SUT is basically your regular unit test with the only difference that it does not give you a binary response (green light on success, red light on failure) but instead calculates a score to quantify how far you are away from the expectation. Testing addition, for example, a SUT would tell you that 2+2=4.1 is less wrong than 2+2=-11.</p><figure><img alt="The box is cut open. Through the cut, several Greek letters are revealed." src="https://cdn-images-1.medium.com/max/600/1*ueQDA7rAvhItneYBdTYPVw.png" /><figcaption><em>Cutting the black box open reveals its internal parameters. (Source: The author)</em></figcaption></figure><p>From the tester’s viewpoint, the program is a black box converting inputs into outputs. Given some input <em>x</em>, it produces an output <em>f</em>( <em>x</em>). Of course, if you would cut the black box open, you would reveal a (possibly huge) number of internal parameters. In a conventional program, all these parameters would be fixed to definite values. In Software 2.0, however, by way of tuning these parameters, the program „moves” through program space.</p><figure><img alt="Many inputs are inserted into the box. The outputs are compared to expected values. A two-sided arrow indicates a feedback." src="https://cdn-images-1.medium.com/max/1024/0*SEsISzCxH1rBS9u2.png" /><figcaption><em>A Software 2.0 program subject to N soft unit tests tunes its internal parameters to match output f(xᵢ) and expectation yᵢ. (Source: The author)</em></figcaption></figure><p>Each of the SUT comprises an input <em>x</em> and an output <em>y</em>. The input is inserted into the program, which produces from it the output <em>f</em>( <em>x</em>). This output is compared to the expected outcome and receives a good score when both values are approximately equal. The result of the comparison is fed back into the Software 2.0 algorithm where it is used to tune the parameters to incrementally improve the test score. <em>y</em></p><p>After a relatively short-lived hype, the term Software 2.0 didn’t become quite the buzzword its inventors had hoped for. However, if you have been anywhere near the Machine Learning crowd in the last decade, you likely have heard of the most relevant subclass of Software 2.0: <em>differentiable code</em>, sometimes written ∂Code („∂” is the symbol of partial differentiation).</p><p>Whereas Software 2.0 describes self-optimizing code in general, differentiable code is code that self-optimizes through gradient descent methods. How does differentiable code help us with the optimization procedure? Naively, we could try out various parameter sets at random, until we are reasonably sure that we can live with the remaining error. But there are at least two major problems with that. First, the full parameterized subset of program space is usually enormous. Even if there’s only a single continuous parameter, we have theoretically infinitely many possible choices. Second, whenever we find a seemingly good solution, how can we ever be sure if there is not an even better solution right next to it?</p><p>These are all age-old problems by no means specific to Machine Learning. In mathematics, such optimization problems are all over the place. Standing on the shoulders of giants such as Newton and Leibniz, we can understand most of it surprisingly well with what is high-school math knowledge, today.</p><p>To illustrate these problems and their solution, let’s have a first look at differentiable programming.</p><h3>A first differentiable program</h3><p><em>(The idea of this section has been adapted from </em><a href="https://www.youtube.com/watch?v=igRLKYgpHy0"><em>Differentiable Functional Programming</em></a><em>, N. Welsh, 2018)</em></p><p>Imagine you’d have to write a fairly simple program. The requirements are as follows: The program has to accept a single floating-point number as an input parameter <em>x</em>. From this input, it has to produce an output <em>y</em>, another float. You are given 200 soft unit tests describing the required behavior. Each test is defined by a pair (<em>x</em>,<em>y</em>) of one input <em>x</em> and one expected output <em>ŷ</em>.</p><p>Since the unit tests are soft, there has to be a measure of how well or bad the program did on each test. For this purpose, we introduce the scoring metric</p><figure><img alt="\displaystyle \mathcal{L}^{(i)}=\left\vert\hat{y}^{(i)}-f(x^{(i)})\right\vert=\left\vert\hat{y}^{(i)}-\omega x^{(i)}\right\ve" src="https://cdn-images-1.medium.com/max/415/1*r9T_u5qklbUicqJnTBNM8g@2x.png" /></figure><p>The metric 𝓛⁽ⁱ⁾ is the so-called <em>loss</em> of the <em>i</em>-th test. Optimally, it would be zero, because then input <em>x</em>⁽ⁱ⁾ would exactly match expected output <em>ŷ</em>⁽ⁱ⁾. The overall test suite performance metric 𝓛 of our program is then simply the sum of all the 200 𝓛⁽ⁱ⁾, or, to put it as <a href="https://towardsdatascience.com/understanding-mathematical-symbols-with-code-5aa0c542644">a mathematician’s for-loop</a>,</p><figure><img alt="$\displaystyle \mathcal{L} = \sum_{i=1}^{200} \mathcal{L}^{(i)}. $" src="https://cdn-images-1.medium.com/max/140/1*8k1WWjCpX8fPj215qceeLg@2x.png" /></figure><p>The smaller 𝓛, the better our overall performance. Since the tests are pairs of numbers, we can visualize all 200 in one 2-D plot, with the inputs on the <em>x</em>-axis and the outputs on the <em>y</em>-axis. Let’s assume the plot of your test data looks like this:</p><figure><img alt="The requirements of our differentiable code example as 200 soft unit tests. Input and output show a sinusoidal relation." src="https://cdn-images-1.medium.com/max/960/1*C95tC1DmVGkHKAyXxh33vQ.png" /><figcaption><em>A plot of 200 soft unit tests. Each point represents a pair of input and expected output. (Source: The author)</em></figcaption></figure><p>Now, there is one last major decision to make, before you can hand-off your development task to the algorithm: Choosing a suitable continuous subset of program space to search for the optimum.</p><p>Considering the sinusoidal nature of the input-output relation in your test suite, we have a hunch that</p><figure><img alt="$\displaystyle f(x) = \sin(\omega x) $" src="https://cdn-images-1.medium.com/max/172/1*440sGE0blMOt3Bw0BP129A@2x.png" /></figure><p>might be a reasonably good choice. There is only one internal parameter in that function: <em>ω</em> (that’s a lower-case „omega”), denoting the frequency of the sine. Therefore, we are looking at a one-dimensional subset of program space that you can visualize as a line from <em>ω</em>=-∞ to <em>ω</em>=∞, just like the <em>x</em>-axis goes from <em>x</em>=-∞ to <em>x</em>=∞.</p><p>Each possible <em>ω-</em>value corresponds to another version of our program <em>f</em>( <em>x</em>). Let’s say we set <em>ω</em> to 12.345, then our program becomes</p><figure><img alt="$\displaystyle f(x)=\sin(12.345\cdot x).$" src="https://cdn-images-1.medium.com/max/243/1*4gSqJK_hwDu4D-2hl94rSg@2x.png" /></figure><p>So, let’s give it a try! Let’s choose some <em>ω</em>-values and see if we can’t satisfy all those unit tests.</p><figure><img alt="For 4 ω-values, progam output is plotted (solid line) next to the expectation (dots). The better the match, the lower the 𝓛." src="https://cdn-images-1.medium.com/max/1024/1*aoeEC0v9IKHlDpsd9CdIPQ.gif" /><figcaption><em>Test suite performance for parameter values ω=0.75, 2.25, 1.0, and 1.5. Left: the program’s outputs (solid line) vs. the expected outputs (dots). In one frame, three orange bars on the left indicate the point-wise error ℒ⁽ⁱ⁾ for three example points. Right: 𝓛-score for each ω-value.</em></figcaption></figure><p>By looking at the animation above, <em>ω</em>= 1.5 is by far the best result. But could there be a better solution, at 1.54321, say? In this example, there is not. In reality though, by random choice, it might have taken you dozens or hundreds of attempts to find a sufficiently good solution and you’d probably still not have arrived very close to the correct 1.5.</p><p>How can we get out of this dilemma? Think about loss metric 𝓛. What are the parameters, that is, the <em>unknowns</em>, in this function? Despite the 200 <em>x</em>- <em>y</em>-pairs, 𝓛 is structurally very simple. Admittedly, for a human it would be a bit unwieldy to write out the full sum of 200 terms, one for each SUT. For a computer, though, a sum with 200 terms is not scarier than a sum of two. What remains is a simple one-parameter function, 𝓛( <em>ω</em>). If you look at its definition above, you see that it is completely determined by the test suite’s x⁽ⁱ⁾- and <em>ŷ</em>⁽ⁱ⁾-values. This means, there is no need for randomized sampling parameter values, at all. You already know the function’s value at <em>every single point!</em> You can easily plot 𝓛( <em>ω</em>), just like any other function:</p><figure><img alt="The loss function of our differential code example has several local minima and a pronounced global minimum at omega=1.5" src="https://cdn-images-1.medium.com/max/1024/1*nVLrAWADD9fwbjIslNfQYQ.gif" /><figcaption><em>The program’s overall test suite performance (loss score) as a function of frequency parameter ω. (Source: The author)</em></figcaption></figure><p>So, to find the optimal <em>ω</em>, you simply have to find a minimum of the function 𝓛(<em>ω</em>). Finding minima — wait a minute, didn’t we do that all the time in our high-school calculus class? Indeed. And it had something to do with derivatives. Fortunately, 𝓛(<em>ω</em>) is not only structurally simple but also <em>differentiable</em>. The term <em>differentiable </em>means that you can calculate a derivative of 𝓛(<em>ω</em>). In fact, the whole reason why our little example here is called <em>differentiable </em>programming is that 𝓛(<em>ω</em>), the function towards which we want to optimize, is differentiable Let us refresh our calculus memories to see how the derivative can help us to systematically optimize.</p><h3>Calculus recap</h3><p>A derivative of a function <em>f</em>( <em>x</em>) at point <em>x</em> measures the local slope of the function. You can view the derivative as a tool that always tells you where’s up and where’s down on a function. Truth is, that’s all you need to know to understand the essential idea of gradient descent and differentiable programming.</p><p>More formally put, if the derivative with respect to its parameter is greater than 0, it means that you will go uphill by increasing the parameter. If it is smaller than 0, it means that you will go downhill by increasing the parameter.</p><p>To see, how the derivative relates to the slope, let us take a look at its definition. Commonly, the derivative is written <em>f </em>′ (read: “eff prime”) and defined as a mathematical limit of the form</p><figure><img alt="$\displaystyle f’(x) = \lim_{\Delta x\rightarrow 0} \frac{f(x+\Delta x)-f(x)}{\Delta x}. $" src="https://cdn-images-1.medium.com/max/358/1*0ykB_4rky1bs-aIT3a7GPw@2x.png" /></figure><p>You can visualize the derivative as the slope of a straight line going from the point (<em>x</em>,<em>f</em>(<em>x</em>)) to (<em>x</em>+<em>Δx</em>,<em>f</em>(<em>x</em>+<em>Δx</em>)) as you reduce the horizontal distance <em>Δx, </em>bringing the points closer and closer together. In the mathematical limit <em>x</em>, <em>f</em>( <em>x</em>)) to ( <em>x</em>+ <em>Δx</em>, <em>f</em>( <em>x</em>+ <em>Δx</em>)) as you reduce the horizontal distance <em>Δx, Δx→0</em> the points practically merge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vuvzLLSuHQ40WiK8Zp_eIg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0g21eFAwLBbq-JS1adNAjQ.gif" /><figcaption>Left: <em>The derivative is the slope of a line connecting two points in the limit of vanishing distance between said points. Right: The slope is change in height divided by change in position, that is, </em>Δf<em>/Δx. (Source: The author)</em></figcaption></figure><p>The slope is then quite naturally defined by</p><figure><img alt="$\displaystyle \mathrm{slope} = \frac{\mathrm{change}\:\mathrm{in}\:\mathrm{heig… …{\mathrm{change}\:\mathrm{in}\:\mathrm" src="https://cdn-images-1.medium.com/max/365/1*55EIV2E6cJxwwM-r2Rhxew@2x.png" /></figure><p>One of the reasons why derivatives are so awfully useful is that at extreme points — minima, the bottoms of your function’s valleys, and maxima, the peaks of your function’s hills — the derivative is always exactly 0. This is directly evident from plotting the slope at the minima and maxima of a function.</p><figure><img alt="The slope at minima and maxima is zero, as can be seen by drawing the horizontal tangents to f in these points." src="https://cdn-images-1.medium.com/max/800/1*PmD0wKgV-Tl2-ysJRP2r3w.gif" /><figcaption><em>In minima and maxima the slope is zero (horizontal), that is, f′=0. (Source: The author)</em></figcaption></figure><p>And it gets even better! Not only does the derivative tell you, whether you are currently at a minimum or maximum, it also tells you in which direction to go to find one! <em>Direction</em> here means literally along which direction you move along the <em>x</em>-axis, that is, whether you increase or decrease the parameter <em>x</em>.</p><p>How does that work? As promised in this section’s introduction, the derivative is a tool that allows you at any point, to know what way is up and what way is down. If you want to maximize the function value, that is, you want to find the highest point in your surroundings, then you go upwards.</p><p>What does that mean now, exactly? Consider you are currently at parameter value <em>x₀</em>. There, the local derivative is <em>f</em>′( <em>x₀</em>). If the derivative is larger than zero, it means that by increasing <em>x</em> you go up and by decreasing <em>x</em> you go down. So, what do you do to come closer to your objective, the highest point? You increase <em>x</em>. More mathematically speaking, you choose a new parameter value <em>x</em> by taking a step in the direction of positive slope:</p><figure><img alt="$\displaystyle x_0 \rightarrow x_0 + \varepsilon\cdot f’(x_0), $" src="https://cdn-images-1.medium.com/max/235/1*u1pt5X_WW-MVD4SI52c8GQ@2x.png" /></figure><p>where <em>ɛ</em> quantifies your step size. In Machine Learning lingo, the step size is called the <a href="https://en.wikipedia.org/wiki/Learning_rate">learning rate</a>.</p><p>This formula automatically covers the opposite case, where the derivative is less than zero. Negative <em>f</em> ′ means that for larger <em>x</em>, you go down, farther away from your objective, the highest point. Therefore, at negative <em>f</em> ′( <em>x₀</em>), going upwards means taking a step towards a <em>smaller</em> <em>x</em>-value. If you want to minimize the function value, you proceed similarly, only that now you take <em>ɛ</em>-steps in the direction of negative slope (downhill):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*59FeD_YRdOYbyQLMHl8mqQ@2x.png" /></figure><p>The process is visualized below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Im7plKV2Ref6xdgx7ZeNRw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8ioy_Z8Bn_jNSJ-_seOtMA.gif" /><figcaption><em>The derivative is used to iteratively find a local maximum (left) or minimum (right). (Source: The author)</em></figcaption></figure><p>The astute reader will have noted several problems with this approach. For one, you will only ever find the minimum or maximum closest to your starting point. In the example above, if you by chance started closer to <em>x</em>ₘᵢₙ,₂ than to <em>x</em>ₘᵢₙ,₁, minimization using the described method will always bring you to <em>x</em>ₘᵢₙ,₂ and never to <em>x</em>ₘᵢₙ,₁, although it would be an even lower, that is, <em>better</em>, point.</p><p>This is a well-known problem stemming from the local nature of the derivative itself, and it’s a hard one. Every method based on derivatives will always have this shortcoming built-in. The problem is even bigger, in particular in higher dimensions, because besides minima and maxima there are also saddle points, other entities with the <em>f</em> ′=0 property, that will interfere with your quest for an optimum.</p><p>Unfortunately, until now there is no method known to humanity to tell, in general, whether or not there is a better point, at all, leave alone how to systematically find it. A large number of tools have been invented to at least mitigate this problem but a general solution might still be lifetimes away.</p><p>The second issue is the choice of the step size <em>ɛ</em>. If it is too large, you risk overshooting, that is, you might jump over an optimum instead of approaching it. If, on the other hand, it is too small, you might have to take <em>a lot</em> of steps to come close enough to an optimum. Even worse, the step size is actually not <em>ɛ</em> but <em>ɛ</em>⋅<em>f</em> ′ and thus proportional to the derivative’s value. Since at the extremum the derivative becomes zero when you are approaching it, the derivative will become smaller and smaller, which in turn results in you taking smaller and smaller steps. To combat both this slow-down as well as the overshooting problem, in practical application <em>ɛ</em> is chosen adaptively.</p><h3>An excursion to higher dimensions</h3><p>But isn’t reality much more complicated, when we have not one parameter but typically hundreds or thousands? No, not really. In fact, it is almost surprisingly easy to generalize the approach described in the previous section from one to arbitrary many dimensions.</p><p>Let us start by going from one to two dimensions. That’s equivalent to going from single-parameter functions <em>f</em>( <em>x</em>) to two-parameter functions <em>f</em>( <em>x</em>, <em>y</em>). Just like the plot of <em>f</em>( <em>x</em>) was two dimensional (one dimension for input <em>x</em>, one for output <em>f</em>( <em>x</em>)), the plot of <em>f</em>( <em>x</em>, <em>y</em>) is three dimensional (two inputs + one output). You can visualize it like a landscape and think of <em>f</em>( <em>x</em>, <em>y</em>) as a height-map.</p><figure><img alt="A point is marked red on a curved surface with a round valley and a round hill with an overlay coordinate grid." src="https://cdn-images-1.medium.com/max/911/1*FTRxQng_U7Tthz1Koi1Rgg.gif" /><figcaption><em>“Landscape” defined by a two-dimensional function f(x,y). (Source: The author)</em></figcaption></figure><p>We are trying to do the same thing we did in 1-D before, that is, to find a local optimum. Imagine we are looking for a local minimum. Our logic from the 1-D case still applies perfectly: To approach the next local minimum, one should walk downhill. But for that we would need to know the slope. How do we calculate the slope in 2-D?</p><p>For example, the line parallel to the <em>y</em>-axis at <em>x</em>₀ <em>x</em>=-0.5 can be seen as the function <em>y</em>₀ <em>g</em>( <em>y</em>)= <em>f</em>(-0.5, <em>y</em>) with constant <em>x</em>=-0.5. That means that at any point (<em>x</em>, y), we can slice the 2-D function into two 1-D functions. And we already know how to get the slope of a 1-D function! We simply calculate its derivative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UeNcGswGOcIoVUSW5fpZaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UlVyETU0_YnJJjuK7ndeMQ.png" /><figcaption><em>Vertical cuts through the f(x,y)-landscape at point (-0.5, 0.5), parallel to the x-axis (left), and parallel to the y-axis (right). (Source: The author)</em></figcaption></figure><p>But first, we have to refine our notation a bit. Now that there is more than one variable, the notation <em>f</em> ′ has become ambiguous, as it is unclear whether the derivative is with respect to <em>x</em> or <em>y</em>. To disambiguate, there is a more general notation. A derivative with respect to <em>x</em> is denoted</p><figure><img alt="$\displaystyle \frac{\partial f}{\partial x} $" src="https://cdn-images-1.medium.com/max/40/1*h-aZ8X7K0KozlOZrtwYumQ@2x.png" /></figure><p>and the derivative with respect to <em>y</em> is</p><figure><img alt="$\displaystyle \frac{\partial f}{\partial y}. $" src="https://cdn-images-1.medium.com/max/47/1*ppAnJAfu2yGWgtDUyDQugg@2x.png" /></figure><p>The symbol <a href="https://en.wikipedia.org/wiki/%E2%88%82#Names_and_coding">∂ goes by many names</a>, such as „die”, „doh” or — my favorite — „dabba”, to name a few. But since it is a stylized letter d, you can simply read it „dee” and the derivative with respect to <em>x</em> as „dee eff dee ex”. If you are not used to multivariate calculus, it might be confusing how suddenly a fraction is used to generalize a simple prime (′) symbol. This comes quite naturally though because, as we saw in the previous section, the derivative <em>is</em> a fraction:</p><figure><img alt="$\displaystyle f’(x) = \lim_{\Delta x\rightarrow 0} \frac{f(x+\Delta x)-f(x)}{\Delta x}. $" src="https://cdn-images-1.medium.com/max/374/1*V1B5MYYToJiT_SbeHHmyhg@2x.png" /></figure><p>You can interpret the numerator <em>∂f</em> as the difference in <em>f</em> and the denominator <em>∂x</em> as the difference in <em>x</em>, in the frame of the limit process.</p><p>Having settled on a notation, how do we combine the two 1-D derivatives back to a two-dimensional entity, so that we can tell in which direction to change our parameters ( <em>x</em>, <em>y</em>)?</p><p>It is one of the great wonders of calculus that, as long as you make small enough steps, you do not even need to combine them at all. If you make a small step along the <em>y</em>-direction exactly as you would in the 1-D case, that is,</p><figure><img alt="$\displaystyle x \rightarrow x — \varepsilon\cdot \frac{\partial f}{\partial x}(x_0, y_0) $" src="https://cdn-images-1.medium.com/max/255/1*_zMzTyCwuSoB-Iw4aqW9Tw@2x.png" /></figure><p>and another small step in the <em>x</em>-direction, again, exactly as you would in 1-D, that is,</p><figure><img alt="$\displaystyle y \rightarrow y — \varepsilon\cdot \frac{\partial f}{\partial y}(x_0, y_0), $" src="https://cdn-images-1.medium.com/max/260/1*IRWJeZB3lco71cEA3NtePw@2x.png" /></figure><p>you have effectively made a 2-D move into the correct direction, straight toward the minimum. Now what is <em>small enough</em> with regards to step size? Strictly speaking, two 1-D steps are the same as one 2-D step only if the steps are what mathematicians call <em>infinitesimal</em>, that is, <em>infinitely</em> small. However, we are pretty much on the safe side, here, as the error from neglecting the interaction of <em>x</em>- and <em>y</em>-dimensions with finite steps scales benignly with the step size. This means that when you increase the step size, you will feel the errors from the single-parameter derivatives long before the mixed-dimension errors become significant (because the former are of order 𝒪(<em>ɛ</em>) while the latter are of order 𝒪( <em>ɛ</em>²) and <em>ɛ </em>is small).</p><p>Of course, there is a better, more compact way to express that you are actually doing the same for each dimension. First, you can define a shorthand for <em>x</em> and <em>y</em>:</p><figure><img alt="$\displaystyle \mathbf{x} := \left(\begin{array}{c}x\\ y\end{array}\right) $" src="https://cdn-images-1.medium.com/max/139/1*VJNX5RMyvsHzWCL9lwdXpQ@2x.png" /></figure><p>Second, the collection of all 1-D derivatives of a function, the <em>gradient</em>, is denoted by <em>∇ f</em> which in 2-D is defined as</p><figure><img alt="\displaystyle \nabla f(x, y) = \left(\begin{array}{c}\frac{\partial f}{\partial x}(x, y)\\ \frac{\partial f}{\partial y}(x,y)" src="https://cdn-images-1.medium.com/max/304/1*pKundUGsEMT7zpfP3GnPng@2x.png" /></figure><p>So you can write your two 1-D optimization steps together as one 2-D step:</p><figure><img alt="$\displaystyle \mathbf{x} \rightarrow \mathbf{x} — \varepsilon\nabla f(\mathbf{x}_0). $" src="https://cdn-images-1.medium.com/max/210/1*7IcFZtuL_-2zZSIfAF670g@2x.png" /></figure><p>Now that we have seen how to perfectly decompose a 2-D problem into two 1-D problems, what is going to stop us from going to 3 dimensions, 42 dimensions, or any other conceivable number of dimensions? Nothing will!</p><p>Consider any positive integer dimension <em>N.</em> Using again a shorthand for the variables</p><figure><img alt="$\displaystyle \mathbf{x} := \left(\begin{array}{c}x_1\\ x_2\\ \vdots\\ x_N\end{array}\right), $" src="https://cdn-images-1.medium.com/max/178/1*oYnKgIUaglDAuEl2IU3wpQ@2x.png" /></figure><p>the slope in <em>N</em> dimensions can be written as the combination of <em>N</em> one-dimensional slopes:</p><figure><img alt="$\displaystyle \nabla f\left(x_1,x_2,…,x_N\right) = \left(\begin{array}{c}\fra… …frac{\partial f}{\partial x_N}\left(…" src="https://cdn-images-1.medium.com/max/541/1*i1vqCBGBn33c-64YmsoT9A@2x.png" /></figure><p>Moreover, written this way, the optimization step in <em>N</em> -D looks exactly like in 2-D:</p><figure><img alt="$\displaystyle \mathbf{x} \rightarrow \mathbf{x} — \varepsilon\nabla f(\mathbf{x}_0). $" src="https://cdn-images-1.medium.com/max/210/1*7IcFZtuL_-2zZSIfAF670g@2x.png" /></figure><p>At this point maybe you think that the mechanics of calculating high-dimensional derivatives is not that difficult, after all, but you’re still not quite comfortable with actually <em>thinking</em> in <em>N</em>-dimensional spaces. If so, do not worry, you are in good company! Just do as Geoffry Hinton, one of the doyens of AI, recommends:</p><blockquote>To deal with hyper-planes in a 14-dimensional space, visualize a 3-D space and say ‚fourteen’ to yourself very loudly. Everyone does it.</blockquote><blockquote>Geoffry Hinton (in his archived Coursera MOOC, <a href="https://www.cs.toronto.edu/~hinton/coursera/lecture2/lec2c.mp4)">Lecture 2c: A geometrical view of perceptions</a>, around minute 1:00)</blockquote><p>To understand everything about gradients you can always resort to thinking of a 3-D landscape like the one from our example, above, and gradient descent is nothing but walking down the hills of this landscape. If you still struggle with visualizing gradient descent even in 3-D, the people from <a href="https://losslandscape.com/">losslandcape.com</a> made <a href="https://www.youtube.com/watch?v=Q3pTEtSEvDI">a beautiful animation (with cheezy voice-over) for you</a>.</p><h3>Differentiating some code</h3><p>Now we have been talking quite a bit about derivatives of mathematical functions in one or many dimensions. But what is the derivative of a piece of computer code? Let us have a look at some concrete programming languages and calculate some actual code derivatives. To follow, you should either be familiar with the derivatives of elementary functions such as x², sin(x), and exp(x) or <a href="https://en.wikipedia.org/wiki/Derivative#Rules_for_basic_functions">have a reference at hand</a>.</p><p>Consider, for example, this simple function implemented in Python:</p><pre>def f(x: float) -&gt; float:<br>    return 3.0 * x</pre><p>This function implements the mathematical function <em>f</em>( <em>x</em>)=3 <em>x</em>. In calculus class it would be the easiest task to calculate its derivative: <em>f</em> ′( <em>x</em>)=3. So how would the best possible implementation of the derivative look like in Python? How about this:</p><pre>def fprime(x: float) -&gt; float:<br>    return 3.0</pre><p>This can be justly called the best possible implementation. It calculates the value of the derivative to machine accuracy. One could even argue that this derivative is actually <em>exact</em> and that only its evaluation at a given <em>x</em> introduces an approximation to machine accuracy.</p><p>Let us look at another example, this time in Scala:</p><pre>def g(x: Double): Double =<br>    math.sin(x)</pre><p>Again, consider the mathematical function implemented here: <em>g</em>(<em>x</em>) = sin(<em>x</em>). The derivative of this important but elementary function is simply <em>g</em>′(<em>x</em>) = cos(<em>x</em>). Therefore, the derivative of our Scala function <strong>g(x: Double): Double</strong> should be this:</p><pre>def gprime(x: Double): Double =<br>    math.cos(x)</pre><p>Here is one final example, this time in C, to make sure we got this right:</p><pre>float h(float x) {<br>    return exp(x) + 1.0/x;<br>}</pre><p>We need a function <strong>float hprime(float x).</strong> How would it look like? Starting again from the actual mathematical function implemented in the code</p><figure><img alt="$\displaystyle h(x) = \mathrm{e}^x + \frac{1}{x} $" src="https://cdn-images-1.medium.com/max/165/1*eVoy3LoEhB89Ldiuuivitg@2x.png" /></figure><p>and applying basic differentiation rules, we obtain</p><figure><img alt="$\displaystyle h’(x) = \mathrm{e}^x — \frac{1}{x²}. $" src="https://cdn-images-1.medium.com/max/191/1*MEOkxKn6lNowiKEZzeXf0Q@2x.png" /></figure><p>That can be readily implemented in C again!</p><pre>float hprime(float x) {<br>    return exp(x) - 1.0/powf(x, 2);<br>}</pre><p>Easy enough, the derivative of code that implements a mathematical function is the implementation of said function’s derivative.</p><h3>Complicated functions are but chains of simple ones</h3><p>So far, there is no need for automation. The derivatives in the previous section’s examples could simply be implemented by hand. But how about more complicated functions? Every function, no matter how complicated, is made up of simple operations. To illustrate how to go from simple to complicated, let’s start with</p><figure><img alt="$\displaystyle h(x) = \sqrt{x+5}. $" src="https://cdn-images-1.medium.com/max/176/1*tkJ2G_NowFRPFL3ghhyTcA@2x.png" /></figure><p>The function <em>h(x</em>) can be seen as the result of subsequent application of two functions</p><figure><img alt="$\displaystyle f(x) = x + 5 \qquad \mathrm{and} \qquad g(x) = \sqrt(x), $" src="https://cdn-images-1.medium.com/max/444/1*Tz4b2-L3DzoE5aSf-ylEAQ@2x.png" /></figure><p>as can be seen here:</p><figure><img alt="$\displaystyle h(x) = \sqrt{x+5} = \sqrt{f(x)} = g(f(x)). $" src="https://cdn-images-1.medium.com/max/405/1*y0FBTzI79uMhLPttXVmvyg@2x.png" /></figure><p>Creating new functions by inserting the result of one function into another is known as <em>function composition</em>. There is a special notation that saves you from getting lost in all those brackets:</p><figure><img alt="$\displaystyle (h \circ f)(x). $" src="https://cdn-images-1.medium.com/max/120/1*CawL6KS6Ne2ePxWotIJ61Q@2x.png" /></figure><p>Let’s take our composition one step further and plug <em>h</em>( <em>x</em>) into yet another function</p><figure><img alt="$\displaystyle k(x) = \mathrm{e}^x. $" src="https://cdn-images-1.medium.com/max/119/1*n9I6j1ycNjWVVCHab3t0PA@2x.png" /></figure><p>The result would be</p><figure><img alt="$\displaystyle l(x) = \mathrm{e}^{\sqrt{x+5}} = k(h)=k(h(f(x))) = \left(k\circ h \circ f\right)(x). $" src="https://cdn-images-1.medium.com/max/582/1*i2ZBCC1FA29wGZXI-PJm6A@2x.png" /></figure><p>Of course, we could continue this game ad infinitum, composing together more and more functions:</p><figure><img alt="$\displaystyle P(x) = f\circ g \circ … (x) = f(g(…(x)…)). $" src="https://cdn-images-1.medium.com/max/416/1*jl0Vd-Or3GOMgA5_gch_0A@2x.png" /></figure><p>Interestingly, the fact that a function can be composed of elementary functions, allows us to also compose its derivative from the derivative of these elementary functions. You probably remember this as another concept from high-school calculus, known as the <a href="https://en.wikipedia.org/wiki/Chain_rule"><em>chain rule</em></a>:</p><figure><img alt="$\displaystyle (f\circ g)’(x) = f’(g(x))\cdot g’(x). $" src="https://cdn-images-1.medium.com/max/326/1*7nO5l-Rv1jIYiNFVFgVRKA@2x.png" /></figure><p>If <em>g</em>( <em>x</em>) is itself a composition, the chain rule can be applied recursively, to differentiate arbitrarily long composition chains.</p><p>Consequently, as long as we know how to differentiate a relatively small set of elementary functions such as sin( <em>x</em>), exp( <em>x</em>), log( <em>x</em>) and <em>xⁿ</em> and basic operations such as sums and products of functions, the chain rule provides us with a simple recipe to compute derivatives of any function, no matter how complicated.</p><p>You could now use this recipe to calculate the derivative of any function manually, for example on a piece of paper, and then implement the result in code. Mathematically, there’s nothing wrong with that approach. Practically, though, even if you only have a moderately complicated function, for example, a product of some dozen factors, each composed of a handful of chained elementary functions, this process becomes tedious and error-prone. For serious applications as, for example, the training of a DNN made up of thousands of elementary operations, the manual approach would be ridiculous. This begs the age-old question that always comes up when facing huge amounts of tedious work: <a href="https://comb.io/UhsQJO">Can’t someone else do it?</a><br> <br> Yes, the computer can! To have the computer differentiate any differentiable function, we just have to teach it how to differentiate simple operations and the chain rule — and we’re done!</p><p>Application of the chain rule is a purely mechanical process that we can easily turn into an algorithm and hand it off to the computer. This is the idea behind <em>automatic</em> differentiation. It can be realized in various ways, for example using a preprocessor that produces the actual code of the differentiated functions, just like we did manually in our example, above. The more common approach watches your program at runtime and records the sequence (or rather graph) of elementary operations on a so-called <em>tape</em> and then computes the derivative of the taped code, dynamically.</p><h3>Conclusion</h3><p>This concludes today’s blog post. We have learned about the concept of Software 2.0 and its currently most important incarnation, differentiable programming. After refreshing our high-school calculus knowledge, we have seen how to employ derivatives to iteratively optimize with respect to a scoring function, that is, we have learned the essence of gradient descent. Looking at examples, we have seen that the derivative of code that implements a mathematical function is the implementation of said function’s derivative. Finally, we showed how the chain rule can be used to turn differentiation of arbitrary functions into a purely mechanical process, opening up the way for automatic differentiation. I hope you enjoyed this blog post and maybe even learned something new.</p><p>In a follow-up post we will dive deeper into the algorithmic details of differentiable programming and focus on the following points:</p><ul><li>How automatic differentiation (AD) works</li><li>What’s forward-mode and reverse-mode (backpropagation) automatic differentiation (AD)</li><li>Why gradient descent <em>needs</em> reverse-mode AD</li><li>How to compute derivatives of for-loops, conditionals, and other control structures</li><li>What differentiable programming can be used for beyond Machine Learning</li></ul><p>In the meanwhile, you might want to check out the following excellent presentations for further insights into the world of differentiable programming:</p><ul><li>Ryan P. Adams, <a href="https://www.youtube.com/watch?v=sq2gPzlrM0g">You Should Be Using Automatic Differentiation</a>, 2016</li><li>Matthew J. Johnson, <a href="http://videolectures.net/deeplearning2017_johnson_automatic_differentiation">Automatic Differentiation</a>, Deep Learning Summer School Montreal 2017</li><li>Noel Welsh, <a href="https://www.youtube.com/watch?v=igRLKYgpHy0">Differentiable Functional Programming</a>, Scala Days 2018</li><li>Viral B. Shah, <a href="https://www.youtube.com/watch?v=6V75lblJ2ns">Differentiable Programming — An exciting generalization of Deep neural networks</a>, PyData Delhi 2019</li></ul><p>Last but not least, if you want to get knee-deep into the math behind AD then I have one special bonus treat for you:</p><ul><li>Conal Elliott, <a href="https://www.youtube.com/watch?v=ne99laPUxN4">The Simple Essence of Automatic Differentiation</a>, Microsoft Research Talk (2018)</li></ul><p><em>Originally published at </em><a href="https://consilica.de/how-differentiable-code-makes-the-machine-learning-world-go-round-part-one/"><em>https://consilica.de</em></a><em> on May 11, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f588140b148" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/high-school-math-for-machines-differentiable-code-5f588140b148">High-School Math for Machines: Differentiable Code</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>