<?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 Ryan Xu on Medium]]></title>
        <description><![CDATA[Stories by Ryan Xu on Medium]]></description>
        <link>https://medium.com/@ryxu?source=rss-ff9d266441dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ByieqTl4dKCjo3wtxmLjzw.png</url>
            <title>Stories by Ryan Xu on Medium</title>
            <link>https://medium.com/@ryxu?source=rss-ff9d266441dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:36:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryxu/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[Lessons from 150 games of Yahtzee]]></title>
            <link>https://medium.com/@ryxu/lessons-from-150-games-of-yahtzee-3475b83dbf4e?source=rss-ff9d266441dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3475b83dbf4e</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[games]]></category>
            <dc:creator><![CDATA[Ryan Xu]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 21:04:12 GMT</pubDate>
            <atom:updated>2024-03-31T21:04:12.071Z</atom:updated>
            <content:encoded><![CDATA[<p>I fell in love with Yahtzee a few weeks ago after playing it for the first time.</p><p>I was struck by how approachable the game was, how every turn felt both strategic and creative.</p><p>Following the game, there was one particular decision that nagged at me and so the next day, I looked for an optimal move calculator. To my delight, in addition to a calculator, I also found an <a href="http://www-set.win.tue.nl/~wstomv/misc/yahtzee/yptd.php">online Yahtzee simulator</a> that gives you the full breakdown of the expected value (EV) of every move, along with the corresponding optimal decision.</p><p>At this point, my poker hindbrain kicked in and I just accepted that I would be spending many hours playing Yahtzee. I wanted to approach optimal play (where each decision maximizes the expected game score).</p><p>I started saving each game and set myself a challenge to be able to play more perfect games than not by game 100.</p><h4>Stats</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOvfYtObA9ujZGPDNcdbIg.png" /><figcaption>By the time of writing, I’ve played 150 games. I’ve included them all mostly because I’m on a particularly good streak right now.</figcaption></figure><p>Ultimately, despite making respectable progress, I fell notably short of my goal with only 4 perfect games total: Games 47, 72, 112, and 122.</p><p>The metric plotted above represents the expected number of points lost each game, computed by summing the expected points lost per move (i.e. a difference of -10 means that based on my moves, I was expected to score 10 points below if I had played optimally).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgMaFP9OkTbjnnLg7AFw_A.png" /></figure><p>My highest score was game 75, hitting 526 points with 3 Yahtzees.</p><p>My lowest score was game 53 with only 135 points.</p><p>Though ironically, the lower scoring game was closer to optimal play (-2.05 vs -9.19 EV).</p><p>As a note, it makes sense that my extremes occurred earlier on since optimal play tends to be lower variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMu8yHboHBTyCljz1er_zg.png" /><figcaption>Very consistently, my quality of play first increases then decreases across each session. You can almost read off when I start and stop each day.</figcaption></figure><h4>Strategy</h4><p>While nowhere near comprehensive, I’ll run through some interesting lessons that I learned in chronological order.</p><p>In the first 30 games, I learned that upper section scores are a critical part of the game. In fact, I would describe all of Yahtzee strategy as a dance between scoring high on the lower half while obtaining the upper section bonus. As an example, one should rarely fill 3 or 4 of a kind before the respective upper section number is filled.</p><p>Some mistakes I made over and over:</p><ul><li>Going for full houses (e.g. keeping 3355 when keeping 55 is optimal)</li><li>Going for straights (e.g. keeping 1234 or 3456 to fish for large straights, particularly if I already have the small straight)</li><li>Taking small straights and full houses instead of going for better (e.g. for first roll 44433, taking full house instead of keeping 444 to go for 4s/Yahtzee)</li></ul><p>A difficult and non-obvious optimization is deciding when to go for 4s, 5s, or 6s without prior pairs. Imagine you roll 11256 with 5s and 6s open. It turns out that keeping 5 or 6 can be optimal depending on the state of the game.<br>Early on in the game, you often want to keep 4 &gt; 5 &gt; 6 for two reasons. First, you would prefer to save your higher slots for better first rolls, say where you roll 2 6s to start. Second, 4s and 5s are better keeps to try for straights, even if nothing else is kept. Generally, as straights are filled and the latter half of the game approaches, keeping the 6 in the original 11256 roll quickly becomes optimal.</p><h4>Note on multi-player Yahtzee</h4><p>In the case of solitaire Yahtzee as I have been playing, optimal strategy simply means maximizing EV.</p><p>This is not the case for multi-player Yahtzee, however, where you only care about beating the opponent.</p><p>While strategy may not differ significantly (increasing/decreasing variance if you’re behind/ahead), strategy I’ve discussed may not directly apply.</p><h4>Reflection</h4><p>This was a really really weird way to learn how to play Yahtzee.</p><p>Learning from an optimal computer is this backwards discovery process where the computer tells me an answer and I must deduce the explanation. While the why may be more obvious in some cases, it took me until games 90+ to realize that keeping 5 instead of 6 had anything to do with straight odds.</p><p>In many ways, I felt like a little RL agent throughout this process — playing the game over and over, receiving seemingly random rewards until I figure out a pattern. It’s a fun but fundamentally different challenge from discovering optimal strategy.</p><p>One last funny note: I didn’t know about the “wild card” rule until game 90+. In fact, I had deleted a couple previous games where it applied because I thought the solver was bugged (-44 EV on a Yahtzee??).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3475b83dbf4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The story of computer science: Chapter 1]]></title>
            <link>https://medium.com/@ryxu/the-story-of-computer-science-chapter-1-5280a15238f8?source=rss-ff9d266441dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5280a15238f8</guid>
            <category><![CDATA[history]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[fiction]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ryan Xu]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 20:43:17 GMT</pubDate>
            <atom:updated>2024-01-25T18:18:27.748Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Story of Computer Science: Chapter 1</h3><h4>From Looms to Turing — An Opinionated Bedtime Story.</h4><p><em>Ryan:</em><br>Tonight, I’m going to be telling you all a personal favorite — the story of computer science. Get ready, this is an exciting one!</p><p>Once upon a time, there were two groups of people: the extremely curious and the business tycoons. They didn’t have all that much in common, except for one thing, one burning question: <strong>what can we automate?</strong></p><blockquote><em>Weaving! Here’s a mechanical loom. All you have to do is punch textile patterns into these little cards!<br>- </em>Jacquard, 1804</blockquote><blockquote><em>Hm these punch cards seem powerful. What </em>else<em> can we automate?</em><strong><em><br>- </em></strong>Business tycoons</blockquote><blockquote><em>Arithmetic! I present a design for the Analytical Engine, inspired by the Jacquard loom. It can perform any calculations, provided that you can figure out how to program it. I’ll build it later.<br>- </em>Babbage, 1837</blockquote><blockquote><em>I’ve devised a program for calculating Bernoulli numbers! But also I think you’re missing the point a bit — these symbols we compute with can represent far more than just numbers. They can potentially compute anything that can be symbolically represented!</em><br>- Lovelace, 1843</blockquote><blockquote><em>That’s absolutely incredible. What </em>else<em> can we automate?</em><strong><em><br></em></strong>- The extremely curious</blockquote><blockquote><em>Perhaps even mathematics itself? At the turn of the century, I challenged the mathematical community to determine if all theorems could be derived from a set of axioms. Now, I extend that challenge with what I call the Entscheidungsproblem: can a mechanical process determine the truth of any given theorem?</em><br>-Hilbert, 1928</blockquote><blockquote><em>Nope. No finite set of axioms can prove all mathematical truths. Not sure about that Entscheidungsproblem though.</em><br>-Gödel, 1931</blockquote><blockquote><em>The Entscheidungsproblem is unsolvable! I’ve defined a formal system for expressing computable functions called the Lambda Calculus and found that no one algorithm can determine the truth of all statements!</em><br>-Church, 1936</blockquote><blockquote><em>The Entscheidungsproblem is unsolvable! I’ve defined a machine that computes by reading and writing from a tape like humans and found that some functions cannot be computed!</em><br>-Turing, independently, soon after</blockquote><blockquote><em>Actually, we find that these two models are equivalent in computational power. We furthermore conjecture that any computational procedure can be represented using one of Turing’s machines.<br></em>-Church, Kleene, and Turing, 1936</blockquote><p><em>Ryan:</em><br>That’s all for tonight kids — at this point, we’ve only just touched on the foundations of theoretical computer science.<br>Any questions before bed?</p><p><em>Kids: </em><br>Aww you always leave us with such cliffhangers! How did we get to the computers we have today? How efficiently can we solve different problems with computation? If they can do math, can machines… think?</p><p><em>Ryan:<br></em>All insightful questions that we’ll answer another time!<br>One last fun fact — if we interpreted his designs right, Babbage’s analytical machine would have been Turing complete — as computationally powerful as a Turing machine!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXdF93X1Pk2Vx9PoU3BwCg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5280a15238f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Motivating Self-Attention]]></title>
            <link>https://medium.com/data-science/motivating-self-attention-aead09a02f70?source=rss-ff9d266441dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/aead09a02f70</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ryan Xu]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 14:24:05 GMT</pubDate>
            <atom:updated>2023-06-12T22:05:13.441Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why do we need queries, keys AND values?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QKijdsY_iXMPcRSCnJPsVA.png" /><figcaption>…self-self-attention?</figcaption></figure><p>The goal of this article is to offer an explanation not for <em>how</em> the self-attention mechanism in transformers works, but rather for <em>why</em> it was designed that way.</p><p>We’ll start with a discussion of the kinds of abilities we would like a language understanding model to have, followed by a interactive construction of the self-attention mechanism. In the process, we’ll discover why we need queries, keys, AND values in order to model relationships between words in a natural way, and that QKV attention is one of the simplest ways to do so.</p><p>This article will be most insightful to readers who have encountered transformers and self-attention before, but should be accessible to anybody familiar with some basic linear algebra. To those who are looking to better understand transformers, I will happily refer you to <a href="http://jalammar.github.io/illustrated-transformer/">this blog post</a>.</p><p><em>All images are by the author.</em></p><p>Transformers are frequently presented in the context of sequence-to-sequence modeling tasks such as language translation or more saliently, sentence completion. However, I think that it’s easier to start off by thinking about the problem of sequence modeling and specifically, language understanding.</p><p>So, here’s a sentence that we want to understand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnIJPLpblkR4ImbjqJiATQ.png" /></figure><p>Let’s think a little bit about how we understand this sentence.</p><ul><li><em>Evan’s dog Riley… </em>From this, we know that Riley is the name of the dog, and that Evan owns Riley.</li><li><em>…is so hyper… </em>Simple enough, “hyper” refers to the dog Riley, influencing our impression of Riley.</li><li><em>…she never stops moving</em>. This one is interesting. “she” refers to Riley, since the dog is the subject of the first phrase. This tells us that Evan’s dog Riley is fact female, which was previously ambiguous due to the commonly unisex dog name, “Riley”. “never stops moving” is a slightly more complex set of words that elaborates on “hyper”.</li></ul><p>The key takeaway here is that to build up our understanding of the sentence, we’re constantly considering how words relate to other words to augment their meaning.</p><p>In the machine learning community, the process of augmenting the meaning of a word <strong>a</strong> by the presence of another word <strong>b</strong> is colloquially referred to as “<strong>a</strong> attends to <strong>b</strong>”, as in word <strong>a</strong> pays attention to word <strong>b</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjeEkQbRWnDycAmF9qcG0Q.png" /><figcaption>An arrow <strong>a</strong> =&gt; <strong>b</strong> indicates that “<strong>a</strong> attends to <strong>b</strong>”</figcaption></figure><p>And so, if we would like a machine learning model to understand language, we might understandably want the model to have the ability to have a word attend to another and somehow update its meaning accordingly.</p><p>This is precisely the ability that we hope to emulate as we build up the aptly named (self) attention mechanism in 3 parts.</p><p><em>In the following, I will pose a number of questions in italics. I strongly encourage the reader to stop and consider the question for a minute before continuing.</em></p><h4>Part 1</h4><p>For now, let’s focus on the relationship between the words “dog” and “Riley”. The word “dog” strongly influences the meaning of the word, “Riley”, and so we want “Riley” to attend to “dog”, and so the goal here is to somehow update the meaning of the word “Riley” accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HDAvCYF945UrnD7AkYhFhQ.png" /></figure><p>To make this example more concrete, let’s say that we begin with vector representations of each word, each of length <strong>n</strong>, based on a context-free understanding of the word. We will assume that this vector space is fairly well organized, meaning that words that are more similar in meaning are associated with vectors that are closer in the space.</p><p>So, we have two vectors, <strong>v_dog</strong> and <strong>v_Riley</strong>, that capture the meaning of the two words.</p><p><em>How can we update the value of </em><strong><em>v_Riley</em></strong><em> using </em><strong><em>v_dog</em></strong><em> to obtain a new value for the word “Riley” that incorporates the meaning of “dog”?</em></p><p>We don’t want to completely replace the value of <strong>v_Riley</strong> with <strong>v_dog</strong>, so let’s say that we take a linear combination of <strong>v_Riley</strong> and <strong>v_dog</strong> as the new value for <strong>v_Riley</strong>:</p><pre>v_Riley = get_value(&#39;Riley&#39;)<br>v_dog = get_value(&#39;dog&#39;)<br><br>ratio = .75<br>v_Riley = (ratio * v_Riley) + ((1-ratio) * v_dog)</pre><p>This seems to work alright, we’ve embedded a bit of the meaning of the word “dog” into the word “Riley”.</p><p>Now we would like to try and apply this form of attention to the whole sentence by updating the vector representations of every single word by the vector representations of every other word.</p><p><em>What goes wrong here?</em></p><p>The core problem is that we don’t know which words should take on the meanings of other words. We would also like some measure of how much the value of each word should contribute to each other word.</p><h4><strong>Part 2</strong></h4><p>Alright. So we need to know how much two words should be related.</p><p>Time for attempt number 2.</p><p>I’ve redesigned our vector database so that each word actually has two associated vectors. The first is the same value vector that we had before, still denoted by <strong>v</strong>. In addition, we now have unit vectors denoted by <strong>k </strong>that store some notion of word relations. Specifically, if two <strong>k</strong> vectors are close together, it means that the values associated with these words are likely to influence each other’s meanings.</p><p><em>With our new </em><strong><em>k</em></strong><em> and </em><strong><em>v</em></strong><em> vectors, how can we modify our previous scheme to update </em><strong><em>v_Riley</em></strong><em>’s value with </em><strong><em>v_dog</em></strong><em> in a way that respects how much two words are related?</em></p><p>Let’s continue with the same linear combination business as before, but only if the k vectors of both are close in embedding space. Even better, we can use the dot product of the two k vectors (which range from 0–1 since they are unit vectors) to tell us how much we should update <strong>v_Riley</strong> with <strong>v_dog</strong>.</p><pre>v_Riley, v_dog = get_value(&#39;Riley&#39;), get_value(&#39;dog&#39;)<br>k_Riley, k_dog = get_key(&#39;Riley&#39;), get_key(&#39;dog&#39;)<br><br>relevance = k_Riley · k_dog # dot product<br><br>v_Riley = (relevance) * v_Riley + (1 - relevance) * v_dog</pre><p>This is a little bit strange since if relevance is 1, <strong>v_Riley</strong> gets completely replaced by <strong>v_dog</strong>, but let’s ignore that for a minute.</p><p>I want to instead think about what happens when we apply this kind of idea to the whole sequence. The word “Riley” will have a relevance value with each other word via dot product of <strong>k</strong>s. So, maybe we can instead update the value of each word proportionally to the value of the dot product. For simplicity, let’s also include it’s dot product with itself as a way to preserve it’s own value.</p><pre>sentence = &quot;Evan&#39;s dog Riley is so hyper, she never stops moving&quot;<br>words = sentence.split()<br><br># obtain a list of values<br>values = get_values(words)<br><br># oh yeah, that&#39;s what k stands for by the way<br>keys = get_keys(words)<br><br># get riley&#39;s relevance key<br>riley_index = words.index(&#39;Riley&#39;)<br>riley_key = keys[riley_index]<br><br># generate relevance of &quot;Riley&quot; to each other word<br>relevances = [riley_key · key for key in keys] #still pretending python has ·<br><br># normalize relevances to sum to 1<br>relevances /= sum(relevances)<br><br># takes a linear combination of values, weighted by relevances<br>v_Riley = relevances · values</pre><p>Ok that’s good enough for now.</p><p>But once again, I claim that there’s something wrong with this approach. It’s not that any of our ideas have been implemented incorrectly, but rather there’s something fundamentally different between this approach and how we actually think about relationships between words.</p><p><em>If there’s any point in this article where I </em><strong><em>really really</em></strong><em> think that you should stop and think, it’s here. Even those of you who think you fully understand attention. What’s wrong with our approach?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AeYiSZQuIdx4pTvuTZKnw.png" /><figcaption>A hint</figcaption></figure><p>Relationships between words are inherently asymmetric! The way that “Riley” attends to “dog” is different from the way that “dog” attends to “Riley”. It’s a much bigger deal that “Riley” refers to a dog, not a human, than the name of the dog.</p><p>In contrast, the dot product is a symmetric operation, which means that in our current setup, if a attends to b, then b attends equally strong to a! Actually, this is somewhat false because we’re normalizing the relevance scores, but the point is that the words should have the option of attending in an asymmetric way, even if the other tokens are held constant.</p><h4>Part 3</h4><p>We’re almost there! Finally, the question becomes:</p><p><em>How can we most naturally extend our current setup to allow for asymmetric relationships?</em></p><p>Well what can we do with one more vector type? We still have our value vectors <strong>v</strong>, and our relation vector <strong>k</strong>. Now we have yet another vector <strong>q</strong> for each token.</p><p><em>How can we modify our setup and use </em><strong><em>q</em></strong><em> to achieve the asymmetric relationship that we want?</em></p><p>Those of you who are familiar with how self-attention works will hopefully be smirking at this point.</p><p>Instead of computing relevance <strong>k_dog</strong> · <strong>k_Riley</strong> when “dog” attends to “Riley”, we can instead <em>query</em> <strong>q_Riley</strong> against the <em>key</em> <strong>k_dog</strong> by taking their dot product. When computing the other way around, we will have <strong>q_dog </strong>· <strong>k_Riley</strong> instead — asymmetric relevance!</p><p>Here’s the whole thing together, computing the update for every value at once!</p><pre>sentence = &quot;Evan&#39;s dog Riley is so hyper, she never stops moving&quot;<br>words = sentence.split()<br>seq_len = len(words)<br><br># obtain arrays of queries, keys, and values, each of shape (seq_len, n)<br>Q = array(get_queries(words))<br>K = array(get_keys(words))<br>V = array(get_values(words))<br><br>relevances = Q @ K.T<br>normalized_relevances = relevances / relevances.sum(axis=1)<br><br>new_V = normalized_relevances @ V</pre><p>And that’s basically self-attention!</p><p>There are a few more details that I left out, but the important ideas are all there.</p><p>To recap, we started with value vectors (<strong>v</strong>) to represent the meaning of each word, but quickly found that we need key vectors (<strong>k</strong>) to account for how words relate to each other. Finally, to properly model the asymmetric nature of word relationships, we introduced query vectors (<strong>q</strong>). It almost feels like if all we’re allowed are dot products and such, 3 is the minimal number of vectors per word needed to properly model relationships between words.</p><p>The purpose of this article is to unravel the self-attention mechanism in a way that’s less overwhelming than the traditional algorithm-first approach. I hope that from this more language-motivated perspective, the elegance and simplicity of the query-key-value design can show through.</p><p>Some details that I left out:</p><ul><li>Instead of storing 3 vectors for each token, we instead store a single embedding vector from which we can extract our <strong>q</strong>-<strong>k</strong>-<strong>v</strong> vectors. The extraction process is just a linear projection.</li><li>Technically, in this whole setup, each word has no idea where the other words are in the sentence. Self-attention is really a set operation. So, we need to embed positional knowledge, typically done by adding a position vector to the embedding vector. This isn’t completely trivial since transformers should allow for sequences of arbitrary length. How this works in practice is outside the scope of this article.</li><li>A single self-attention layer only allows us to represent two-word relationships. But by composing self-attention layers, we can model higher level relationships between words. Since the output of a self-attention layer is of the same sequence length as the original sequence, this means that we can compose them. In fact, transformer blocks are just self-attention layers followed by position-wise feed-forward blocks. Stack a few hundred of these, pay a few million dollars, and you have yourself an LLM! :)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxQDTw3Rt9f-M5yHsnctCA.png" /><figcaption>OpenAI showed that it takes 512 transformer blocks to understand that second half.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aead09a02f70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/motivating-self-attention-aead09a02f70">Motivating Self-Attention</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[4 fun facts from Jan 2023]]></title>
            <link>https://medium.com/@ryxu/4-fun-facts-from-jan-2023-d92c6036c045?source=rss-ff9d266441dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d92c6036c045</guid>
            <category><![CDATA[science]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[food]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[humor]]></category>
            <dc:creator><![CDATA[Ryan Xu]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 16:08:49 GMT</pubDate>
            <atom:updated>2023-02-08T16:08:49.251Z</atom:updated>
            <content:encoded><![CDATA[<p>alternate title: “01–23. 4 fun facts”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*2UbcW4SdhnkhE0UG0NBklQ.jpeg" /><figcaption>an undercover nuclear sub. “It’s year 23 of my mission… the fish think I’m one of them…”</figcaption></figure><ol><li>Nuclear submarines aren’t subs with nuclear weapons, they’re subs powered by nuclear energy! And they can stay underwater for decades without refueling — I wonder if they’ve considered using some of this nuclear stuff for other things.</li><li>The word, “alphabet”, is just composed of the first two greek letters! Makes a lot of sense in hindsight.</li><li>Canned foods are cooked <em>after</em> being canned. That’s how they stay good for so long!</li><li>India’s population has (probably) just surpassed China’s!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHu37o1TC8kvXWWvBUwMMA.jpeg" /><figcaption>a beautiful population density map</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d92c6036c045" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Preprocessing with an ASCII Art Generator?]]></title>
            <link>https://medium.com/@ryxu/from-vision-transformers-to-ascii-art-a4cfa70cbfef?source=rss-ff9d266441dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4cfa70cbfef</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ryan Xu]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 03:40:56 GMT</pubDate>
            <atom:updated>2023-02-12T23:44:55.866Z</atom:updated>
            <content:encoded><![CDATA[<p>A random train of thought.</p><p>I read this paper recently, <a href="https://arxiv.org/pdf/2212.08045.pdf"><em>Image-and-Language Understanding from Pixels Only</em></a>, that does VQA¹ using only vision encoders instead of using separate vision and text encoders. They do this by rendering the question’s text as an image and passing it as an input to the vision network.</p><p>¹VQA stands for visual question answering, a task in which a network is expected to answer natural language questions about a given image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*XEJWM2yHfXILdwgcG7bYkA.jpeg" /><figcaption>Sample VQA question: Is the house suspended from the ground? Answer: Yes</figcaption></figure><p>Quite frankly, this seemed ridiculous, and made me want to create something in response — something like “VQA, but only using only text encoders².” I decided that passing the image through an ascii art generator would probably be a good idea.</p><p>²though all of this is already pretty ironic because the encoders used in the paper are vision transformers, which themselves are basically a crude repurposing of an architecture originally designed for text.</p><p>For those of you looking for results, I regret to share that I never went through with running this experiment, almost entirely because I found out how stupidly simple ascii art generators are. Most of them just find the character whose brightness value is closest to the average brightness in the image patch. The nice ascii art that you normally encounter is usually carefully designed by people³.</p><p>³side note, Chat-GPT is hilariously bad at generating ascii art.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*gPhA3o_bQy1ULjAnPjGHGA.png" /><figcaption>Ascii artists, your jobs are safe!</figcaption></figure><p>Anyways, all of this got me thinking. I actually really liked the concept of turning images into good ascii art, where the segmentations of the objects are well represented by the curves of the ascii characters. In this case, learning the character embeddings is in some sense just learning to embed the shape of the characters.</p><p>More generally, this made me wonder whether you could do something similar in normal networks — some variation of discretizing and learning an embedding for the discrete forms. Optimistically, discretized forms deep in the network may even begin to represent objects that are easier to symbolically manipulate and interpret.</p><p>Thats about it for now — just a train of thought that I had recently.</p><p>Honestly, I’m not really sure who the target audience is for this, but I hope that at the very least, you found something pretty, amusing, or informative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Tc7LH7WL22nuwmc5W0kAXA.jpeg" /><figcaption>A random train of thought</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4cfa70cbfef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[N-Student Learning]]></title>
            <link>https://medium.com/data-science/n-student-learning-fc4e452ad006?source=rss-ff9d266441dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc4e452ad006</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Ryan Xu]]></dc:creator>
            <pubDate>Wed, 27 Jul 2022 18:41:13 GMT</pubDate>
            <atom:updated>2023-02-04T18:43:03.006Z</atom:updated>
            <content:encoded><![CDATA[<h4>An architecture to help combat overfitting and model uncertainty.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPJTyHYsR569j1knvFbalw.png" /><figcaption>An overfit decision boundary.</figcaption></figure><p>Overfitting is a fundamental problem in the field of machine learning, and is especially important in the context of training with noisy data. As we scale our datasets, the amount of noise naturally increases due to the infeasibility of careful human labeling.</p><p>In the following article, we will be introducing the main ideas behind N-Student Learning, a multi-network architecture that can be applied to any network in order to reduce the impact of overfitting. The setup also allows for precise control over how a network learns to model any noise or uncertainty in the data.</p><p><em>All images unless otherwise noted are by the author.</em></p><h3><strong>The Problem</strong></h3><h4>Overfitting</h4><p>The goal of <strong>supervised classification</strong> is to model the relationship between an input space and a label space, typically given a training dataset of input-label pairs (e.g. learn to classify images of animals into the correct categories).</p><p>In particular, the labels are <strong>one-hot</strong>, meaning that the label for each input is a single correct category with 100% probability, as opposed to the label being a probability distribution over multiple categories.</p><p>N-Student learning tackles the problem of <strong>overfitting</strong>, specifically in the domain of supervised classification. Overfitting can be roughly stated as a phenomenon in which a machine learning model learns to solve the given task using quirks of the training data that are not generalizable to unseen data. At worst, overfitting means memorizing the labels for training set at the expense of generalization, a serious concern for the training of deep neural networks (where the sheer number of parameters allows them to memorize even random labels).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56IAhHqBYUnPJesmBfVM1g.png" /><figcaption>Well-fit vs overfit decision boundaries</figcaption></figure><p>In the figure above, we see an example of overfitting using a small dataset of 20 points drawn from two classes. The classes in this dataset are fairly well separated, but contain a few outliers.</p><p>The dotted line is a <strong>decision boundary</strong>, separating the areas that a model predicts to be blue from the areas that the model predicts to be red. As we can see, the overfit decision boundary “memorized” the few outliers, creating portions of the input space that will generalize poorly to new examples.</p><p>The extent to which overfitting impairs a network depends on the quality of the data. If we had a perfect training set, then fitting exactly to the data is less of an issue. The worry is that the labels in our training set are imperfect — noisy in some way.</p><h4>Two forms of label noise</h4><p>I want to first distinguish between two fundamental sources of label noise that might affect datasets with one-hot labels: <strong>errors</strong> and <strong>stochasticity</strong>.</p><p>The simplest type of noise is when there are errors in the labels. An example of this is the task of classifying high resolution images of cats and dogs. Imagine that a human labeler is used to generate the training set labels and they sometimes accidentally choose the incorrect label, introducing errors into the dataset. The reason that I specify high resolution is to make it clear that given any image, it is completely unambiguous whether it is a dog or a cat, and so any noise in the labeling process can be directly attributed to errors in the labeling process. Memorizing these sorts of errors in the training set will have a clear negative impact on model generalization to unseen data.</p><p>Label noise due to stochasticity is a much more subtle form of label noise that occurs when the problem domain is inherently stochastic. A good example is the problem of melanoma diagnosis using images. Given a dermoscopic image, it is not always possible to say for certain whether it is a case of melanoma. Many times, the optimal prediction for an image might be that it is 80% likely that the patient has melanoma because 20% of the time, the same image might actually show a benign melanoma mimicker. However, we don’t have these platonic probabilities available to us — our one-hot datasets pair a dermoscopic image with a binary signal of whether that specific patient was diagnosed with melanoma. This gap between the optimal 80% likelihood and the 100% confident label that we receive creates this “stochastic noise gap”. When tasks like these are defined, we implicitly want the network to output an accurate estimate of how likely a patient is to be diagnosed with melanoma, not just the most likely answer. This type of stochastic noise is another form of noise that a network can overfit to.</p><p>The commonality between error-based noise and stochastic noise is that given a particular example from the input domain, the generated label might not always be the same.</p><p>In the error case, the human-labeler may label a cat correctly in one instance but accidentally choose dog in another.</p><p>In the stochastic case, the exact same type of dermoscopic image may result in melanoma in one patient but not another.</p><p>Without any domain knowledge, and specifically without a prior on what sort of noise a dataset has, I claim that these two forms of noise are indistinguishable.</p><h4>Fun with gaussians — visualizing errors and stochasticity</h4><p>Let’s see what this means through the following toy dataset of blue and yellow points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tl6OmnU7aSxroy_qBCI3bw.png" /><figcaption>Blue-Yellow Toy Dataset</figcaption></figure><p>What we notice is that if a point is on the far left side, it is almost certainly blue and if the point is on the far right side, it is almost certainly yellow. However, the correct class becomes more ambiguous as we get closer to the middle.</p><p>One plausible explanation for the data is that there are actually two very disjoint classes on the plane, but there are errors in the dataset’s labels (especially in the middle area where the two classes become more similar). In this case, the “optimal” decision boundary between the two classes might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8JWK-l9A7OdLuaUiYEjBA.png" /><figcaption>Optimal decision boundary, assuming that noise is due to <strong>errors</strong>.</figcaption></figure><p>Another plausible explanation is that the data is fundamentally stochastic — given a location on the plane, there is some probability that it belongs to either class. In this case, the optimal decision boundary will have a sort of class gradient in the middle. As you might have guessed, these points were actually drawn from two gaussians, so we can generate an optimal “soft” decision boundary by simply computing the probability of a point being drawn from each gaussian given the location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpCl5Rk1rNnJ9FoK8X8NdA.png" /><figcaption>Optimal decision boundary, assuming that noise is due to <strong>stochasticity</strong>.</figcaption></figure><p>In the context of these two gaussians, my claim from earlier says that both explanations are plausible, and we cannot know whether the overlapping data points in the middle are caused by errors in the labeling process or stochasticity without a prior on what kind of noise is present in the dataset.</p><p><em>Note: You might still think that from the dataset alone, it’s clear that the points are stochastic in the middle due to the overlap. If I were to generate these gaussians farther apart so that the classes were completely disjoint except for a few outliers, I suspect that the stochastic nature would be far less obvious.</em></p><h3><strong>2-Student Learning</strong></h3><h4>The architecture</h4><p>In short, the N-Student Learning paradigm involves the training of a multi-network architecture in which each “<strong>student network</strong>” learns from a different subset of the dataset. Throughout the course of training, each student continues to train on its own subset, but with some of the labels replaced by <strong>pseudo-labels</strong> from the other networks.</p><p>Pseudo-labeling is the process of using a network’s outputs to generate new labels for the data. For now, let’s assume that pseudo-labels are generated by taking the class that the network assigns the highest probability to. These are called “<strong>hard pseudo-labels”</strong>, and we will later show that based on the pseudo-labeling method chosen, we can control whether the students learn to model the noise in the data as errors or stochasticity.</p><p>Let’s go ahead and describe a simple <strong>2-Student Setup</strong>.</p><ol><li>Split training dataset into two halves<br>– D₁ and D₂</li><li>Train 2 networks in parallel<br>– N₁ and N₂</li><li>Warm up the networks by training each network on its respective dataset<br>– N₁ trains on D₁<br>– N₂ trains on D₂</li><li>Every epoch, train each network on its respective dataset with a proportion of the samples replaced with pseudo-labels generated by the other network.<br>– N₁ trains on {N₂’s labels for D₁}<br>– N₂ trains on {N₁’s labels for D₂}</li></ol><p>The key insight is that each network only ever trains on its own dataset, so it cannot overfit to the dataset that it generates pseudo-labels for. Network 1’s pseudo-labels for Dataset 2 should be clean of any instance-dependent noise in D₂. The same goes for N₂’s pseudo-labels for D₁.</p><p>The effectiveness of this setup relies on the idea that machine learning algorithms generalize before overfitting. By training on pseudo-labels that have not overfit, the networks can converge to a solution that is more robust to noise in the training data.</p><p>As you might imagine, there are a number of ways to generalize this 2-Student Setup for more students and different dataset splits, but we won’t get into that here.</p><h4>More fun with gaussians — controlling uncertainty</h4><p>Finally, we’ll see all of this in action by returning to our trusty blue and yellow dataset. To motivate our choices of pseudo-labeling methods, let’s consider how we would want to generate pseudo-labels from the outputs of a network that has generalized and not yet overfit. (We assume that a cross-entropy loss is used, which encourages the output distribution of a network to be representative of the distribution of labels in the training data.)</p><p>If our prior on the problem tells us that the true labels are one-hot (noise in the dataset is due to errors), then we would want the network to generate one-hot labels that ignore any small probabilities for other classes that might come from errors in the dataset. We can do this by using hard pseudo-labels.</p><p>If we think that the problem is fundamentally stochastic, then we would want pseudo-labels that match the distribution of the network’s outputs. We can do this by either taking the network output (a distribution over classes) as the pseudo-label, or by randomly sampling from the network’s output to choose a one-hot label. We call these “soft pseudo-labels” and “<strong>stochastic pseudo-labels</strong>”, respectively. (They are equivalent for infinitely large batch sizes, but stochastic pseudo-labels perform better in practice.)</p><p>Now let’s see what happens when we train two 2-Student Setups using hard and stochastic pseudo-labeling methods. The soft decision boundaries for the networks are shown for epochs 10, 200, and 400 (number of training iterations), and the same network trained normally will be used as a baseline (without the 2-Student-Setup).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vPT4_BPd6knU1c9IV4gUw.png" /></figure><p>What we see is that the baseline network overfits to the noise in the dataset, creating a complex decision boundary that accommodates as much of the noise as its parameters can handle.</p><p>In contrast, the hard-pseudo-labeled network draws a sharp decision boundary down the middle. This is exactly what we would want if our assumption is that the ambiguous data points in the middle are a result of noise.</p><p>The stochastic-pseudo-labeled network outputs a layered decision boundary. If our assumption was that the data is not error-prone and the ambiguity comes from stochasticity, then this decision boundary well-represents the conditional probability of the blue and yellow classes.</p><p>In many ways, this figure alone summarizes my thesis work. Given a dataset without domain knowledge, it’s impossible to determine whether labeling errors or stochastic effects are responsible for noise in the labels. However, we typically have strong priors on the dataset and what kinds of noise might be present. By choosing the appropriate pseudo-labeling method, we can control exactly what kind of distribution that the model learns from the data.</p><p>N-Student Learning was developed as part of my undergraduate thesis in Computer Science at Brandeis University.</p><p>This post is the culmination of more than a year’s worth of learning and research. My hope is that anyone who stumbles across this is able to walk away with new insights, regardless of their amount of prior experience with machine learning.</p><p>For those who wish to dive further, here is a <a href="http://ryanxu.net/thesis">link to the thesis itself</a>.</p><p>The full thesis discusses the topics presented here in depth, and also demonstrates that N-Student Learning performs favorably to many state-of-the-art methods on a variety of benchmark noisy-label datasets.</p><p>Please reach out if you have any questions about this work or have any suggestions on how the concepts could be explained in a more clear and approachable way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc4e452ad006" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/n-student-learning-fc4e452ad006">N-Student Learning</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[The 8–3 Problem]]></title>
            <link>https://medium.com/@ryxu/the-8-3-problem-1bfb0bb8caf3?source=rss-ff9d266441dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bfb0bb8caf3</guid>
            <category><![CDATA[robustness]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ryan Xu]]></dc:creator>
            <pubDate>Thu, 21 Jul 2022 03:40:26 GMT</pubDate>
            <atom:updated>2022-07-21T03:40:26.723Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s play a game.</h4><p>These are <strong>8</strong>s:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUlX8pGLMTSLMbFKTzKN6w.png" /></figure><p>These are <strong>3</strong>s:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFpLNhiuMiD0A20QUIgxBg.png" /></figure><p>Now get ready…<br>What’s this symbol?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*kevIxb6fPqeBWWbXM3t8xw.png" /></figure><p><strong>3</strong>? Not sure? Neither?</p><p>Any of those may be reasonable answers but unfortunately for you, it’s an <strong>8</strong>!</p><p>That’s because the game that we’re playing today is called,<br><strong>“What would LeNet say?”</strong></p><p>By the way, this is also an <strong>8</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*vTW3SOyT1bBrADITS1_ZEQ.png" /></figure><p>And this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*ZseqgWVpGgI2MJxjlTH1ww.png" /></figure><p>Just kidding! That last one’s a <strong>3</strong>!</p><p>Let’s play one more round, just for good measure. What’s this symbol?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*lH90PEu-5NpZwlg7Q9lH9g.png" /></figure><p>That’s right, it’s an <strong>8</strong>!</p><p>Ok. What the hell is going on here?</p><p>Well, let’s think about how LeNet might distinguish between <strong>8</strong>s and <strong>3</strong>s.</p><p>Both symbols have loops on the right side. The primary difference is that <strong>8</strong>s have loops on the left side too!</p><p>Regardless of whether the symbol is an <strong>8</strong> or a <strong>3</strong>, we should expect “active” (lighter) pixels on the right side of the image. As a result, active pixels on the right side tell us little about whether the symbol is an <strong>8</strong> or a <strong>3</strong>.</p><p>Active pixels on the left side, however, are incredibly informative. If there are active pixels on the left side, especially along the left loops of an 8, the symbol is almost certainly an <strong>8</strong>!</p><p>Let’s investigate this further by probing LeNet to get a sense of how the network reacts to active pixels in various locations accross the input image. We can do this by having LeNet make a prediction on an image where the only active pixels are a 2x2 block. By predicting on a set of such images (with a 2x2 block on all pixel locations) we can visualize the relationship between active pixels and network outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*xbpGPMqvfPFa3cOIIJM-Lw.png" /></figure><p>What we find is that LeNet predicts an <strong>8</strong> with high confidence when pixels are active along that left curve. This would explain why LeNet predicted <strong>8</strong>s on those backwards 3s from earlier. It also explains why when we shifted the backwards 3 a few pixels to the right, it predicted a <strong>3</strong>. Similarly, when the regular 3 was shifted a few pixels left, LeNet predicted an <strong>8 </strong>— simply because there were active pixels on the left.</p><p>Of course, this kind of light probing into LeNet is an oversimplification. After all, LeNet is convolution-based, and the outputs are non-linear with respect to the input pixels. However, this quick experiment gives valuable insight into how the network sees. (It’s also slightly concerning that LeNet will predict with such high confidence when shown only a 2x2 block of active pixels.)</p><p>This experiment draws attention to a fundamental difference between learning a robust representation of a class and learning to distinguish between classes. Not only is the latter task easier, but there is no obvious incentive for a network to perform the former task in traditional supervised classification settings. This in turn contributes to poor out-of-domain generalization and high variability in network outputs in response to semantically irrelevant changes to the input.</p><p>To formalize this difference, I propose the <strong>8–3 problem</strong>:<br>Design a training scheme so that after training a network on instances of MNIST 8s and 3s, the 8 and 3 output neurons will fire minimally in response to an image of a backwards 3. (This isn’t possible for networks with softmax output activations without out-of-domain considerations, which perhaps says something about the relevance of vanilla softmax networks to real-world classification problems.)</p><p>The 8–3 problem is less so a technically-difficult challenge and more so a mental check that one should perform when designing and thinking about network training schemes. Consider it a means for evaluating model robustness in a way that’s orthogonal to traditional test accuracy.</p><p>In short, the 8–3 problem poses the question of how to train a network to learn robust representations of 8s and 3s instead of simply learning the differences between 8s and 3s.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bfb0bb8caf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>