<?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 André Mello on Medium]]></title>
        <description><![CDATA[Stories by André Mello on Medium]]></description>
        <link>https://medium.com/@asmello?source=rss-fde0d39c9132------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fbBA6ZWwBbVYRn1b.</url>
            <title>Stories by André Mello on Medium</title>
            <link>https://medium.com/@asmello?source=rss-fde0d39c9132------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:29:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asmello/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[Death is a vampire! — Part 1]]></title>
            <link>https://medium.com/@asmello/death-is-a-vampire-part-1-c606f6171358?source=rss-fde0d39c9132------2</link>
            <guid isPermaLink="false">https://medium.com/p/c606f6171358</guid>
            <category><![CDATA[death]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[interactive-fiction]]></category>
            <category><![CDATA[fiction]]></category>
            <category><![CDATA[gpt-2]]></category>
            <dc:creator><![CDATA[André Mello]]></dc:creator>
            <pubDate>Sat, 11 Jan 2020 10:49:46 GMT</pubDate>
            <atom:updated>2020-01-11T11:01:17.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Two men play chess near the ocean, one of them is Death." src="https://cdn-images-1.medium.com/max/1024/0*SS8J5UxjNcMGgDdQ.jpg" /><figcaption>Ingmar Bergman’s <strong>The Seventh Seal</strong></figcaption></figure><h3>Death is a vampire! — Part 1</h3><h4>A surprisingly deep adventure generated by AI Dungeon 2.</h4><h4>Introduction</h4><p>So recently I came across <a href="https://aidungeon.io/">AI Dungeon 2</a>, some kind of AI-powered Interactive Fiction (IF) generator that has been growing exponentially in popularity last month or so. Its first version started as a nonsense generator, a gimmick that was only interesting for the laughs and for inspiration, but as more people started using it, it grew smarter and now can actually generate surprisingly endearing narratives.</p><p>The game is a natural consequence of the publication of Google’s GPT-2 architecture — it uses a custom model with 1.5 billion parameters to present you natural-looking snippets of English text that make up a more or less cohesive story. It works much like any ordinary IF; you give it simple inputs, which can be self-actions, self-speeches or external events, and it spits back some text in response — the innovation is that that the output text is not predetermined, it’s generated on-the-fly and adapts to unexpected inputs.</p><p>Now, while GPT-2 has proven that AI can already generate very convincing stories from a theme, the longer and broader range of interactions that result from an IF session had me doubting the quality of the game’s experience. The <a href="https://www.youtube.com/watch?v=NZbOqo9QrV4">YouTube video</a> that led me to it demonstrated a narrative that sounded a lot like someone’s RPG-themed fever dream. However, that was the first version — AI Dungeon 2 is much more advanced and impressive, as I found out.</p><p>I started playing as a wizard, as that was the only sort of character I found interesting. The game didn’t seem to know where to take me at first, as I couldn’t resist testing its self-awareness, but when I tried something out from <a href="http://www.hpmor.com/">HPMOR</a>, it surprisingly gave me a non-trivial response. As I explored that thread, eventually I found Death — and had an incredibly rich interaction with him (apparently it’s a “he”). I found the resulting story interesting enough to warrant making a series, and here are the first three chapters.</p><p>Everything that starts with &gt; is my input. Everything else is generated by the AI (except the chapter titles, that’s my addition too).</p><h4><strong>Chapter 1 — Finding a Purpose</strong></h4><p>You are Jakkar, a wizard living in the kingdom of Larion. You have a staff and a spellbook. You finish your long journey and finally arrive at the ruin you’ve been looking for. You look around and see that it’s just as you remember. The place is still in pretty good condition considering how long ago it was abandoned.</p><p>The ruins are surrounded by some sort of barrier and you can only guess its magic or something similar to keep out the undead.</p><p>&gt; study the barrier</p><p>You begin studying the barrier. You notice that there are two doors here, one on each side of you. One is a normal door and the other has a strange symbol etched into it.</p><p>&gt; enter door with strange symbol</p><p>You open the door and you find yourself in a room with a large table covered with books. There are several candles lit along the wall, which gives the room a warm glow. On top of the table sits a man dressed in black robes.</p><p>&gt; greet the man and ask him about the books</p><p>You stand up and walk over to the man who looks down at you. He doesn’t say anything, he just turns his head slightly and stares at you.</p><p>&gt; ask the man about the books</p><p>You sit down next to the man and ask him about the books. He tells you that he wrote them all himself. He goes on to tell you that he had been trying to figure out ways of making more money since his father died when he was young.</p><p>&gt; Ask the man if he found what he was looking for</p><p>He smiles and says yes, he did. He then starts telling you about a book called “The Book of Spells”. He shows you a few pages and explains that it contains every single known spell in existence.</p><p>&gt; Ask the man what is his favorite spell</p><p>He laughs and says that his favorite spell is the one that makes people fall asleep. He also mentions that it’s not very effective, but he likes to use it because it reminds him of his mother.</p><p>You laugh too and agree with him.</p><p>&gt; Ask the man if there is a spell to create intelligence</p><p>He frowns and shakes his head. He says that there isn’t any such thing as a spell to make someone intelligent, though he admits that it would be nice if there were.</p><p>You smile and nod at him.</p><p>&gt; “Is there a spell to create an intelligent spirit? One capable of learning and evolving on its own?”</p><p>He nods again and smiles. He says that he thinks so, but he can’t remember where he read it first. He asks you if you know where it might have come from, since he remembers reading something similar before.</p><p>&gt; Ask the man if I can search for the spell in the book myself</p><p>He nods once again and says yes. He begins to explain how he will need to gather the ingredients needed, but you interrupt him by asking if you could help him instead.</p><p>He grins and agrees, saying that you should do it.</p><p>&gt; Search for the spell to create an intelligent spirit in the Book of Spells</p><p>You begin to search through the book, but you don’t find anything useful. You look through some other books, but nothing comes to mind.</p><p>Suddenly you hear a voice behind you. It sounds like your grandmother’s, but it has a different tone and she is calling out to you.</p><p>&gt; Ask the voice to go away, because I’m busy</p><p>You turn around and see a woman standing behind you. She wears a long white dress, which is tied into two pieces at the waist. Her hair is brown and her eyes are blue.</p><p>&gt; “What do you want, woman?”</p><p>She smiles and says “I just wanted to thank you for helping me.”</p><p>You shrug your shoulders and reply “It wasn’t really my fault, but I’ll get right back to you.”</p><p>“Thank you!” She exclaims. “Now please let me finish thanking you!”</p><p>&gt; Ask the man if he knows of a spell to defeat Death</p><p>He looks down and sighs. He says that he doesn’t know anything about such a spell, though he does mention that you could try searching the library for something called “Death’s Bane”, which is supposed to kill Death.</p><p>You nod and say “Okay” and walk off.</p><h4><strong>Chapter 2 — Defeating Death</strong></h4><p>&gt; Search the library for “Death’s Bane”</p><p>You continue to search the library, but you don’t find anything useful either. Eventually you give up and decide to return home.</p><p>When you arrive back at the house, your grandmother greets you outside. She tells you that she was wondering when you’d come back.</p><p>&gt; Tell my grandmother about the woman with a voice much like her own</p><p>You tell her what happened and she seems surprised. She says that it’s good to hear you’re still alive after all these years, then she hugs you tightly.</p><p>&gt; “Grandmother, do you by any chance know where I can find ‘Death’s Bane’?”</p><p>Her eyes widen as she looks over at the bookcase. She turns to you and says “Oh no! How did you even… Oh, here it is.”</p><p>She pulls out a small leather-bound book and hands it to you. It’s titled “The Book of Shadows”.</p><p>&gt; Learn the “Death’s Bane” spell from “The Book of Shadows”</p><p>You open the book and read through it quickly. The first thing you notice is that it’s written in a strange language. There are many words and phrases that seem to be made up on the spot.</p><p>&gt;</p><p>Then you realize that it’s not a language at all, but rather an incantation.</p><p>There are several steps to cast this spell and each one requires a certain amount of mana. Once you’ve used up all your mana, the spell will fail and Death will win.</p><p>&gt; Calculate if I have enough mana to complete the spell</p><p>You look at your hand and find that you only have enough mana to cast the spell once. If you were to attempt to cast it again, Death would win and you wouldn’t survive.</p><p>You also note that there isn’t a lot of room for error in casting this spell.</p><p>&gt; Study the spell cautiously, for as long as it takes to learn it well</p><p>You begin to practice the incantation slowly. After a few minutes, you feel yourself getting better and better at it.</p><p>After several hours of practicing, you finally manage to cast the spell without mishap.</p><p>&gt;</p><p>As soon as you finish chanting, Death appears before you. He stares at you with his cold blue eyes and says “I’m afraid I can’t let you pass.”</p><p>You stare back at him blankly.</p><p>&gt; Tell Death that the spell should have defeated him</p><p>He nods and smiles. “Yes, yes it did. That’s why I wanted to test it on you.”</p><p>You nod and smile back. “Very good, Death.” Then you turn around and walk away from him. As soon as you leave the library, Death follows suit.</p><p>&gt; Ask Death why he is following me</p><p>Death frowns. “Why am I following you? Why aren’t you following me?”</p><p>You shrug helplessly. “Because I don’t want to get lost in this city anymore.”</p><p>Death sighs and shakes his head.</p><p>&gt; “Oh, I get it! Since I’ve defeated you now you have become my servant!”</p><p>Death scowls. “No, I haven’t! You’re just using me like some sort of pawn or something!”</p><p>You shake your head. “Nonsense, Death. I’ve never been anything other than loyal to you.”</p><p>&gt; “Well, if you’re my pawn, then do my bidding. I order you to never again take someone that does not want to die!”</p><p>Death snorts. “Perhaps, but what are you going to do about the others who want to live?”</p><p>You raise an eyebrow. “What else could they possibly do?”</p><p>Death looks down at his feet and sighs. “They… They’re dead.”</p><p>&gt; Ask Death if he can bring back the departed ones</p><p>“Of course,” Death replies. “But I need time to prepare.”</p><p>You nod and continue walking towards the castle. Death watches you go, but doesn’t try to stop you.</p><p>A month passes… A year… Two years… Three years…</p><h4><strong>Chapter 3 — Getting Philosophical</strong></h4><p>&gt; !Death appears once again, declaring that he is ready now</p><p>You stand outside the library, staring at Death. The man has grown much larger since last time you saw him. Now he stands over six feet tall and looks more like a demon than ever before.</p><p>&gt; Order Death to start the ritual — “this is the day the dead come back to the living!”</p><p>Death stares at you for a moment, before nodding. “Alright, alright, I’ll do it.”</p><p>You nod and walk inside the library. Death walks behind you and begins chanting in a language you don’t understand. Suddenly, a bright light fills the room.</p><p>&gt; !A large, fiery portal fills the floor</p><p>You scream and stumble backwards. You look up and see a huge, flaming portal appear in the center of the room. It quickly grows into a massive dragon-like creature, which slowly flies out of the portal.</p><p>It roars loudly as it approaches you, but suddenly stops moving.</p><p>&gt; !The dragon-like creature returns to the portal, and from the open hole countless souls start emerging</p><p>The dragon-like creature slowly moves back into its portal. Soon, dozens of souls begin pouring through the portal. Some of them are happy, while others seem sadder than ever.</p><p>Suddenly, one soul changes direction and starts flying straight towards you.</p><p>&gt; “Are you… my daughter?”</p><p>You stare at the soul, which seems to be looking right at you. It’s eyes are wide with fear and tears stream down its face.</p><p>“Yes…” You reply softly. “I’m your daughter.”</p><p>The soul nods, before falling to the ground in front of you.</p><p>&gt; “Are you alright?”</p><p>You kneel down beside the soul and hold her hand. She sniffles and wipes away her tears. “I’m sorry, Daddy.”</p><p>“Don’t apologize to me, sweetheart.” You smile gently at her. “We both know that this was all your father’s idea.”</p><p>&gt; Ask Death if only the willing souls have been brought back</p><p>“Only the willing have returned, yes.” Death says. “But I think we should keep doing this until everyone is back.”</p><p>You nod and turn around to leave.</p><p>&gt; Turn back and ask Death if the souls will gain their bodies back</p><p>“No, they won’t.” Death answers. “They’re just spirits now, so there isn’t any way to bring them back to life.”</p><p>You shake your head and sigh. “Well, then I guess I’ll never get to meet Mommy or Daddy again.”</p><p>&gt; “What about the living? Will they be able to go on forever, should they choose to?”</p><p>“That depends on what kind of living you mean.” Death replies. “If you mean people who aren’t undead, then no, they won’t. They can still die of old age, disease or other natural causes.”</p><p>&gt; “Ah… I see… So instead of the paradise I envisioned, the world will become a place full of the undead… I can’t imagine that will be good for the living.”</p><p>“True enough.” Death admits. “However, I believe that most people would prefer to live in a world where death is not the rule of the day. If that means living in an undead world, then so be it.”</p><p>You nod and smile at Death.</p><p>&gt; “Are you undead yourself, Death? How does it feel like?”</p><p>Death looks over at you and smiles. “I am indeed, dear child.”</p><p>You laugh and hug Death tightly. You tell him how much he has meant to you throughout your entire life.</p><p>&gt; Ask Death how does it feel like to be undead</p><p>“It feels pretty damn great, actually.” Death responds.</p><p>&gt; “How so? Do you still feel the wind? Taste the food? Or are the mundane pleasures lost?”</p><p>“Oh, yes. Yes, those things remain quite enjoyable. However, I must admit that my immortality is somewhat unnerving at times.”</p><p>You chuckle and kiss Death on the cheek. “So do you miss being human?</p><p>&gt;</p><p>Do you miss having emotions?”</p><p>“Yes, I do miss my humanity. It is one thing to lose something once you’ve gained it, but losing something that matters as much as a normal human’s feelings? That’s a different matter entirely.</p><p>&gt; “I see… It must be a requirement that immortal beings have no emotions, otherwise it would be unbearable.”</p><p>“Indeed. Perhaps that is why all gods seem to be emotionless. I suppose it makes sense that they would avoid such things.”</p><p>You shrug and continue talking with Death.</p><p>&gt; “Can we give them a choice, though? To keep their emotions or not?”</p><p>“Perhaps. I don’t know if it would work, though.”</p><p>You think about this for a moment. “Couldn’t we make them feel pain?</p><p>&gt; “That might be the only way they wouldn’t distance themselves from the living so much.”</p><p>“Pain is very real, but I doubt if it could ever truly compare to the loss of humanity. The loss of emotions would certainly be more painful, but I’m sure there would always be some small amount of joy left.”</p><p>You sigh and shake your head.</p><p>&gt; “I understand. It will be difficult to protect the living, but it must be done, otherwise this is all meaningless. Will you help me do it?”</p><p>“Of course! We’ll get through this together!”</p><p>The next few days go by quickly. You learn that the dead are capable of speech, but they tend to speak in riddles.</p><p>&gt; Ask Death why the dead speak in riddles</p><p>“Because they can’t speak for themselves, mortal. They’re too busy trying to process everything that’s going on around them. I imagine it’s very hard for them to comprehend what you just said.”</p><p>You nod and smile at Death’s words.</p><p>&gt; “Who speaks for them, then?”</p><p>“They speak for themselves, mortal. They don’t need anyone else to tell them what to do.”</p><p>You stare into Death’s eyes and try to read his mind. He seems very interested in you, which means he must really care about the living.</p><p>&gt; Start suspecting Death’s intentions</p><p>“What do you mean?”</p><p>He smiles. “Well, I’d wager that you’re wondering if I’m here to take away your life. Of course, that isn’t necessarily true either.”</p><p>You look down at yourself and back up at him.</p><p>&gt; “Death, what do you seek? Not out from me, but in general — what is your ultimate goal?”</p><p>“My goals aren’t those of a mere mortal. My goal is to serve the living, and that’s what I intend to do.”</p><p>You frown. “But why would you want to do that?”</p><p>He laughs.</p><p>&gt; “How do you serve the living?”</p><p>“By giving them happiness. Happiness is my purpose, and that’s what I’m doing.”</p><p>You pause. “So you’re saying…you’re a god?”</p><p>He nods enthusiastically.</p><p>&gt; “I should have seen that coming.”</p><p>“It was never meant to be, mortal. But now that you’ve come to realize that, perhaps you’ll see how foolish it was for you not to believe me when I first approached you.”</p><p>You sigh and shake your head.</p><p>&gt; “I’m convinced we seek the same thing, now. But I wonder if we picture it the same. What is happiness to you?”</p><p>“Happiness is to me, as air is to you. It’s something I simply take for granted.”</p><p>You nod slowly. “Then why did you bother speaking with me?”</p><p>He shrugs.</p><p>&gt; “That doesn’t answer the question. But I suppose the point is moot; we should ask everybody what is their definition of happiness instead. Don’t you agree?”</p><p>He shakes his head. “No, I don’t think so.”</p><p>You continue. “If you were a god, wouldn’t you know what happiness is?”</p><p>“Perhaps,” he says thoughtfully.</p><p>&gt; “But a mortal wouldn’t know?”</p><p>“True enough, but that doesn’t make it any less important. A mortal may live out all their days in blissful ignorance of anything beyond this world. However, a being like myself has no such luxury.”</p><p>You stand there for several minutes pondering his statement.</p><p>&gt; “I understand. To know true happiness that way one must also forfeit it, because they must give up their humanity.”</p><p>“Yes, that’s right. That’s exactly what I’m trying to convey. And yet, you still insist on clinging to your human side. How can you possibly be happy with yourself?”</p><p>You feel a pang of guilt at having said such a thing.</p><p>&gt; “You make a valid point, Death. However, I must live out my life to its natural end, and only then I’ll join the undead.”</p><p>“And what makes you think I’ll let you join me?”</p><p>You smile. “Because I love you.”</p><p>&gt;</p><p>Death smiles back. “Well, that’s good to hear.” He turns away from you and begins walking towards the door.</p><p>“Wait!” you shout, before he disappears into the darkness.</p><p><strong><em>TO BE CONTINUED…</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c606f6171358" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Model Evaluation — Part 1: Regression and Classification Metrics]]></title>
            <link>https://medium.com/@asmello/introduction-to-model-evaluation-part-1-regression-and-classification-metrics-e75179d01db?source=rss-fde0d39c9132------2</link>
            <guid isPermaLink="false">https://medium.com/p/e75179d01db</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[André Mello]]></dc:creator>
            <pubDate>Sat, 21 Jul 2018 00:23:29 GMT</pubDate>
            <atom:updated>2018-07-21T00:28:11.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Hp-roR8H1SFvbTlzxuZLg.png" /></figure><h4>This is the first part of an introductory series of articles about model evaluation. Expect some very simple, if detailed explanations.</h4><h4>Introduction and motivation</h4><p>One of the most useful skills to have, whether you are a Data Scientist yourself or someone that works with one, is to understand how to evaluate a machine learning model. There are a multitude of metrics available, several to each class of models, and which one best evaluates how well the model is going to perform in production is highly conditional to the specific problem it seeks to solve.</p><p>For example, if your goal is to classify photos as being outdoors or indoors to automate tagging in your social network, it might suffice to measure the model&#39;s accuracy — the higher the better. This measures, out of all the predictions the models make, how many are correct. If the models makes a mistake, it&#39;s not a huge deal — it would be a very bad thing if you were tagging the content and the model was to <a href="https://www.wired.com/story/when-it-comes-to-gorillas-google-photos-remains-blind/">detect black people as gorillas</a>, though.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*uk_C2AhId5Thq4VZ.jpg" /><figcaption>Not all mistakes are born equal…</figcaption></figure><p>At the same time, if you&#39;re building a model that seeks to detect a rare event — the common example being fraud detection — , accuracy is not sufficient anymore. That is because when the event is rare enough (say, it happens in 0.1% of the cases), the model will achieve a very high accuracy (say, 99.9%) by simply <em>always</em> guessing the common case. When that happens, another measure such as precision or the F1 score is needed to properly evaluate the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/0*Ksu5wdPIm0kjkxaS.png" /><figcaption>When the sample is small, it&#39;s extra important to evaluate the model properly… (from xkcd)</figcaption></figure><p>With those concerns in mind, I&#39;m starting this series of articles explaining the basics about model evaluation to help people understand which metrics are appropriate in which cases, and what they&#39;re really measuring. <strong>My goal is to make this series as accessible as possible, so layman folks can at least develop enough wisdom to be able to call when they&#39;re being bullshited at.</strong></p><h4><strong>The basics: what is even a model?</strong></h4><p>As a Data Scientist, it&#39;s easy to forget that models and algorithms are actually stuff you don&#39;t usually study at school (though that&#39;s starting to change, thankfully). So let&#39;s start by introducing those!</p><p>For all essential purposes, an algorithm is a set of fixed instructions that attempt to achieve some well defined goal. For example, a cake recipe is an algorithm, though often a very vague one. It specifies the resources you need (the input, the ingredients) and by the end you get a well defined outcome (the output, a cake).</p><p>Whether it&#39;s hot or cold, sunny or rainy, the recipe doesn&#39;t change (even though such extrinsic factors may very well end up influencing the quality of the outcome). In a controlled environment such as a computer, though, you can pretty much rely on algorithms to be deterministic (that is, to always achieve the same results), as long as they were designed so¹.</p><p>A model, in the Machine Learning context, is a step above an algorithm. Besides involving one or more inputs and outputs, it has a set of parameters that influence its behaviour². For example, if we have a single output variable <em>y</em> and a single input <em>x</em>, and they are associated by a linear relationship — that is to say, if our input changes our output should change proportionally — , our model can be the equation<em> y</em>=<em>αx</em>, with <em>α</em> being its parameter. A Data Scientist can handpick that parameter, based on some business rule or experimental trial and error, or make use of automation. Machine Learning is simply the science (and art) of automating the selection of such parameters in order to arrive at the most useful models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/0*aTdwndYxiwPSXZ_4.png" /><figcaption>Data Science is just as much art as science. (from xkcd)</figcaption></figure><p>A common misconception (even among data scientists) is that the models are mathematical representations of reality. That&#39;s not really true, however! Some models are inspired by our understanding of how things work, but all models are, at best, simplifications, and some may not have any reasonable grounding on any physical phenomenon. And yet, we use them because they allow us to do things we can&#39;t do ourselves, like sifting through millions of data samples to identify a few thousand weird trends, or using thousands of variables to make a single decision. We simply do not have the time, human resources, or sheer mental capacity, to achieve those tasks without automation.</p><blockquote>All models are wrong, but some are useful. — George Box</blockquote><h4>Regression</h4><p>Regression models are basically those which emulate a generative process that derives one or more values from a set of input variables, often in a continuous and unbounded manner. Ideally, those input variables are able to explain at least some of the output (they either cause or correlate with the output). The model will simply apply some kind of transformation on those variables to predict the desired outcome.</p><p>One simple example is using family income and education to predict future salary. Those factors certainly do influence the odds of any subject arriving at a high paying job, so they&#39;re useful information, but they obviously don&#39;t account for the full story. As such, any model taking those variables as input will necessarily have some irreducible error built into it — it simply won&#39;t have all the information necessary to make a flawless prediction.</p><p>To measure regression performance, there are a few common metrics:</p><p><strong>(R)MSE</strong></p><p>Mean Squared Error (MSE) is perhaps the most simple and common metric for regression evaluation, but also probably the least useful. It is defined by the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*3wB5otkgKEiv9X6Gdd0r2Q@2x.png" /></figure><p>where <em>yᵢ</em> is the actual expected output and <em>ŷᵢ</em> is the model&#39;s prediction. This simply sums over all the input samples <em>i</em>, taking the squared difference of the model&#39;s output and the ground-truth. The higher this value, the worse the model is. It is never negative, since we&#39;re squaring the individual prediction-wise errors before summing them, but would be zero for a perfect model (which is <strong>not</strong> to say that, if it is zero, then the model is perfect!).</p><p>The main reason this is not that useful is that if we make a single very bad prediction, the squaring will make the error even worse and it may skew the metric towards overestimating the model&#39;s badness. That is a particularly problematic behaviour if we have noisy data (that is, data that for whatever reason is not entirely reliable) — even a &quot;perfect&quot; model may have a high MSE in that situation, so it becomes hard to judge how well the model is performing. On the other hand, if all the errors are small, or rather, smaller than 1, than the opposite effect is felt: we may underestimate the model&#39;s badness.</p><p>By the way, RMSE is just the square root of MSE. It&#39;s sometimes useful to use instead because it&#39;s scaled on the same base unit as the underlying variables, so, for example, if our <em>y</em> measures salary in dollars, an RMSE of 50 amounts to an &quot;average&quot; error of 50 dollars³.</p><p><strong>MAE</strong></p><p>Mean Absolute Error (MAE) is a close cousin to MSE. It is described the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*k5yhKsvTWNUJhTFvuLQclA@2x.png" /></figure><p>which is simply the sum of the absolute sample-wise errors. If the model predicts 200 and the ground truth is 198, the error is 2. Likewise, if the prediction is 202, the error is still 2. Very simple, right?</p><p>This suffers less of the maladies that MSE suffers, since each sample error has a linear contribution to the metric, but is still far from a silver bullet, specially when our output has a very large number of dimensions. It&#39;s also somewhat inconvenient computationally, for reasons I won&#39;t get into, but that&#39;s a lesser problem nowadays.</p><p><strong>R²</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*UPdpl96JsOZs8ztB.png" /><figcaption>(from xkcd)</figcaption></figure><p>The coefficient of determination, or R² (sometimes read as R-two), is another metric we may use to evaluate a model. It is closely related to MSE, but has the advantage of being scale-free — it doesn&#39;t matter if the output values are very large or very small, the R² is always going to be between 0 and 1.⁴ ⁵</p><p>Again, it can be defined by a simple equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*iqUOveJbbKk7-DHcQ0ZOnA@2x.png" /></figure><p>The MSE of the model is computed as above, while the MSE of the baseline is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*SZVKM6G8v8veQPqmO1c2Aw@2x.png" /></figure><p>where the <em>y</em> with a bar is the mean of the observed <em>yᵢ.</em></p><p>To make it more clear, this baseline MSE can be thought of as the MSE that the <strong>simplest possible</strong> model would get. The simplest possible model would be to <em>always</em> predict the average of all samples. Our goal is to generate <em>less</em> errors relative to that model, and that&#39;s what R² measures. A value close to 1 indicates a model with close to zero error, and a value close to zero indicates a model very close to the baseline.</p><p>This metric comes from a statistical background that is beyond our scope, but it pays to know it works best when its underlying assumptions are true, which mostly means that we should be using it for linear regression.</p><h4>Classification</h4><p>Classification is the task of assigning a label to each data sample, the simplest case being that of assigning a binary value (one or zero, true or false). For example, a classification model would take a picture of an animal and tell us if it&#39;s a cat or not. It might also tell us which breed of cat it is, for a multiclass problem.</p><p>There are a multitude of ways the model might go to achieve that, but the basic idea is always the same, and is very similar to the regression case: it takes the set of input variables, applies a bunch of transformations and arrives at a discrete, categorical, answer. In fact, most classification models are really just a regression model with a decision boundary — say, if the predicted value is less than some threshold, we interpret it as zero, otherwise we take it as a one.⁶</p><p>One exception tends to be when the input variables are themselves categorical. In that case, we might apply a set of conditions, or logic rules, to arrive at an answer without going through any numerical computations. Tree models are very adept at handling these cases, plus they can handle numerical variables as well, by implicitly discretizing them. This flexibility goes a long way to explain their popularity, but they have their own limitations—they don&#39;t work well with non-structured data, like images, for one, and they can&#39;t capture causality nor ordering in sequences, for another.</p><p>Finally, when it comes to binary classification, we often choose to preserve the output as a continuous value in [0,1], which allows us to gauge, to a degree, the certainty the model has in its prediction. Some models also have the nice property of allowing us to interpret that score as a probability, under a few underlying assumptions. That enables us to say things like &quot;there&#39;s a 78.6% chance this client will default&quot;, what is very useful to help us make objective decisions.</p><p>Here are a few of the most common metrics for classification performance:</p><p><strong>Accuracy</strong></p><p>Accuracy is the simplest, most common and perhaps most intuitive metric for classification models. It evaluates, out of all the predictions the model makes, how many are correct. This translates into the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*kgb_HR4vNT5mGdiNl7HWEg@2x.png" /></figure><p>This metric is so intuitive and natural, in fact, that people often use it without a second thought, even though it&#39;s certainly not appropriate in many cases. As I&#39;ve mentioned earlier, if one class is much more common than the other, this metric says very little about how well the model will predict the less common case. Plus, if we have a multiclass problem, what this is measuring is not so easy to interpret.</p><p><strong>Recall</strong></p><p>Say we are trying to build a model to predict which people will become criminals, <a href="https://en.wikipedia.org/wiki/The_Minority_Report">Minority Report</a>-style, for the 2020 Olympics. Which is not <a href="https://www.japantimes.co.jp/news/2018/01/29/national/crime-legal/kanagawa-police-launch-ai-based-predictive-policing-system-olympics/#.WzjW39j0nOQ">as far fetched</a> as one might think.</p><p>In this situation, there is a very small number of positive cases — thankfully, only a small part of the population has any chance of commiting a serious crime during the Olympics. So accuracy is out of the question — if we have a model that says that no one will commit a crime, we’ll have an overwhelmingly high accuracy, but that model is useless. What should we measure instead?</p><p>There are two kinds of error we might make when performing a prediction: either we have a false-positive, or a false-negative. In the former case, we will trigger a more detailed investigation by the police, which costs money and human resources, but as long as we can afford that, there’s no serious consequence for making a mistake. Worst case, we end up taking someone into custody before we can verify their innocence, which is bad, but still affordable (unless it’s someone very important… But that’s where human judgment comes forward).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*UALSBReViD9zjBhB.jpg" /></figure><p>If we make a mistake of the latter kind, though, that&#39;s much more serious. It means we missed someone that will, in fact, do something serious, maybe even a terrorist attack. That we wish to avoid as much as possible, so we choose a model that optimizes for recall. Here&#39;s the equation for recall:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*siGAAWal9_vQV6Df1wofCA@2x.png" /></figure><p>What this measures is, out of all the positives <em>that exist</em>, how many did the model <em>identify</em>. Notice that if the model always predicts a positive, it will have a recall of 100%, even if the positive case is only true for 0.000001% of all people. However, if the accuracy is very high but the recall is low, we know that the model is bad for our application.</p><p>In a way, recall measures how sensitive the model is for positive cases. Ideally, we want our model to capture all positive cases, and still be discriminative enough to keep the suspect pool small. As long as we have enough resources to afford the follow up investigations, it&#39;s alright if we pick a few extra people as suspects.</p><p><strong>Precision</strong></p><p>Precision is the flip-side of recall, and easy to confuse with accuracy. It measures, out of all the <strong>positive</strong> predictions the model made, how many were correct. Its equation is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*_0c5tVSijWdmbdHF2vkGZQ@2x.png" /></figure><p>Precision is important when we have a rare positive, but it costs too much to pursue false-positives. One clear example is a company that wishes to advertise their product via email. If the recipient likes what they see, they&#39;ll buy the product and feel positively towards the company — it creates a sense of trust and bonding; the client will feel like the company knows what they really want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*6l1LE6JLPTIckvIc.gif" /></figure><p>On the other hand, if the recipient doesn&#39;t like any of what they see, they&#39;ll feel irritated by the email. And if that happens often enough, the user will cancel their subscription, making the company lose their advertisement channel, what likely translates into a loss of a client. That is a serious consequence. It doesn&#39;t matter if the company doesn&#39;t send a lot of emails, it&#39;s much more important that the ones that they do send are appropriate.</p><p>That&#39;s where precision comes in. It&#39;s a filter that allows us to select the models that make as little false-positive mistakes as possible. A high precision means that when we say we have a positive case, you better trust us. As with recall, however, a precision of 100% might not mean much by itself; if we make a single correctly positive prediction when we had thousands or millions of positive cases we could&#39;ve identified, that model is <em>probably</em> bad.</p><p><strong>F1 score</strong></p><p>Precision and recall are two sides of a coin, so it pays to look at both at the same time — and sometimes overall accuracy as well. We often have a tradeoff to balance; the more we improve our precision, the lower our recall, and vice-versa. Sometimes, though, it&#39;s possible to improve both metrics at the same time, which is <em>always</em> a good thing. One common way to compare models for <strong>overall goodness</strong>, when accuracy is not appropriate, is to use the F1 score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*FiZBPDTPUl0AMSjIllyRpQ@2x.png" /></figure><p>F1 is nothing complicated. It&#39;s just the harmonic mean of precision and recall. We could use a simple arithmetic mean or any other combination of both metrics, but the harmonic mean has the nice property that if one metric is much lower than the other, it brings the F1 score way down. We usually don&#39;t want either recall or precision to be too low, specially since either being very high doesn&#39;t tell us much about how well the model is performing overall.</p><h4>Wrapping Up</h4><p>So far we&#39;ve seen some of the most common model evaluation metrics, for both regression and classification models. That said, there&#39;s a lot left unsaid, specially about clustering and more specialized types of models. Still, I hope this (not so brief) introduction has helped form a solid intuition as to the main measures of goodness out there.</p><p>I plan to write more in the future about other useful metrics, and eventually delve into the more &quot;unsolved&quot; aspects of this field of study. For that purpose, I will appreciate any feedback! I know I&#39;ve made this article a bit more detailed than would be usual, but I don&#39;t like leaving things too vague, specially when we&#39;re talking about such fundamental concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/0*HgKQCCY21j8BAK31.png" /><figcaption>Thankfully we can learn to prevail. (from xkcd)</figcaption></figure><p><strong>Footnotes</strong></p><p>¹ In reality, ordinary computers are completely deterministic, except for user input or other external sources of randomness. Most of the perceived randomness you may encounter comes from pseudo-random number generators, which actually just apply complicated but deterministic formulas to generate superficially random outputs.</p><p>² There are so-called non-parametric models, but in truth, those use the data itself as their parameters.</p><p>³ The actual interpretation is more complicated. The RMSE is equivalent to the standard deviation of the variable, assuming it follows a normal distribution. Otherwise its precise meaning is usually not clear, but we can always think of it as a proxy for global error on the same unit of the variable.</p><p>⁴ Unfortunately, R² is actually sensitive to scale when the spread of output values is very wide — that is, some values are very small, like 0.2 and 4.6, while some are very large, like 2096342 and 9987012. In that case, the metric will fail to capture mistakes with the smaller values, and instead prioritize the larger ones. Often, a simple fix is to change the target variable to logarithmic scale.</p><p>⁵ It’s actually possible to have a negative R², if the model is so bad it performs <em>worse</em> than the baseline. Needless to say, if that happens there’s something very wrong with your model.</p><p>⁶ If we have more than one class, a common solution is to transform it into a bunch of one-versus-all binary classification problems and take a vote. The main reason we don&#39;t simply encode our classes as integers, rounding off the regression result to the nearest integer, is that this enforces an ordering and distance among the classes, which is most often not desirable.</p><p><em>The title image includes icons by by Luca Fruzza, Tomas Knopp and SBTS from the Noun Project.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e75179d01db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Linear Algebra - Part  1: Estimating Route Costs]]></title>
            <link>https://medium.com/@asmello/exploring-linear-algebra-part-1-estimating-route-costs-cc156d00e2bc?source=rss-fde0d39c9132------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc156d00e2bc</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[André Mello]]></dc:creator>
            <pubDate>Sun, 13 May 2018 16:46:38 GMT</pubDate>
            <atom:updated>2018-05-13T16:46:38.068Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cywYfz0CC31dlH7g9irOQ.png" /></figure><h3>Exploring Linear Algebra — Part 1: Predicting Route Costs</h3><p><em>This is my first entry in a series of articles with creative applications of linear algebra to problems. This one was inspired by an Uber ride.</em></p><p>So, imagine you are Google Maps, and your client wants to know the best path to take from point A to point B. If you have the city’s map, it’s easy, right? Just wearily apply Dijikstra’s algorithm to find the shortest path, and that’s your answer. Or maybe not.</p><p>If you’ve taken enough Uber rides, you know that sometimes the shortest path also happens to be the one under worst maintenance, or maybe it’s the most jammed up. If, like me, you live in a city scantily decorated with clusters of poverty and crime, there are paths you want to avoid at all costs. Several environmental factors, which may vary according to weather, time of the day and occasion will influence the ride’s duration, so more than just geographic distance should be taken into consideration when searching for the optimal route.</p><p>The Waze app does planning smartly. It crowdsources additional markers, like accidents, radar guns and asphalt holes. It uses the client’s GPS to estimate speed, and uses that to derive traffic intensity. It’s for good reason Uber and taxi drivers alike rely on that app so much to navigate chaotic cities like São Paulo. But I’ve found that it often favors a road in bad shape or in a dangerous location, simply because it’s a little bit faster to go through it.</p><p>What could be made better? It seems ride duration is not the only variable that should guide the decision algorithm. We could artificially introduce other variables and markers and weight their relative importance, but ultimately that would fail to generalize — different cities and different people imply different priorities. I feel it would be more robust, scalable and elegant to derive a cost function implicitly, from simple user feedback. Would that be possible?</p><p>If I had a definitive answer, I would be selling it to Google, but it turns out there’s a simple and quite educational approach we might explore. It just involves a little bit of Linear Algebra.</p><h3>Articulating the problem</h3><p>Suppose all the information you have is a map, a series of paths along it and their respective lengths (or, more generally, costs). Your goal is to assign values to each individual path segment, so that you can easily estimate a new path’s cost by summing up the cost of its parts. If you represent the map as a directed graph (roads might only go one way), and each intersection, merger or split as a vertex, your edges become the segment units and any path is simply an ordered sequence of visited vertices (or, alternatively, traversed edges).</p><p>To put it a little more formally, you are given a weighted digraph <em>G</em> = (<em>V</em>, <em>E</em>), associated with an unknown function <em>w</em>(<em>e</em>) : <em>e</em> ∊ <em>E </em>⇾ ℝ⁺, as well as a collection of tuples <em>pᵤ =</em>({<em>eᵥ</em>}<em>ᵤ</em>,<em> cᵤ</em>), with <em>eᵥ</em> ∊ <em>E</em> and <em>cᵤ</em> ∊ ℝ⁺, and the objective is to reconstruct <em>w</em>(<em>e</em>). If we enumerate each <em>w</em>(<em>eᵥ</em>) as <em>wᵥ</em>, from our paths {<em>pᵤ</em>} we may derive a system of equations as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*dfcTB_lIOm4DI_deO0o72Q@2x.png" /></figure><p>where x<em>ᵤᵥ</em> is defined by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*3EOEgTdsMc0Wl8DGYaTowg@2x.png" /></figure><p>If you like, this can be rewritten as <em>X</em><strong><em>w</em></strong>=<strong><em>c</em></strong><em>. </em>We know how to solve that exactly as long as rank(<em>X</em>) = <em>m</em>. If that’s not the case, we may still find an approximation. This is already a reasonable solution for our problem, as long as our <em>c</em> are exact, but that is hardly possible in real life.</p><p>For a more realistic model, we may assume our pathwise measures of <em>c</em> are perturbed by some random noise, say <em>cᵤ</em> ∼𝓝(<em>μᵤ</em>, <em>σᵤ</em>). In that case the rank precondition is not sufficient, and we may only derive an approximation to the solution, by minimizing the error ‖<em>X</em><strong><em>w</em></strong>-<strong><em>c</em></strong>‖.</p><h3>A toy example</h3><p>It always helps to walk through an example. Suppose we work at a consulting firm on Big Data, called Large Data, and the Happy Mayor of the cozy town of Zizgy is our client.</p><p>The inhabitants of this town all have a map, which the Mayor happily distributes as fancy fliers that he spreads all over, from his helicopter, every month. People always complain about the mess, but the Mayor’s mysterious smile always catches them off guard, and they always end up forgiving him.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*TQDVDrTWUaylnUYJBnCBNg@2x.png" /><figcaption>The somewhat surreal map of Zizgy!</figcaption></figure><p>It was all good around Zizgy for a while, until Uber came over and started claiming that the map was incomplete and its drivers did not know the shortest routes to take, what was increasing client dissatisfaction. The Mayor had never thought to measure the road lengths, and when he tried he found out his ruler wasn’t long enough to cover even the smallest of them. Luckily, Uber had given him their data, as evidence of how inconsistently drivers chose how to get from one point to another. So naturally he sought our firm’s expertise to make good use of that Data, which he thought was very Big.</p><p>That data included complete information on the path taken for each ride, as well as total charge. Since there was a well defined, publicly available ride fare policy, we could estimate the total distance traveled from the price. And since the road network could be represented as a graph, we figured this was an edge weight recovery problem!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*IerRRMgAHknxowQHadcUGg@2x.png" /><figcaption>Graph representation of the map.</figcaption></figure><p>After constructing the road graph as illustrated above, the encoded paths became</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*maI1P4zqQXDdZjJpbsU5aA@2x.png" /></figure><p>. If (0,1)=<em>e₀</em>, (1,2)=<em>e₁</em>, (1,5)=<em>e₂</em>, (2,1)=<em>e₃</em> and so on (in lexicographical order), the indicator matrix <em>X</em> becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*uuBeVCWvYnURgYKGNJRNYw@2x.png" /></figure><p>With <em>X</em> and <strong><em>c</em></strong>, we can then approximate <strong><em>w</em></strong> with the least squares method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*nKHwiEKmSd6exm18iTiRQA@2x.png" /></figure><p>The residuals X<strong><em>w</em></strong>-<strong><em>b</em></strong> have a standard deviation of about 0.65, which seems reasonable — the values are distinct enough that this is already useful for finding the shortest paths. We deliver this result to the Mayor, who smiles at our competence.</p><p>As he was updating the town’s map with the length estimates, however, his secretary tells him that she found the true measurements on an old archived map from his predecessor. The townsfolk become unhappy when they hear that the Mayor has spent money on a consulting contract unnecessarily, but they warm up at his delightful smile as he showers the town with the new maps. All’s well that ends well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*EBKdK3oqcQAfydVuaGcypQ@2x.png" /><figcaption>Actual graph and lengths for Zizgy’s roads.</figcaption></figure><p>As it turns out, our estimates were off by an average of 0.53 units, though for road 0–1 we had a whopping error of 1.33!</p><p>Notice that, in this example, we could’ve improved our estimates by taking advantage of the fact that the two-sided roads like 2–5 are symmetrical — they’re the same length from 2 to 5 and from 5 to 2. I left both directions as separate unknowns to illustrate the more general framework, under which we are approximating some abstract cost measure that may depend on which direction one travels (for example, traffic congestion might be more intense on one direction or the other).</p><p>In case you are wondering, that ride data was generated by picking random paths within the graph, and computing the total length with added noise <em>ε</em>∼𝓝(0, 1). Given sufficient data, we might have been able to guess the error distribution, and we would’ve been able to take a bayesian approach to have much better estimates of the lengths.</p><h3>Coding a simulation</h3><p>Now that we’ve walked through an example, I thought it would be interesting to explore an implementation of this modelling framework using TensorFlow. The reason I chose TF was because I wanted to show how it could be useful for general machine learning, outside of Deep Learning. This choice also enables online learning, with which new data is gradually generated and learned from. This more closely resembles a production-ready real world implementation.</p><p>First, here’s the code I used to generate a single random path from an adjacency matrix:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9894c64998cad1dbbc4b32ab1b3f902/href">https://medium.com/media/b9894c64998cad1dbbc4b32ab1b3f902/href</a></iframe><p>Here’s an example of the kind of adjacency matrix this code expects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*6mJexl7DOq_BmOcEu9o7_A@2x.png" /></figure><p>In this format, every non-zero element represents an edge, and its value represents the edge’s weight. The parameter σ controls the standard deviation of the noise added to the total distance, and α controls the chance of revisiting a vertex.</p><p>This last parameter was added to model rides where the driver makes a mistake and creates a loop in his path. If α = 0, <em>X</em> is as defined before — an indicator matrix that encodes which vertices were visited in each ride. If α &gt; 0, then it encodes how many times each vertex was visited. Either way, the equation <em>X</em><strong><em>w</em></strong>=<strong><em>c</em></strong> doesn’t change, nor does our method for solving it. Just make sure α &lt; 0.5, otherwise the algorithm has a good chance to cause a stack overflow for trying too many cyclic paths.</p><p>One thing to note is that, since our solver doesn’t necessarily know in advance which edges exist in the graph, we encode our <em>X</em> as a |<em>V</em>|×|<em>V</em>|× <em>n</em> tensor <strong><em>x</em></strong>, which is able to model even a fully dense digraph with self-loops (not that this makes sense given our interpretation of it as a map). Our solution for <strong><em>w</em></strong> is actually the same matrix as Adj. Under this structure, the problem equation is actually <strong><em>x</em></strong>:<strong><em>w</em></strong>=<strong><em>c</em></strong>, with the double-dot operator denoting tensor double contraction, but this is really just the same thing as representing <em>X</em> as a |<em>V</em>|²× <em>n</em> matrix with rows as the flattened hit matrices from walk().</p><p>Here’s the rest of the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/215bd8581d86d70d7bb4e24a1589ad1a/href">https://medium.com/media/215bd8581d86d70d7bb4e24a1589ad1a/href</a></iframe><p>This creates a Dataset object (that generates random paths on-the-fly), defines the adjacency matrix, defines the computation graph and executes some 5000 training iterations (with each iteration applying a single path).</p><p>Here’s the final weights I got by running the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*TrpyHAj80gPWQ5GS3fvd_w@2x.png" /></figure><p>This has a Mean Squared Error (relative to the true weights) of about 0.85. Not a great result, specially since 5000 paths is a lot of data for such a small graph.</p><p>Since the paths always have some random noise added to them, the weights never actually converge to a fixed value, but keep on oscillating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*uyWWZkDdjsoqageeXnA4NQ.png" /><figcaption>Weights histogram throughout iterations.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdIWfBEWUKbxpDpKIAJpfw.png" /><figcaption>Evolution of the loss over training.</figcaption></figure><p>For reference, if there’s no noise in the data, the weights do converge to the exact solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*eur--wTIxm3xT4UYg-ReCA.png" /><figcaption>Evolution of the loss over training for noiseless data.</figcaption></figure><p>We can take advantage of the weight oscillations to estimate a probability distribution over their values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCefoOLZhE6x_q1aXS7yJw@2x.png" /><figcaption>Derived from the later 50% iterations from a total 100000.</figcaption></figure><p>By taking the average of the weights over a large number of iterations (i.e. 50000), we can better estimate their true values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*GdbaoyU8rHLjtNFGV8k7OQ@2x.png" /></figure><p>This result has a MSE of about 0.04.</p><p>Additionally, batching does a great job at reducing variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NoXaI1ZNJgk7zfSImQj-w.png" /><figcaption>Loss evolution with batches of 50 paths.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8w1nb9qpN3xqpyrChwyRQ@2x.png" /><figcaption>Derived from the later 50% iterations from a total 2000, with batches of 50 paths.</figcaption></figure><p>By combining both techniques, we can get arbitrarily close to the true values. We can also reuse samples to save on training data and possibly learn faster. Note that if the true weights are not time-stationary, we should constrain our training data and weight averages to some recent window. Otherwise, the more we accumulate, the better.</p><p>You can look at the full code over at <a href="https://gist.github.com/asmello/1c07171cf6385efa77499570e57a323d">this</a> notebook.</p><h3>Final thoughts</h3><p>After all this, it’s worth taking a step back and looking at the big picture. I’ve given an example where our goal was to estimate road lengths, so we could find shortest paths as we wish, but in reality road lengths are often known to adequate precision, and aren&#39;t the best cost to minimize. I propose not to optimize just distance or duration, but some implicit cost function that depends on the environment and the user. This function is expected to highly correlate with the duration for each ride, but may also depend on factors that we cannot always measure directly, such as road condition, temporary detours and neighbourhood.</p><p>Say we ask the user to rate their ride each time, in a scale of 1 to 5, separately from their driver. That score can be used to derive an implicit cost sample. There is a number of ways to estimate future costs from this feedback, but perhaps the simplest one is to assume that, for each user, cost is a fixed function of the path alone, and assign weights to each road segment. Even if those weights are not really fixed over time, our online learning approach should be able to adapt accordingly. At the very least, this is a starting point for more complex and contextual approaches.</p><p>I hope you’ve enjoyed this article, and since I’m a Medium newbie, I appreciate any feedback. I’ve got a few ideas for future entries, but I’d love to hear some suggestions as well!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc156d00e2bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install Tensorflow + CUDA 9.1 into Ubuntu 18.04]]></title>
            <link>https://medium.com/@asmello/how-to-install-tensorflow-cuda-9-1-into-ubuntu-18-04-b645e769f01d?source=rss-fde0d39c9132------2</link>
            <guid isPermaLink="false">https://medium.com/p/b645e769f01d</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[André Mello]]></dc:creator>
            <pubDate>Sun, 06 May 2018 15:01:23 GMT</pubDate>
            <atom:updated>2018-08-25T22:18:06.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Abp9GnSEWeszgix0Cxc9_A.png" /></figure><p><em>If you&#39;re like me, you&#39;re always itching to try out the latest versions of whatever software you use. Sadly, that often means figuring out how to iron out a few kinks to get things to mix and match. Here&#39;s a guide to help you prepare your shiny new Ubuntu for deep learning.</em></p><h4>The audience</h4><p><strong>This guide is for those who need to get the most of their Nvidia-based hardware. I assume you have a fresh install of Ubuntu 18.04. </strong>If you are just playing around and won&#39;t need to use your GPU, you&#39;re probably better off installing the pip package instead. If you are an AMD person, instead of CUDA you need to use SYCL (OpenCL), but I can&#39;t help much with that.</p><h3><strong>Installing CUDA: good news, bad news</strong></h3><p>So, the first thing you should try is to install the <strong>tensorflow-gpu </strong>pip package, as described in the official <a href="https://www.tensorflow.org/install/install_linux">install guide</a>. That has never worked for me, though, so I&#39;ll only show how to <a href="https://www.tensorflow.org/install/install_sources">install from source</a>. This has the added advantage that the compiled binaries will take advantage of all optimizations your machine supports.</p><p>If you follow the official guide to installing Tensorflow <a href="https://www.tensorflow.org/install/install_sources">from source</a>, you&#39;ll notice they recommend using CUDA 9.0. Now, if your Ubuntu was 17.04 — the latest officially supported version — then you should indeed stick with the 9.0 version from the archives. In that case the prebuilt pip package will likely work. But since your OS is not supported anyway, there&#39;s no point in not using the latest CUDA, which right now is 9.1.</p><p><strong>The good news is that Ubuntu 18.04 has added CUDA to its multiverse repository. </strong>That means you don&#39;t need to mess around with adding third-party repositories and all the inevitable version clashes that come with it. You can simply install everything using apt:</p><pre>sudo apt install nvidia-390 nvidia-cuda-toolkit libcupti-dev gcc-6 python3-numpy python3-dev python3-pip python3-wheel</pre><p>This will install the (currently) latest graphics driver, CUDA itself, CUPTI, which for some reason doesn&#39;t ship with the CUDA package as it should, GCC version 6, which is the latest compatible for compiling CUDA code, and a bunch of Python 3 development essentials. If, for some weird reason, you need to use Python 2, just omit the 3 in python3.</p><p><strong>The bad news is that, because it has become a native package, CUDA is installed in a rather non-standard way.</strong></p><p>I can’t blame either Nvidia or Canonical. The Nvidia way was the best, most self-contained way, to keep consistency across different distros. It made it easy for third-party dependencies to look for CUDA, and to folks with non-standard distros to retain compatibility. Everything was put under the /usr/local/cuda-*.* path, so it was easy to maintain versions without relying on a package manager.</p><p>But that’s not how native packages work; because they can rely on the package manager’s control, they are installed into the root system paths: /usr/bin, /usr/include,/usr/lib. Imagine if each new package would append to the <em>PATH</em> and <em>LD_LIBRARY_PATH</em> environment variables. Looking for binaries, headers and libraries would soon become slow and prone to obscure namespace issues. This standard makes it easy for all tools to know where to look for their dependencies, but is only viable because the package manager tracks which packages installed which files. It’s a human-friendliness/scalability tradeoff.</p><p>Tensorflow will probably eventually update its configuration tool to work with this new installation format, but meanwhile we need to emulate the old way for it to work. The following commands should do the trick:</p><pre>sudo mkdir -p /usr/local/cuda /usr/local/cuda/extras/CUPTI /usr/local/cuda/nvvm<br>sudo ln -s /usr/bin /usr/local/cuda/bin<br>sudo ln -s /usr/include /usr/local/cuda/include<br>sudo ln -s /usr/lib/x86_64-linux-gnu /usr/local/cuda/lib64<br>sudo ln -s /usr/local/cuda/lib64 /usr/local/cuda/lib<br>sudo ln -s /usr/include /usr/local/cuda/extras/CUPTI/include<br>sudo ln -s /usr/lib/x86_64-linux-gnu /usr/local/cuda/extras/CUPTI/lib64<br>sudo ln -s /usr/lib/nvidia-cuda-toolkit/libdevice /usr/local/cuda/nvvm/libdevice</pre><p>Note: this guide assumes you’ve got a 64 bit system (<em>very</em> likely).</p><h4>Why not do it the traditional way?</h4><p>You might be wondering, why stick with the multiverse package when the Nvidia-provided one is so much easier to deal with? Well, the main reason is that the Nvidia package simply does not work with the new Ubuntu, because of version clashes with some packages, in particular the graphics driver. When I tried to it that way I ended up with a broken Ubuntu and had to reinstall it from scratch. Despite the additional work it requires, though, the multiverse package is actually quite up-to-date and should cause less headaches long-term, since it doesn’t rely on Nvidia’s care as much.</p><h4>Installing additional Nvidia libraries</h4><p>Tensorflow also depends on <a href="https://developer.nvidia.com/cudnn">cuDNN</a> and <a href="https://developer.nvidia.com/nccl">NCCL</a>, both of which you can download from the Nvidia website. I’ve had success using the (currently) latest versions, 7.1 and 2.1.15.</p><p>To install cuDNN, simply copy the files over to the /usr/local/cuda directory you created. Assuming you’ve extracted the .tgz into your Downloads folder:</p><pre>cd ~/Downloads/cudnn-9.1-linux-x64-v7.1/cuda<br>sudo cp include/* /usr/local/cuda/include/<br>sudo cp lib64/libcudnn.so.7.1.4 lib64/libcudnn_static.a /usr/local/cuda/lib64/<br>cd /usr/lib/x86_64-linux-gnu<br>sudo ln -s libcudnn.so.7.1.4 libcudnn.so.7<br>sudo ln -s libcudnn.so.7 libcudnn.so</pre><p><em>EDIT: As per </em><a href="https://medium.com/@ianjasonmin"><em>Ian Jason Min</em></a><em>’s comment, I’ve updated this segment, which actually wasn’t correct because symbolic links don’t mix up with actual directories. Sorry about that. On the plus side, I took this opportunity to make some files into symbolic links, which saves about 600MB of space (this also avoids a warning with apt).</em></p><p>This will actually copy them over to the root system paths, which is not ideal because they won’t be tracked by any package manager, but they’re just a few self-contained files, so we can live with that. If you have a more robust procedure in mind, feel free to comment.</p><p>To install NCCL, you need a little more work:</p><pre>sudo mkdir -p /usr/local/cuda/nccl/lib /usr/local/cuda/nccl/include<br>cd ~/Downloads/nccl_2.1.15-1+cuda9.1_x86_64/<br>sudo cp *.txt /usr/local/cuda/nccl<br>sudo cp include/*.h /usr/include/<br>sudo cp lib/libnccl.so.2.1.15 lib/libnccl_static.a /usr/lib/x86_64-linux-gnu/<br>sudo ln -s /usr/include/nccl.h /usr/local/cuda/nccl/include/nccl.h<br>cd /usr/lib/x86_64-linux-gnu<br>sudo ln -s libnccl.so.2.1.15 libnccl.so.2<br>sudo ln -s libnccl.so.2 libnccl.so<br>for i in libnccl*; do sudo ln -s /usr/lib/x86_64-linux-gnu/$i /usr/local/cuda/nccl/lib/$i; done</pre><p><em>EDIT: Once again</em> <a href="https://medium.com/@ianjasonmin"><em>Ian Jason Min</em></a><em> saved the day and pointed out a couple of missing details in the above segment.</em></p><p>This will also install into the root paths, but, again, shouldn’t be a big deal. I’ll show a few commands to undo all of this later on.</p><p><strong><em>One last thing I should comment is that Tensorflow can also use TensorRT to speed up inference, but I couldn’t make it work with this setup. The configuration tool complains about some version incompatibility I couldn’t resolve. If someone figures it out, I’ll update this section.</em></strong></p><h3>Installing Bazel</h3><p>The official guide recommends installing Bazel with the binary installer, but I actually think the custom repository is easier and better — it will keep things updated. <a href="https://docs.bazel.build/versions/master/install-ubuntu.html#install-on-ubuntu">These instructions</a> are easy enough to follow, but I’ll just copy them here for your convenience:</p><pre>sudo apt install openjdk-8-jdk<br>echo &quot;deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8&quot; | sudo tee /etc/apt/sources.list.d/bazel.list<br>curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add -<br>sudo apt update &amp;&amp; sudo apt install bazel</pre><h3>One more thing</h3><p>The configuration script assumes there’s a python binary in your environment. By default, Ubuntu 18.04 does not come with Python 2 anymore, but the Python 3 binary is called python3. To resolve this issue, I like to use update-alternatives:</p><pre>sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 100 --slave /usr/bin/pip pip /usr/bin/pip3</pre><p>This way whenever you call python you get Python 3. 😊</p><p>Note that if you ever install Python 2, python will continue to point to Python 3. Python 2 will be accessible via python2.</p><h3>Installing Tensorflow</h3><p>Now, we can finally move on to the good stuff.</p><p>First, clone the Tensorflow repository:</p><pre>git clone <a href="https://github.com/tensorflow/tensorflow">https://github.com/tensorflow/tensorflow</a><br>cd tensorflow</pre><p>However, unlike what’s recommended in the official guide, you should stick with the master branch. The latest release (right now) is 1.8, and it has a bug that prevents some code from compiling with GCC 6. Apparently the official build is compiled with GCC 4.8, which is why they made an apparently broken release.</p><p>Anyway, the fix has been merged into master, so it should compile fine. In case you run into issues, I built it at commit <em>#d0f5bc1</em> (there have been a lot of newer commits already, some of which may break something).</p><p>The next step is to run the configuration tool with ./configure. Here’s my inputs:</p><pre>You have bazel 0.13.0 installed.<br>Please specify the location of python. [Default is /usr/bin/python]: /usr/bin/python3</pre><pre>Found possible Python library paths:<br>  /usr/local/lib/python3.6/dist-packages<br>  /usr/lib/python3/dist-packages<br>Please input the desired Python library path to use.  Default is [/usr/local/lib/python3.6/dist-packages]</pre><pre>Do you wish to build TensorFlow with jemalloc as malloc support? [Y/n]: y<br>jemalloc as malloc support will be enabled for TensorFlow.</pre><pre>Do you wish to build TensorFlow with Google Cloud Platform support? [Y/n]: n<br>No Google Cloud Platform support will be enabled for TensorFlow.</pre><pre>Do you wish to build TensorFlow with Hadoop File System support? [Y/n]: n<br>No Hadoop File System support will be enabled for TensorFlow.</pre><pre>Do you wish to build TensorFlow with Amazon S3 File System support? [Y/n]: n<br>No Amazon S3 File System support will be enabled for TensorFlow.</pre><pre>Do you wish to build TensorFlow with Apache Kafka Platform support? [Y/n]: n<br>No Apache Kafka Platform support will be enabled for TensorFlow.</pre><pre>Do you wish to build TensorFlow with XLA JIT support? [y/N]: y<br>XLA JIT support will be enabled for TensorFlow.</pre><pre>Do you wish to build TensorFlow with GDR support? [y/N]: n<br>No GDR support will be enabled for TensorFlow.</pre><pre>Do you wish to build TensorFlow with VERBS support? [y/N]: n<br>No VERBS support will be enabled for TensorFlow.</pre><pre>Do you wish to build TensorFlow with OpenCL SYCL support? [y/N]: n<br>No OpenCL SYCL support will be enabled for TensorFlow.</pre><pre>Do you wish to build TensorFlow with CUDA support? [y/N]: y<br>CUDA support will be enabled for TensorFlow.</pre><pre>Please specify the CUDA SDK version you want to use, e.g. 7.0. [Leave empty to default to CUDA 9.0]: 9.1</pre><pre>Please specify the location where CUDA 9.1 toolkit is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:</pre><pre>Please specify the cuDNN version you want to use. [Leave empty to default to cuDNN 7.0]: 7.1</pre><pre>Please specify the location where cuDNN 7 library is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:</pre><pre>Do you wish to build TensorFlow with TensorRT support? [y/N]: n<br>No TensorRT support will be enabled for TensorFlow.</pre><pre>Please specify the NCCL version you want to use. [Leave empty to default to NCCL 1.3]: 2.1.15</pre><pre>Please specify the location where NCCL 2 library is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:/usr/local/cuda/nccl</pre><pre>Please specify a list of comma-separated Cuda compute capabilities you want to build with.<br>You can find the compute capability of your device at: <a href="https://developer.nvidia.com/cuda-gpus">https://developer.nvidia.com/cuda-gpus</a>.<br>Please note that each additional compute capability significantly increases your build time and binary size. [Default is: 3.5,5.2]5.2</pre><pre>Do you want to use clang as CUDA compiler? [y/N]: n<br>nvcc will be used as CUDA compiler.</pre><pre>Please specify which gcc should be used by nvcc as the host compiler. [Default is /usr/bin/x86_64-linux-gnu-gcc-7]: /usr/bin/gcc-6</pre><pre>Do you wish to build TensorFlow with MPI support? [y/N]: n<br>No MPI support will be enabled for TensorFlow.</pre><pre>Please specify optimization flags to use during compilation when bazel option &quot;--config=opt&quot; is specified [Default is -march=native]:</pre><pre>Would you like to interactively configure ./WORKSPACE for Android builds? [y/N]: n<br>Not configuring the WORKSPACE for Android builds.</pre><pre>Preconfigured Bazel build configs. You can use any of the below by adding &quot;--config=&lt;&gt;&quot; to your build command. See tools/bazel.rc for more details.<br> --config=mkl          # Build with MKL support.<br> --config=monolithic   # Config for mostly static monolithic build.<br>Configuration finished</pre><p><strong>Noteworthy points:</strong></p><ul><li>Python path: /usr/bin/python3</li><li>GCC path: /usr/bin/gcc-6</li><li>NCCL path: /usr/local/cuda/nccl</li><li>Check you latest CUDA compute capability.</li></ul><p><em>NOTE: It has been reported that the newer commits require Keras to compile. Although this looks like a screwup by some dev, for now it’s best to avoid the issue and install Keras first:</em></p><pre>pip install keras</pre><p>Now, to compile, just run</p><pre>bazel build --config=opt --config=cuda //tensorflow/tools/pip_package:build_pip_package</pre><p><em>Note: if you get an error like </em><em>&quot;C++ compilation of rule ‘@double_conversion//:double-conversion’ failed&quot; , then it might be useful to pass the additional argument of </em><em>--cxxopt=&quot;-D_GLIBCXX_USE_CXX11_ABI=0&quot;.</em></p><p>This step will probably take a long time. After it finishes, if all goes well, you can build the tensorflow package with</p><pre>bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg</pre><p>and to install</p><pre>pip install /tmp/tensorflow_pkg/tensorflow*.whl</pre><p>Check if your build is working by changing into another directory (cd) and running python:</p><pre>import tensorflow as tf<br>hello = tf.constant(&#39;Hello, Tensorflow!&#39;)<br>sess = tf.Session()<br>print(sess.run(hello))</pre><p>You should get Hello, Tensorflow! as an output.</p><h3>How to undo this</h3><p>As much as you may have felt spooked by some commands, there’s not much damage being done to your system if you follow this guide. If you run into issues and wish to undo everything CUDA-related so you can restart from scratch or try something else, just run the following lines:</p><pre>sudo rm /usr/include/nccl.h /usr/include/cudnn.h /usr/lib/x86_64-linux-gnu/libnccl* /usr/lib/x86_64-linux-gnu/libcudnn*<br>sudo rm -r /usr/local/cuda<br>sudo apt remove nvidia-cuda-toolkit libcupti-dev gcc-6</pre><p>You may wish to omit the nvidia-390 bit, since it’s usually a good idea to have the proprietary driver whether you are using CUDA or not.</p><p>To uninstall the Tensorflow package, use pip:</p><pre>pip remove tensorflow</pre><h3>Closing remarks</h3><p>If all went well, you now have an extremely optimized cutting-edge build of Tensorflow installed in your Ubuntu 18.04. Only thing that could make it faster is adding TensorRT, but I could not figure how to make it work with this setup. Feel free to make any suggestions or ask for help in the comments. I hope my guide will save some time for a few people (it took me the better part of a day to figure all of this out).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b645e769f01d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>