<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[ML in JS - Burak Kanber, Engineer]]></title><description><![CDATA[Author, tech CTO, engineer, and some other things too.]]></description><link>https://burakkanber.com/</link><image><url>https://burakkanber.com/favicon.png</url><title>ML in JS - Burak Kanber, Engineer</title><link>https://burakkanber.com/</link></image><generator>Ghost 2.19</generator><lastBuildDate>Wed, 28 Aug 2024 13:09:43 GMT</lastBuildDate><atom:link href="https://burakkanber.com/tag/ml-in-js/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Hands-on Machine Learning in JavaScript]]></title><description><![CDATA[The Hands-on Machine Learning with JavaScript book teaches ML algorithms from first principles to JS devs for use in the browser, node.js, and mobile apps.]]></description><link>https://burakkanber.com/blog/hands-on-machine-learning-in-javascript/</link><guid isPermaLink="false">5b15db1761a6570001244579</guid><category><![CDATA[ML in JS]]></category><category><![CDATA[Books]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Tue, 05 Jun 2018 01:15:39 GMT</pubDate><media:content url="https://burakkanber.com/content/images/2018/06/MLwithJSBookCover-Short-1.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><img src="https://burakkanber.com/content/images/2018/06/MLwithJSBookCover-Short-1.jpg" alt="Hands-on Machine Learning in JavaScript"><p>It's been a while since my last ML in JS post, but to make it up to you I'm excited to announce the release of my latest book, <a href="https://www.packtpub.com/big-data-and-business-intelligence/hands-machine-learning-javascript">Hands-on Machine Learning with JavaScript</a>.</p>
<p>The book is similar in many ways to my old blog series. It's a no-nonsense tour of twenty or so machine learning algorithms, covering many typical use-cases. <!-- more --> You learn to write many of the algorithms from scratch, though now that JS has a bit of an ML ecosystem we also use popular libraries (like TensorFlow.js) for the more complex algorithms. I show you the math where necessary, though I focus more on the implementations and the practical advice you'll need when starting to work with ML algorithms.</p>
<p>If you're primarily a JavaScript developer who hasn't worked much with ML, I think you'll love the book. I wrote it <em>specifically</em> for you: experienced JS devs who want to start with machine learning. Even if JS isn't your primary language, you might still love it because you'll learn a lot about ML in the context of a language you're comfortable with. The concepts and lessons in the book are broad enough to apply to any programming language, so you can take it with you when you're done.</p>
<p>If you've enjoyed my blog posts about ML in JS - and I'm proud to say that over a million readers have - please do check out <a href="https://www.packtpub.com/big-data-and-business-intelligence/hands-machine-learning-javascript">Hands-on Machine Learning with JavaScript</a>.</p>
<p>Teaching is a passion of mine, and I'm always looking for new ways to do it. While I love what I've been able to do with this blog, I think that ML in JS in book form is the right way to present the right material to the right people. I hope you agree, and thanks for being a reader!</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Machine Learning: Full-Text Search in Javascript (Part 1: Relevance Scoring)]]></title><description><![CDATA[Full-text search is a powerful machine learning algorithm, especially relevant for web developers. This article teaches you the basics, from scratch.]]></description><link>https://burakkanber.com/blog/machine-learning-full-text-search-in-javascript-relevance-scoring/</link><guid isPermaLink="false">59b43b8b934a21000178fc15</guid><category><![CDATA[ML in JS]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Sun, 22 Mar 2015 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>Full-text search, unlike most of the topics in this machine learning series, is a problem that most web developers have encountered at some point in their daily work. A client asks you to put a search field somewhere, and you write some SQL along the lines of <code>WHERE title LIKE %:query%</code>. It's convincing at first, but then a few days later the client calls you and claims that &quot;search is broken!&quot;</p>
<!-- more -->
<p>Of course, your search isn't <em>broken</em>, it's just not doing what the client wants. Regular web users don't really understand the concept of exact matches, so your search quality ends up being poor. You decide you need to use full-text search. With some MySQL fidgeting you're able to set up a FULLTEXT index and use a more evolved syntax, the &quot;MATCH() ... AGAINST()&quot; query.</p>
<p>Great! Problem solved. For smallish databases.</p>
<p>As you hit the hundreds of thousands of records, you notice that your database is sluggish. MySQL just isn't <em>great</em> at full-text search. So you grab ElasticSearch, refactor your code a bit, and deploy a Lucene-driven full-text search cluster that works wonders. It's fast and the quality of results is great.</p>
<p>Which leads you to ask: what the heck is Lucene doing <em>so right</em>?</p>
<p>This article (on TF-IDF, Okapi BM-25, and relevance scoring in general) and the next one (on inverted indices) describe the basic concepts behind full-text search.</p>
<h2>Relevance</h2>
It would be convenient to be able to define a "relevance score" that relates a document to a search query. And then, when users search for things, we can sort by the relevance score instead of sorting chronologically. That way the most relevant documents come up on top, regardless (or maybe not) of how old they are.
<p>There are many, many ways to relate one text to another, but let's start simple and use a statistics-based approach that doesn't need to understand language itself, but rather looks at the statistics of word usage and matches and weighs documents based on the prevalence of their unique words.</p>
<p>This algorithm doesn't care about verbs or nouns or even meaning. All it cares about is the simple fact that there are common words and there are rare words, and if your search phrase includes both common and rare words, you'd be better off to rank the documents that have that rare word in it higher, and put less weight on matched common words.</p>
<p>The algorithm we'll use is called <a title="Okapi BM25" href="http://en.wikipedia.org/wiki/Okapi_BM25" target="_blank">Okapi BM25</a>, but it builds on two basic concepts: <em>term frequency (&quot;TF&quot;) </em>and <em>inverse document frequency (&quot;IDF&quot;). </em>Together, these concepts form &quot;TF-IDF&quot;, which is a statistical measure that represents how important a term is to a document.</p>
<h2>TF-IDF</h2>
<p><em>Term Frequency, </em>abbreviated &quot;TF&quot;, is a simple metric: it's the number of times a certain word appears in a document. You can also represent it as the fraction of the number of times a word appears over the total number of tokens (ie, total words) in a document. Term frequency says &quot;I'm 100 words long and 'the' shows up 8 times, so the term frequency of 'the' is 8 or 8/100 or 8%&quot; (depending on the representation you want).</p>
<p><em>Inverse Document Frequency, </em>abbreviated &quot;IDF&quot;, is more evolved: the <em>rarer</em> a word is, the <em>higher</em> this value. It's the log ratio of the number of total documents over the number of documents a term appears in. Rarer words, therefore, yield bigger &quot;IDF&quot;s.</p>
<p>If you multiply these two numbers together, (TF*IDF), you'll get the importance of a word to a document. &quot;Importance&quot; being defined as &quot;how rare is this word and how often does it appear in this document?&quot;</p>
<p>You can then use this concept to relate a document to a search query. For each term in a search query, calculate its TF-IDF score, add them all up, and whichever document has the highest score is your winner.</p>
<p>Cool? Cool.</p>
<h2>Okapi BM25</h2>
<p>The algorithm described above is <em>okay </em>but not wonderful. It does provide us with statistically-derived relevance scores, but it could be improved.</p>
<p>Okapi BM25 is considered a state-of-the-art ranking algorithm (<a href="http://www.elastic.co/guide/en/elasticsearch/guide/current/pluggable-similarites.html" target="_blank">so says ElasticSearch</a>). The major improvements that Okapi BM25 bring over TF-IDF are two tunable parameters, called k1 and b, that modulate &quot;term frequency saturation&quot; and &quot;field-length normalization&quot;. What?</p>
<p>To intuit term frequency saturation, imagine two documents of roughly the same length that both talk about baseball. Imagine that the overall corpus doesn't have much to do with baseball, so the term &quot;baseball&quot;s IDF is pretty high -- it's a rare and important-ish word. These two documents both talk about baseball, and talk about it a lot, but one of them uses the term &quot;baseball&quot; way more. Should that document <em>really</em> show up that much higher in the rankings? Both the documents talk about baseball a hefty amount, and at a certain point it shouldn't really matter if you use the word &quot;baseball&quot; 40 times or 80 times. Anything above 30 is enough!</p>
<p>This is &quot;term frequency saturation.&quot; The naive TF-IDF algorithm doesn't saturate, so the document that uses &quot;baseball&quot; 80 times will have twice the score as the one that uses it 40 times. Sometimes that's desired, sometimes it's not.</p>
<p>Okapi BM25, on the other hand, has a parameter called &quot;k1&quot; that actually lets you tune how quickly term frequency will saturate. The parameter k1 is usually taken between 1.2 and 2.0. Lower values result in quicker saturation (meaning that those two documents above will have similar scores, because they both have a significant number of &quot;baseball&quot;s).</p>
<p>Field-length normalization considers the length of the document and normalizes against the average length of all documents. It's useful in single-field collections (like ours) to put documents of differing lengths on the same playing field. It's doubly useful in multiple-field collections (like &quot;title&quot; and &quot;body&quot;) in putting the title and body fields on the same playing field as well. The term &quot;b&quot; is ranged from 0 to 1, with 1 giving full normalization and 0 giving no normalization.</p>
<h2>The Algorithm</h2>
<p>You can see the formula for the Okapi BM25 algorithm on the <a href="http://en.wikipedia.org/wiki/Okapi_BM25" target="_blank">Okapi BM25 Wikipedia page</a>. Now that you know what each of the terms are, it should be pretty straight-forward to understand, so we won't dive into the equation here. Let's dive into code:</p>
<pre><code class="language-javascript">BM25.Tokenize = function(text) {
    text = text
        .toLowerCase()
        .replace(/\W/g, ' ')
        .replace(/\s+/g, ' ')
        .trim()
        .split(' ')
        .map(function(a) { return stemmer(a); });

    // Filter out stopStems
    var out = [];
    for (var i = 0, len = text.length; i &amp;lt; len; i++) {
        if (stopStems.indexOf(text[i]) === -1) {
            out.push(text[i]);
        }
    }

    return out;
};
</code></pre>
<p>We define a simple <code class="code">Tokenize()</code> static method whose purpose is to parse a string into an array of tokens. Along the way, we lower-case all the tokens (to reduce entropy), we run the Porter Stemmer Algorithm to reduce the entropy of the corpus and also to improve matching (so that &quot;walking&quot; and &quot;walk&quot; match the same), and we also filter out stop-words (very common words) to further reduce entropy. I've written about all these concepts in-depth previously, so please excuse me if I'm glossing over this section. :)</p>
<pre><code class="language-javascript">BM25.prototype.addDocument = function(doc) {
    if (typeof doc.id === 'undefined') { throw new Error(1000, 'ID is a required property of documents.'); };
    if (typeof doc.body === 'undefined') { throw new Error(1001, 'Body is a required property of documents.'); };

    // Raw tokenized list of words
    var tokens = BM25.Tokenize(doc.body);

    // Will hold unique terms and their counts and frequencies
    var _terms = {};

    // docObj will eventually be added to the documents database
    var docObj = {id: doc.id, tokens: tokens, body: doc.body};

    // Count number of terms
    docObj.termCount = tokens.length;

    // Increment totalDocuments
    this.totalDocuments++;

    // Readjust averageDocumentLength
    this.totalDocumentTermLength += docObj.termCount;
    this.averageDocumentLength = this.totalDocumentTermLength / this.totalDocuments;

    // Calculate term frequency
    // First get terms count
    for (var i = 0, len = tokens.length; i &amp;lt; len; i++) {
        var term = tokens[i];
        if (!_terms[term]) { 
            _terms[term] = {
                count: 0,
                freq: 0
            }; 
        };
        _terms[term].count++;
    }

    // Then re-loop to calculate term frequency.
    // We'll also update inverse document frequencies here.
    var keys = Object.keys(_terms);
    for (var i = 0, len = keys.length; i &amp;lt; len; i++) {
        var term = keys[i];
        // Term Frequency for this document.
        _terms[term].freq = _terms[term].count / docObj.termCount;

        // Inverse Document Frequency initialization
        if (!this.terms[term]) {
            this.terms[term] = {
                n: 0, // Number of docs this term appears in, uniquely
                idf: 0
            };
        }

        this.terms[term].n++;
    };

    // Calculate inverse document frequencies
    // This is SLOWish so if you want to index a big batch of documents,
    // comment this out and run it once at the end of your addDocuments run
    // If you're only indexing a document or two at a time you can leave this in.
    // this.updateIdf();

    // Add docObj to docs db
    docObj.terms = _terms;
    this.documents[docObj.id] = docObj;
};
</code></pre>
<p>This <code class="code">addDocument()</code> method is where most of the magic happens. We're essentially building and maintaining two similar data structures: <code class="code">this.documents</code>, and <code class="code">this.terms</code>.</p>
<p><code class="code">this.documents</code> is our database of individual documents, but along with storing the full, original text of the document, we also store the document length and a list of all the tokens in the document along with their count and frequency. Using this data structure we can easily and quickly (with a super-fast, O(1) hash table lookup) answer the question &quot;in document #3, how many times did the word 'walk' occur?&quot;</p>
<p>We also build a second data structure called <code class="code">this.terms</code>. This represents all terms in the entire corpus. Through this O(1) data structure we can quickly answer the questions &quot;how many documents does 'walk' appear in? And what's its idf score?&quot;.</p>
<p>Finally, we record the document length for each individual document, and also maintain an average document length for the whole corpus.</p>
<p>Of course, you see above that idf is initialized to zero, and I've even commented out the <code class="code">updateIdf()</code> call above. That's because it's quite slow, and only needs to be run once at the end of the indexing operation. No need to run this 50,000 times when once will suffice. Leaving this commented out and running it only once at the end of a bulk index operation really speeds things up. Here's the method:</p>
<pre><code class="language-javascript">BM25.prototype.updateIdf = function() {
    var keys = Object.keys(this.terms);
    for (var i = 0, len = keys.length; i &amp;lt; len; i++) {
        var term = keys[i];
        var num = (this.totalDocuments - this.terms[term].n + 0.5);
        var denom = (this.terms[term].n + 0.5);
        this.terms[term].idf = Math.max(Math.log10(num / denom), 0.01);
    }
};
</code></pre>
<p>It's a simple function, but since it loops over the entire corpus terms list, updating each one, it's a somewhat expensive operation. The implementation is the standard formula for inverse document frequency (which you can easily find <a href="http://en.wikipedia.org/wiki/Tf–idf" target="_blank">on Wikipedia</a>) -- it's the log ratio of total documents to the number of documents a term appears in. I've also modified it to always be above zero.</p>
<pre><code class="language-javascript">BM25.prototype.search = function(query) {

    var queryTerms = BM25.Tokenize(query);
    var results = [];

    // Look at each document in turn. There are better ways to do this with inverted indices.
    var keys = Object.keys(this.documents);
    for (var j = 0, nDocs = keys.length; j &lt; nDocs; j++) {
        var id = keys[j];
        // The relevance score for a document is the sum of a tf-idf-like
        // calculation for each query term.
        this.documents[id]._score = 0;

        // Calculate the score for each query term
        for (var i = 0, len = queryTerms.length; i &lt; len; i++) {
            var queryTerm = queryTerms[i];

            // We've never seen this term before so IDF will be 0.
            // Means we can skip the whole term, it adds nothing to the score
            // and isn't in any document.
            if (typeof this.terms[queryTerm] === 'undefined') {
                continue;
            }

            // This term isn't in the document, so the TF portion is 0 and this
            // term contributes nothing to the search score.
            if (typeof this.documents[id].terms[queryTerm] === 'undefined') {
                continue;
            }

            // The term is in the document, let's go.
            // The whole term is :
            // IDF * (TF * (k1 + 1)) / (TF + k1 * (1 - b + b * docLength / avgDocLength))

            // IDF is pre-calculated for the whole docset.
            var idf = this.terms[queryTerm].idf;
            // Numerator of the TF portion.
            var num = this.documents[id].terms[queryTerm].count * (this.k1 + 1);
            // Denomerator of the TF portion.
            var denom = this.documents[id].terms[queryTerm].count 
                + (this.k1 * (1 - this.b + (this.b * this.documents[id].termCount / this.averageDocumentLength)));

            // Add this query term to the score
            this.documents[id]._score += idf * num / denom;
        }

        if (!isNaN(this.documents[id]._score) &amp;&amp; this.documents[id]._score &gt; 0) {
            results.push(this.documents[id]);
        }
    }

    results.sort(function(a, b) { return b._score - a._score; });
    return results.slice(0, 10);
};
</code></pre>
<p>Finally, the <code class="code">search()</code> method loops through all documents and assigns a BM25 relevance score to each, sorting the highest scores at the end. Of course, it's silly to loop through every document in the corpus when searching, but that's the subject of Part Two (inverted indices and performance).</p>
<p>The code above is documented inline, but the gist is as follows: for each document and for each query term, calculate the BM25 score. The idf score for each query term is globally pre-calculated and just a simple look-up, the term frequency is document-specific but was also pre-calculated, and the rest of the work is simply multiplication and division! We add a temporary variable called <code class="code">_score</code> to each document, and then sort the results by the score (descending) and return the top 10.</p>
<h2>Demo, Source Code, Notes, and Next Steps</h2>
There are lots of ways the above can be improved, and we'll explore those in Part Two of "Full-Text Search"! Stay tuned. I hope to publish it in a few weeks. Some things we'll accomplish next time are:
<ul>
	<li>Inverted index for faster searches</li>
	<li>Faster indexing</li>
	<li>Even better search results</li>
</ul>
For this demo, I built a little Wikipedia crawler that grabs the first paragraph of a decent number (85,000) of Wikipedia articles. Since indexing all 85k documents takes about 90 seconds on my computer I've cut the corpus in half for this demo. Don't want you guys to waste your laptop battery juice on indexing Wikipedia articles for a simple full-text demo.
<p>Because the indexing is a CPU-heavy, blocking operation, I implemented it as a Web Worker. The indexing runs in a background thread -- you can find the <a href="http://burakkanber.com/~/mlinjs/bm25.js" target="_blank">full source code here</a>. You'll also find references to the stemmer algorithm and my stop-word list in the source code. The code license, as always, is free to use for educational purposes but not for any commercial purpose.</p>
<p>Finally, here's the demo. Once the indexing is complete, try searching for random things and phrases that Wikipedia might know about. Note that there's only 40,000 paragraphs indexed here, so you might have to try a few topics before you find one that the system knows about.</p>
<iframe src="https://burakkanber.com/~/mlinjs/bm25.html" border="0" style="width: 100%; height: 400px; border: 1px solid #CCC;"></iframe>
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<div id="mc_embed_signup">
<form action="http://burakkanber.us5.list-manage.com/subscribe/post?u=3269dc566d381f05852d92aa8&amp;id=3f5451bda5" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
<h2>Email me when new ML in JS articles are posted</h2>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address </label><input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group input-group">
    <strong>Survey: Would you buy an ML in JS e-book? </strong>
    <input type="checkbox" value="1" name="group[6613][1]" id="mce-group[6613]-6613-0"><label for="mce-group[6613]-6613-0">I would pay $10 for a DRM-free e-book with tons of ML lessons and JS examples.</label>
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>	<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<!--End mc_embed_signup--><!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Machine Learning: Sentiment Analysis]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>This article demonstrates a simple but effective sentiment analysis algorithm built on top of the <a href="http://burakkanber.com/blog/machine-learning-naive-bayes-1/">Naive Bayes classifier I demonstrated</a> in the last ML in JS article. I'll go over some basic sentiment analysis concepts and then discuss how a Naive Bayes classifier can be modified for sentiment analysis.</p>
<!-- more -->
<p>If</p>]]></description><link>https://burakkanber.com/blog/machine-learning-sentiment-analysis/</link><guid isPermaLink="false">59b43b8b934a21000178fc18</guid><category><![CDATA[ML in JS]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Sat, 09 Nov 2013 17:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>This article demonstrates a simple but effective sentiment analysis algorithm built on top of the <a href="http://burakkanber.com/blog/machine-learning-naive-bayes-1/">Naive Bayes classifier I demonstrated</a> in the last ML in JS article. I'll go over some basic sentiment analysis concepts and then discuss how a Naive Bayes classifier can be modified for sentiment analysis.</p>
<!-- more -->
<p>If you're just looking for the summary and code demonstration, <a href="#liveexample">jump down</a>.</p>
<h2>Introduction</h2>
<p>Compared to the other major machine learning tasks, sentiment analysis has surprisingly little written about it. This is in part because sentiment analysis (and natural language in general) is difficult, but I also suspect that many people opt to monetize their sentiment algorithms rather than publishing them.</p>
<p>Sentiment analysis is highly applicable to enterprise business (&quot;alert me any time someone writes something negative about one of our products anywhere on the internet!&quot;), and sentiment analysis is fresh enough that there's a lot of &quot;secret sauce&quot; still out there. And now that the world is run on social sites like Twitter, Facebook, Yelp, and Amazon (Reviews), there are literally billions of data points that can be analyzed every single day. So it's hard to blame anyone for trying to get a piece of that pie!</p>
<p>Today we'll discuss an &quot;easy&quot; but effective sentiment analysis algorithm. I put &quot;easy&quot; in quotes because our work today will build upon the Naive Bayes classifer we talked about last time; but this will only be &quot;easy&quot; if you're familiar with those concepts already--you may want to review that article before continuing.</p>
<p>There are better, more sophisticated algorithms than the one we'll develop today, but this is a great place to start. As always, I'll follow up with additional articles that cover more advanced topics in sentiment analysis in the future.</p>
<p>I found <a href="http://www.cs.cornell.edu/people/pabo/movie-review-data/" target="_blank">a nice, compact data set</a> for this experiment. It consists of 10,662 sentences from movie reviews, labeled &quot;positive&quot; and &quot;negative&quot; (and split evenly). The primary goal today is to figure out how to tweak the Naive Bayes classifier so that it works well for sentiment analysis.</p>
<h2>Modifying Naive Bayes</h2>
<p>&quot;Naive Bayes Classification&quot; is termed such because it makes the assumption that each word is statistically independent from each other word. In language, however, that assumption doesn't hold true. &quot;England&quot; follows the word &quot;Queen [of]&quot; much more commonly than most other words (&quot;Queen of Asparagus&quot; just isn't something you see every day), so it's clear that words are not independent of one another. Still, it's been shown that the &quot;naive&quot; assumption is pretty good for the purposes of document classification.</p>
<p>And that's good news, because sentiment analysis feels quite a bit like classification: given a document, would you label it &quot;positive&quot; or &quot;negative&quot;? The main difference between classification and sentiment analysis is the idea that classification is objective but sentiment is subjective. But let's make another &quot;naive&quot; assumption and pretend that we don't care about that. Let's try applying Bayes to sentiment and see what happens.</p>
<p>For what it's worth, lots of scientific discoveries are made by people who are willing to &quot;just try it and see what happens&quot;. If it fails, so what? Most experiments do. If it succceds though, that'd be great news!</p>
<p>Still, I don't think we should completely ignore the fact that sentiment is subjective and classification is objective. Subjective language is trickier than objective language because it's prone to idiom, turns of phrase, sarcasm, negation, and other artifacts of emotive language. Detecting what language a sentence is in, for instance, is straightforward because it's built on <em>facts</em>. Did you observe the word &quot;<em>allons-y</em>&quot;? If so, probably French. But consider Borat-ifying a movie review: &quot;I loved this movie... not!&quot; The naive approach may see the word &quot;loved&quot; and label the review positive, but that &quot;not&quot; changes the entire meaning of the sentence.</p>
<p>We should try to move just a little bit away from our assumption that words are independent. One nice way of doing this -- if you have lots of training data -- would be to use bigrams instead of unigrams. If you recall, the training portion of a Bayes classifer involves looking through your training set and counting the number of times a word appears in a class of documents. (Eg: &quot;Clinton&quot; appeared 9% of the time in &quot;politics&quot; articles, but only 0.1% of the time in &quot;cooking&quot; articles.)</p>
<p>Our Bayes classifier can easily be extended to use bigrams just by tokenizing our document two words at a time instead of one! Rather than treating the words &quot;This&quot; &quot;movie&quot; &quot;was&quot; &quot;not&quot; &quot;great&quot; separately -- and risk getting confused by the negation -- all we have to do is record them as pairs: &quot;This movie&quot; &quot;movie was&quot; &quot;was not&quot; &quot;not great&quot;. Now our classifer knows the difference between &quot;was great&quot; and &quot;not great&quot;!</p>
<h2>Entropy</h2>
<p>Sadly, using bigrams poses a real problem for us: it increases our entropy. Entropy is a concept used across lots of fields, but roughly speaking, it's a measure of the number of possible &quot;states&quot; a system can be in. If we use 7,000 different words in conversational English and build a unigram-based Bayes classifer for them, then we'll need to store data (word counts) for only 7,000 words. But if we start using bigrams, we could <em>potentially</em> need to store data for up to 49,000,000 different word <em>pairs</em> (that's our maximum possible value though; in practice we'd probably only encounter 30,000 unique word pairs or so).</p>
<p>But storage space and computational complexity is the least of our concerns (30,000 records is nothing!). The real problem is the lack of training data. Using bigrams and introducing more entropy into our system means that each word pair is going to be relatively rare! A unigram approach might encounter the word &quot;great&quot; 150 times in our training data, but how many times will it see &quot;great movie&quot;? Or &quot;not great&quot;? Or &quot;was great&quot;? Or &quot;seriously great&quot;? The bigram approach is nice, but unless you have a huge training corpus it's probably not the way to go.</p>
<blockquote>Note that there are other ways to combat entropy, and that's a good thing to do even when you're using unigrams. I almost always <em>stem</em> words as part of the tokenization process. Stemming puts word variations like "great", "greatly", "greatest", and "greater" all into one bucket, effectively decreasing your entropy and giving you more data around the concept of "great".</blockquote>
<h2>Dealing with negation without using bigrams</h2>
<p>It turns out that dealing with negations (like &quot;not great&quot;) is a pretty important step in sentiment analysis. A negation word can affect the tone of all the words around it, and ignoring negations would be a pretty big oversight. Bigrams, unfortunately, require too much training data, so we've got to find a better way to consider negation terms.</p>
<p>Fortunately, the solution is &quot;kick-yourself-for-not-thinking-of-it&quot; easy. Here's how I do it: if I see a negation (like &quot;not&quot;, &quot;never&quot;, &quot;no&quot;, etc), I just add an exclamation point to the beginning of every word after it!</p>
<p>The sentence &quot;This movie was not great&quot; turns into &quot;This movie was not !great&quot;, and the token &quot;!great&quot; gets stored in our Bayes classifer as having appeared in a negative review. &quot;Great&quot; appears in positive reviews, and its negation, &quot;!great&quot; appears in negative ones. It's simple, it's clever, and it's effective. Best of all: you get to use a regular Naive Bayes classifer. The only modification you need to make is in your tokenizer (the code that goes through the text, pre-processes it, and splits it up in to words or &quot;tokens&quot;), but the Bayes classification algorithm stays the same.</p>
<blockquote>I ran this experiment's data through a variety of different tokenizers, and in this case I found it's more effective to flag only the word immediately before and after the negation term, rather than all the words until the end of the sentence. My tokenizer takes the sentence "This movie was not good because of the plot" and turns it into "This movie !was not !good because of the plot".</blockquote>
<h2>Being confident</h2>
Another effective trick you can use has nothing to do with the Bayes algorithm itself but rather with how you handle its results. A nice feature of a Bayes classifier is that it outright <em>tells</em> you its "confidence" in its ruling (confidence is in quotes here because this isn't the <em>statistical</em> definition of confidence, I'm just editorializing and calling probability "confidence").
<p>Recall that the output of a Bayes classifier is &quot;the probability that this document is 'negative'&quot;. If you have the luxury of not needing to label every single document you encounter, it may be best to only label documents that have over a certain percentage probability. This approach should make intuitive sense: if you read something and you're only 51% sure it's negative, maybe you shouldn't be labeling that document at all.</p>
<p>In this experiment, setting the &quot;confidence threshold&quot; to 75% or greater increased the classifier's accuracy from 78.5% to 85%, a 6.5 percentage-point difference!</p>
<p>You may not always have the luxury to abstain from guessing, but it makes sense in most cases. For example, if you need to alert a client about negative reviews, you could hit close to 90% accuracy if you only sent alerts out when the probability of being negative was greater than 80% or so.</p>
<h2>Implementation and cross-validation</h2>
<p>I won't do a code walkthrough like I usually do, since the core of this project is just the Naive Bayes classifier we built last time. However, the cross-validation and test procedure is worth talking about.</p>
<p>Cross-validation is how you should be testing your algorithms. In short, here's what you do:</p>
<ul>
	<li>Obtain your training data set.</li>
	<li>Shuffle it up.</li>
	<li>Set 20% (or so) of it aside. Don't use that portion for training.</li>
	<li>Train your algorithm on the other 80% of data.</li>
	<li>Test your algorithm on the 20% you set aside. You test on this portion of the data because your algorithm has never seen it before (it wasn't part of the training set), but it's pre-labeled which means you can:</li>
	<li>Record the algorithm's accuracy (how many did it get right?)</li>
	<li>Optionally, record the algorithm's accuracy more granularly by recording true positives, true negatives, false positives, and false negatives. From this data you can discern not only the overall accuracy, but also the algorithm's "precision" and "recall", which we'll talk about in-depth at a later date.</li>
	<li>Repeat from step 2. I tend to shuffle, retrain, and retest about 30 times in order to get a statistically significant sample. Average your individual run accuracies to get an overall algorithm accuracy.</li>
</ul>
Remember that your algorithm will likely be highly specific to the type of training data you gave it. The program below gets 85% on movie reviews, but if you use it to judge the sentiment of a married couple's conversation it'll probably fall short.
<h2>Overview and results.</h2>
This experiment's goal was simple: use a Naive Bayes classifier for sentiment analysis, and figure out what we can do to boost its accuracy.
<p>I tried and tested 18 different variants of tokenizers and the Bayes classifier, both with and without adjustments for rare tokens, resulting in 36 total tests. Each test was run 30 times, for a total of 1,080 experiments. I found that the least effective tokenizer was the &quot;stemmed, stopword-removed bigram&quot; tokenizer (61.4% accuracy and slow as hell), and the most effective tokenizer had these properties:</p>
<ul>
	<li>Unigram tokenizer (look at one word at a time)</li>
	<li>Tokens were stemmed (with the <a href="https://github.com/kristopolous/Porter-Stemmer" target="_blank">Porter stemmer algorithm</a>; this converts "greater", "greatest", and "greatly" all to "great", thereby giving us more data points for the concept "great" and reducing our entropy)</li>
	<li>Flag any word to the left and right of a negation term (ie, put an exclamation point in front of any word next to "not" or "never" or similar; this turns that word into a different, negatively-connated word as far as Bayes is concerned. "great" becomes distinct from "!great", which implies "not great".)</li>
	<li>Deal with rare tokens by pulling them towards 50% "wordicity" (a term I use in the Bayes article) with a weight of 3 (ie, words we've seen fewer times are forced closer to 50%, because we don't trust them as much).</li>
	<li>Only label a document if we determine the probability to be 75% or greater.</li>
</ul>
The overall accuracy on that algorithm was 85.0%, which was pleasantly surprising to me. Most machine learning algorithms max out near 90%, so this turned out to be very successful for our "introduction to sentiment analysis"!
<h2 id="liveexample">Live example</h2>
<p>Wait for the system to train, and then write a movie-review-like sentence and see if it gets your sentiment right.</p>
<p>I'll be writing at least two more articles about sentiment analysis, so please be sure to ask any questions or make any suggestions you have in the comments below.</p>
<p>If you like this article, or thought it was helpful, please consider:</p>
<ul>
<li>Sharing it with friends on Facebook and Twitter</li>
<li>Discussing it on Hacker News and Reddit</li>
<li>Discussing it in the comments section below</li>
<li><a href="//twitter.com/bkanber" target="_blank">Following me on Twitter @bkanber</a></li>
<li><a href="http://burakkanber.com/blog/machine-learning-in-other-languages-introduction/">Reading my other ML in JS articles</a></li>
<li>Signing up for the ML in JS mailing list below &mdash; I only send emails about new articles, never spam, won't ever sell your info</li>
</ul>
<iframe id="fiddle" width="100%" height="360" src="https://jsfiddle.net/bkanber/DHU7J/embedded/result,js,html,css/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Machine Learning: Naive Bayes Document Classification Algorithm in Javascript]]></title><description><![CDATA[Today we're going to learn a great machine learning technique called document classification. We'll use my favorite tool, the Naive Bayes Classifier.]]></description><link>https://burakkanber.com/blog/machine-learning-naive-bayes-1/</link><guid isPermaLink="false">59b43b8b934a21000178fc19</guid><category><![CDATA[ML in JS]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Wed, 20 Mar 2013 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>Today we're going to learn a great machine learning technique called document classification. We'll use my favorite tool, the Naive Bayes Classifier.</p>
<!-- more -->
<blockquote>
<p>This article is part of the <a title="Machine Learning in Javascript: Introduction" href="http://burakkanber.com/blog/machine-learning-in-other-languages-introduction/" target="_blank">Machine Learning in Javascript</a> series which teaches the essential machine learning algorithms using Javascript for examples. I use Javascript because it's well-known and universally supported, making it an excellent language to use for teaching. There’s a mailing list at the bottom of the page if you want to know about new articles; you can also <a href="https://twitter.com/bkanber" target="_blank">follow me on twitter: @bkanber</a>.</p>
</blockquote>
<blockquote>
<p>Are you just looking for the code example? <a href="http://burakkanber.com/blog/machine-learning-k-means-clustering-in-javascript-part-1/#fiddle">Scroll down!</a></p>
</blockquote>
<h2>Introduction and Motivation</h2>
<p>Document classification is one of my favorite tasks. &quot;Document classification&quot; is exactly what you think it is: given a document and a set of labels, apply the most appropriate label to that document. Labels (or &quot;classes&quot; or &quot;categories&quot;) can be things like:</p>
<ul>
	<li>"spam" or "not spam" (most mail clients use some form of Bayesian spam detection)</li>
	<li>"written by a male" or "written by a female" (yes, there are clues that can hint to the gender of the author)</li>
	<li>"technology", "politics", "finance", "sports" (if you need to automatically categorize old articles from a newspaper)</li>
</ul>
Today we're going to solve a simple problem: <strong>language detection.</strong> Put another way: "given a piece of text, determine if it's in Spanish, English, or French".
<h2>The Very Basics of Natural Language Processing</h2>
First, we'll have to change the way we think about "documents". At their most basic level, documents are just collections of arranged characters. Some characters may be letters, others are not. Letters make words, and words have meaning. Sometimes punctuation alters the meaning of words, other times it doesn't matter too much! (See what I did there?) We typically study documents by studying the individual words in them. Sometimes, if the situation calls for it, we'll look at more than one word at a time (word pairs are called "bigrams"), but since this is only "part 1" of this Bayes series we'll only consider unigrams for now.
<p>Because natural language itself is so quirky and complicated, we generally try to simplify things; we try to reduce the <em>entropy</em> of the system. If you consider both uppercase and lowercase letters, you can create 7.3 million different four-letter words. If you limit yourself to only lowercase letters, that figure drops down to only 450,000. Why is this important? You want your system to use as much data as it can, and treating &quot;YOU'RE&quot; and &quot;you're&quot; and &quot;You're&quot; separately only serves to keep what you learn about each in separate buckets. Converting all of those to a simple &quot;you're&quot; is best, because it'll allow you to study the <em>concept</em> of the word &quot;you're&quot; rather than the various syntaxes of the word.</p>
<p>Of course, more advanced data scientists will recognize that sometimes you <em>do </em>want these quirks in your system. When detecting spam emails, for instance, it turns out that &quot;offer&quot; and &quot;OFFER&quot; are two very different things. Often, spam detection algorithms will <em>not </em>normalize based on case because of this. Similarly, &quot;money back&quot; and &quot;money back!!!!&quot; have two very different meanings, so spam detection algorithms will generally also leave the punctuation intact.</p>
<p>You may also decide that you also want the meanings of the words &quot;imagine&quot;, &quot;imagination&quot;, and &quot;imaginary&quot; to be lumped together. To do so, you might chop off the ending of each, converting them to &quot;imagin&quot; -- it's neither verb nor noun, neither singular nor plural, it's simply a concept. This is called &quot;stemming&quot;, and it serves to treat different words with the same meaning as the same entity. These entropy-reduction techniques are very important in machine learning as a whole, since training sets for learning algorithms are usually limited.</p>
<p>The process of splitting a document up into discrete chunks that you can study is called &quot;tokenization&quot;. For now, we'll keep our tokenization simple: we'll remove any punctuation, make everything lowercase, and split the document up by spaces to get our tokens.</p>
<h2>Bayes' Theorem</h2>
I'm not going to talk about the math around <a href="http://en.wikipedia.org/wiki/Bayes'_theorem" target="_blank">Bayes' theorem</a>, because interested readers can easily learn the basics of probability and Bayes' theorem on their own. Instead, we'll aim to develop an intuition about this important tool in probability.
<p>We're trying to figure out which language a previously unseen document is in. We have a stack of pre-labeled documents in English, French, and Spanish. Since we decided above that we can learn about a document by inspecting the individual words in that document, let's start there.</p>
<p>If you look at a single word in a document, you can easily figure out how many times it appeared in your training data. Using that information, you can determine the probability that a certain language will use a given word. For example: &quot;vous&quot; is the first word in your document of unknown origin. &quot;Vous&quot; may show up in all of your French documents (100%), no Spanish documents, and a small number of English documents (5%). That's a great hint! The document is French!</p>
<p>But no, we can't stop there. Just because &quot;vous&quot; is clearly a French word doesn't mean the document itself is French. It may be an English novel quoting a French character. So we can't just simply look at the &quot;probability that 'vous' is French&quot;, which is what we just tried. Instead, we need to determine the &quot;probability that this document is French given that the word 'vous' is in it&quot;. Fortunately, Bayes' theorem does exactly that. If we apply Bayes' theorem to the fake numbers I gave above, we find that there's a 98% chance that a document is French if &quot;vous&quot; appears in it. The formula to calculate that is quite simple; see <a href="http://en.wikipedia.org/wiki/Bayes'_theorem" target="_blank">Bayes' theorem</a>.</p>
<p>Of course, if the next phrase in the document is &quot;said Jean Pierre, the French museum curator&quot;, we know there's a much smaller chance of the document being French. So we look at each word in turn and calculate the &quot;probability that the document is (French|English|Spanish) given that this word is in it&quot;. We combine those individual probabilities and end up with an overall &quot;probability that this document is French [given that all these words are in it]&quot;. If that probability is high enough, you can act upon it.</p>
<h2>Why it Works</h2>
The Naive Bayes Classifier is so named because it assumes that each word in the document has nothing to do with the next word. That's a naive assumption. But it turns out that, while naive, it's actually a great simplifying assumption; studying words separately like this actually yields very good results. You could also study bigrams or trigrams (sets of two or three words at a time), at which point the classifier is no longer "naive" but it'll require a much larger amount of training data and storage space.
<p>The reason the NB classifier works well for document classification is that it de-correlates the number of times a word is seen in a given language from its statistical importance. The word &quot;a&quot; is found in many languages. Perhaps it even appears in 100% of your English training set. But that doesn't mean that documents that have it are English. We use Bayes to convert the &quot;probability that 'a' appears in an English document&quot; (which is 100%) to the &quot;probability that this document is English because it has 'a' in it&quot; (maybe 50%).</p>
<p>Therefore, the common stuff that's found everywhere is given a very weak significance and the stuff that's found more uniquely across a category is given a much stronger weight. The end result is a very smart, simple algorithm that has low error rates (&quot;low&quot; being a relative term). It's not magic, there's no neural network, there's no &quot;intelligence&quot;, it's just math and probability.</p>
<h2>The Code: Training</h2>
<p>As usual, let's just dive in. The first thing our document classifier needs to be able to do is train itself given a piece of text and a label for that text. Since I decided to build this classifier as generalized as possible, we won't hard code the labels or even put a cap on the number of labels allowed. (Though naive Bayes classifiers with only two possible labels, like spam/ham, <em>are</em> a little bit easier to build.)</p>
<pre><code class="language-javascript">Bayes.train = function (text, label) {
    registerLabel(label);
    var words = tokenize(text);
    var length = words.length;
    for (var i = 0; i &lt; length; i++)
        incrementStem(words[i], label);
    incrementDocCount(label);
};
</code></pre>
<p>The <code>registerLabel</code> function simply adds the label to the &quot;database&quot; (in this case, localStorage) so that we can retrieve a list of labels later.</p>
<p>The <code>tokenize</code> function in this case is very simple. We'll look at more interesting tokenization techniques in another article (tokenization can be an important part of these classifiers), but this one is straight-forward:</p>
<pre><code class="language-javascript">var tokenize = function (text) {
    text = text.toLowerCase().replace(/\W/g, ' ').replace(/\s+/g, ' ').trim().split(' ').unique();
    return text;
};
</code></pre>
<p>In this case, we use <code>unique()</code> because we're only interested in <em>whether</em> a word shows up in a document, and not the number of times it shows up. In certain situations, you may get better results by considering the number of times a word appears in a document.</p>
<p>We then loop through each word (or &quot;token&quot;), and call <code>incrementStem</code> on it. This function is also very simple: it just records the number of times a word was seen for a given label.</p>
<p>Finally, we call <code>incrementDocCount</code>, which records how many documents we've seen for a given label.</p>
<p>The end result of training is that we have a database that stores each label we've ever seen (in our example, it'll hold &quot;english&quot;, &quot;spanish&quot;, and &quot;french&quot;), stores the number of times a word has been seen for a label (eg, &quot;le&quot; was seen in French documents 30 times), and stores the total number of documents for each label (eg, we saw 40 French documents).</p>
<h2>The Code: Guessing</h2>
<p>Training a naive Bayes classifier is dead simple and really fast, as demonstrated above. Guessing a label given a document is a little tougher, but writing the algorithm is easy to those who understand probability. If you don't understand probability, that's ok; you can spend some time reading up on naive Bayes classifiers and you'll always have this example to come back to and study.</p>
<p>The first thing we'll do in our guessing function (other than initializing variables; see the JSFiddle for the minutiae) is a little bit of bookkeeping:</p>
<pre><code class="language-javascript">for (var j = 0; j &lt; labels.length; j++) {
    var label = labels[j];
    docCounts[label] = docCount(label);
    docInverseCounts[label] = docInverseCount(label);
    totalDocCount += parseInt(docCounts[label]);
}
</code></pre>
<p>Our goal here is to set ourselves up for calculating certain probabilities later. To do this, we need to know the number of documents we've seen for a given label (docCounts), but we also need to know the number of documents <em>not</em> in that label (docInverseCounts). Finally, we need to know the total number of documents we've ever seen.</p>
<p>You could flip this function upside down and get docInverseCount simply by subtracting a label's docCount from the totalDocCount -- in fact, that approach is better and faster, but I did it with an explicit docInverseCount function because it reads a little easier.</p>
<p>Given the above information we can determine, for example, the probability that any arbitrary document would be French. We also know the probability that any document is NOT French.</p>
<pre><code class="language-javascript">for (var j = 0; j &lt; labels.length; j++) {
    var label = labels[j];
    var logSum = 0;
    ...
</code></pre>
<p>Next, we look at each label. We set up a <code>logSum</code> variable, which will store the probability that the document is in this label's category.</p>
<pre><code class="language-javascript">for (var i = 0; i &lt; length; i++) {
    var word = words[i];
    var _stemTotalCount = stemTotalCount(word);
    if (_stemTotalCount === 0) {
        continue;
    } else {
        var wordProbability = stemLabelCount(word, label) / docCounts[label];
        var wordInverseProbability = stemInverseLabelCount(word, label) / docInverseCounts[label];
        var wordicity = wordProbability / (wordProbability + wordInverseProbability);

        wordicity = ( (1 * 0.5) + (_stemTotalCount * wordicity) ) / ( 1 + _stemTotalCount );
        if (wordicity === 0)
            wordicity = 0.01;
        else if (wordicity === 1)
            wordicity = 0.99;
   }

    logSum += (Math.log(1 - wordicity) - Math.log(wordicity));
}
scores[label] = 1 / ( 1 + Math.exp(logSum) );
</code></pre>
<p>The above is the meat of the algorithm. For each label we're considering, we look at each word in the document. The _stemTotalCount variable holds the number of times we've seen that word in <em>any</em> document during training. If we've never seen this word before, just skip it! We don't have any information on it, so why use it?</p>
<p><code>wordProbability</code> represents the &quot;probability that this word shows up in a [French|English|Spanish] document&quot;. If you've seen 40 French documents, and 30 of them have the word &quot;le&quot; in them, this value is 0.75. <code>wordInverseProbability</code> is the probability that the word shows up in any other category than the one we're considering.</p>
<p>The funny <code>wordicity</code> variable is what happens when you apply Bayes' theorem to the two probabilities above. While the wordProbability variable represents &quot;the probability that [le] shows up in a [French] document&quot;, the wordicity variable represents &quot;the probability that this document is [French] given that [le] is in it&quot;. The distinction is subtle but very important. If you're having trouble understanding the distinction at this point, I strongly recommend saying those two phrases out loud and making sure you understand the difference before moving on.</p>
<p>The wordicity line above also makes the assumption that English, French, and Spanish documents are all equally common and starting off on the same footing. This assumption makes the calculation a little simpler, but you can consider the <em>a priori</em> probabilities of each language if you'd like. A note on that later.</p>
<p>The line below the wordicity definition is an optional <em>adjustment</em> for words that we've only seen in training a few times. If you've only seen a word once, for instance, you don't really have enough information about that word to determine if it's really French or Spanish. So we make a weighted adjustment: we bring the wordicity closer to 50% if we haven't seen it too many times. The &quot;0.5&quot; in that equation is the value we should try to adjust towards, and the &quot;1&quot;s in the equation are the weight -- if you increase this value, the wordicity will remain close to 0.5 longer. If you have a large training set, you can make the weight 5 or 10 or 20 or 50 (depending on how big your training set is). Since we have a very small training set, I made this value 1 but realistically I should have just omitted the line completely (my training set is only 15 paragraphs). I just wanted to show you that adjusting for rare words is something that you can do.</p>
<p>Below that, we avoid letting wordicity be either 0 or 1 since we're about to use a log function on our data, and either of those values would kind of mess up the results.</p>
<p>The logSum line isn't really a part of the mathematical equations, but is rather a practical consideration. After calculating the wordicity for each word, we need to combine those probabilities somehow. The normal mathematical way to do that would be to multiply each probability together and divide by the multiplication of all the inverses. Unfortunately, floating point math isn't perfect and you can run into &quot;floating point underflow&quot;, where the number gets too small for floating point math to deal with. So instead, we take a log of the numerator and denominator (combined probabilities and their inverses), and add up the logs.</p>
<p>Finally, after we've combined all the individual word probabilities with the logSum line, we undo the log function we just used to get the probability back in the 0 to 1 range. Note that this happens outside of the &quot;look at each word&quot; loop but still inside the &quot;look at each label&quot; loop.</p>
<h2>Important Assumptions and Caveats</h2>
<p>One thing I'd like to point out is that the above makes a big simplifying assumption: we've assumed that English, French, and Spanish documents are all <em>equally likely</em> to appear. In our example, this is a good assumption since you guys are probably going to test one of each later, but in the real world this isn't necessarily true.</p>
<p>The Bayes classification algorithm does actually let you consider the <em>a priori</em> probability of a document's language (meaning, the probability that a document is English just based on the number of English documents out there, before considering the actual contents of the document), but I've simply left this out. It's not too hard to put in; adding just a few more terms to the wordicity calculation can do this. The next Bayes article I write will use the full form of Bayes theorem.</p>
<p>Finally, please note that I was <em>really lazy</em> while training this algorithm. You can see from the JSFiddle that I've only used 5 paragraphs from each language to train the thing on. That's not nearly enough to go by, as the words seen during training are the only words it knows. I've found that this example <em>does</em> work well if you type in sentences or paragraphs (try just copy/pasting stuff from news sites), but simple nouns and phrases probably won't work. For example, you'll get the wrong result for &quot;la tortuga&quot; (&quot;the turtle&quot; in Spanish) simply because we never showed it the word &quot;tortuga&quot; before. The algorithm will guess French in this case because it's seen slightly more &quot;la&quot;s in French than it's seen in Spanish. A larger training set would fix this issue.</p>
<h2>Results</h2>
<p>We're basically done. All we have to do now is either report all the labels' probabilities or just pluck out the highest one. Try pasting some English, French, or Spanish news text in the JSFiddle below -- you should see the guessed language and the probability that led us to guess that language. This example works better with sentences or paragraphs; the more words you give it to guess by, the better the chance that it has seen one of those words in its limited training set.</p>
<p>So far, I've had 100% accuracy when copying and pasting sentences from news sites. Try it below and see for yourself!</p>
<p>If you like this article, or thought it was helpful, please consider:</p>
<ul>
<li>Sharing it with friends on Facebook and Twitter</li>
<li>Discussing it on Hacker News and Reddit</li>
<li>Discussing it in the comments section below</li>
<li><a href="//twitter.com/bkanber" target="_blank">Following me on Twitter @bkanber</a></li>
<li><a href="http://burakkanber.com/blog/machine-learning-in-other-languages-introduction/">Reading my other ML in JS articles</a></li>
<li>Signing up for the ML in JS mailing list below &mdash; I only send emails about new articles, never spam, won't ever sell your info</li>
</ul>
<iframe id="fiddle" width="100%" height="300" src="https://jsfiddle.net/bkanber/gNrdF/embedded/result,js,html,css/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<div id="mc_embed_signup">
<form action="http://burakkanber.us5.list-manage.com/subscribe/post?u=3269dc566d381f05852d92aa8&amp;id=3f5451bda5" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
	<h2>Email me when new ML in JS articles are posted</h2>
<div class="mc-field-group">
	<label for="mce-EMAIL">Email Address </label><input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group input-group">
    <strong>Survey: Would you buy an ML in JS e-book? </strong>
    <input type="checkbox" value="1" name="group[6613][1]" id="mce-group[6613]-6613-0"><label for="mce-group[6613]-6613-0">I would pay $10 for a DRM-free e-book with tons of ML lessons and JS examples.</label>
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div></div>	<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<!--End mc_embed_signup--><!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Machine Learning: k-Means Clustering Algorithm in Javascript]]></title><description><![CDATA[Today we're going to figure out how to find clusters of data points. Given a set of data points, how do you find the center of the clusters in that data?]]></description><link>https://burakkanber.com/blog/machine-learning-k-means-clustering-in-javascript-part-1/</link><guid isPermaLink="false">59b43b8b934a21000178fc1b</guid><category><![CDATA[ML in JS]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Mon, 15 Oct 2012 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>Machine learning helps us navigate and process large volumes of data. We can ask all sorts of questions about our data, and hope that ML can answer them: what is this data point most similar to? Does the data come in patterns? Can we predict what will happen in the future, given past trends? These questions are applicable to all fields of study.</p>
<!-- more -->
<blockquote>
<p>This article is part of the <a href="http://burakkanber.com/blog/machine-learning-in-other-languages-introduction/" title="Machine Learning in Javascript: Introduction" target="_blank">Machine Learning in Javascript</a> series. The series covers some of the essential machine learning algorithms and assumes little background knowledge. There's also a mailing list at the bottom of the page if you want to know about new articles; you can also <a href="https://twitter.com/bkanber" target="_blank">follow me on twitter: @bkanber</a>.</p>
</blockquote>
<blockquote>
<p>Are you just looking for the code example? <a href="#fiddle">Scroll down!</a></p>
</blockquote>
<h2>Introduction and Motivation</h2> 
<p>Today we're going to figure out how to find clusters of data points. Let's say you work at a medical imaging devices company. Imagine you already have a way to identify malignant cells from an image scan, but it would be great to automatically identify the centers of clusters of cells as well. Then a robot could go in with surgical precision and remove the problem!</p>
<p>What we're looking for is a clustering algorithm; today we're going to talk specifically about the k-means algorithm.</p>
<h2>Clustering</h2>
<p>Clustering algorithms, in general, find groups of similar pieces of data. If you run an online store you might use a clustering algorithm to identify different shopper types. You may find that you have one type of visitor that just window shops through 3-5 pages of products and leaves. Another group might make meticulous purchasing decisions by looking through 15 pages of products and reviews and end up making only one, high-value purchase. And you may also identify the impulse buyer, who makes numerous small purchases without browsing too deeply. Once you've identified your e-shopper demographics, you're better able to optimize your site to increase sales. You can release features that appeal to your impulse buyers, because now you know that you <em>have </em>impulse buyers!</p>
<p>And while that's just one practical example of k-means, you'll find this algorithm used in multiple fields. Sometimes it's just image processing in 2 dimensions, other times it's processing huge data across dozens of dimensions and parameters. Like our k-nearest-neighbor algorithm, k-means is versatile, simple to understand and implement, and sneakily powerful.</p>
<h2>k-means</h2>
Like k-nearest-neighbor, the "k" in k-means gives away that there's going to be some number that we're going to have to feed to our algorithm. Specifically, "k" is the number of clusters we're going to find in our data. Unfortunately, it's rarely possible to know the number of clusters before you solve the problem, so k-means is usually supplemented by another algorithm that first helps you find the best value of <em>k</em>.
<p>The issue is this: the k-means algorithm will partition your data into &quot;k&quot; distinct clusters, but it does not tell you if that's the <em>correct </em>number of clusters. Your data might naturally have 5 different clusters in it, but if you feed k-means the number 3 you'll get 3 clusters back. Those clusters will be bigger, looser and more awkwardly shaped than if you had told it to find 5 clusters.</p>
<p>The long and short of it is this: in order to use k-means you either need to know how many clusters you're looking for at the outset, <em>or </em>you have to use a second algorithm to also guess the number of clusters. K-means just organizes your points into clusters; you need to do something else to figure out the right number of clusters.</p>
<p>For today we'll contrive a situation and use three clusters from the outset. Next time (in k-means part 2) we'll look at a technique you can use to automatically guess the value of &quot;k&quot;. Most often, these algorithms rely on some kind of error analysis and multiple passes of the k-means algorithm in order to optimize for the solution with the smallest error value.</p>
<h2>The Procedure</h2>
The k-means algorithm is simple but can become very powerful if you're using it on a dataset with many dimensions. Today we're going to work in 2 dimensions, but next time we'll do something more complicated. Here's what the algorithm looks like:
<ol>
	<li>Plot your data points</li>
	<li>Create "k" <em>additional</em> points, placing them randomly on your graph. These points are the "cluster centroids" -- or the candidates for the centers of your clusters.</li>
	<li>Repeat the following:
<ol>
	<li>"Assign" each data point to the cluster centroid closest to it</li>
	<li>Move the centroid to the average position of all the data points that belong to it</li>
	<li>If any of the centroids moved in the last step, repeat. If nothing moved, exit.</li>
</ol>
</li>
</ol>
<div>It's that simple! As you can see, this is an iterative process. It may take 2 or 3 or dozens of iterations, but eventually your cluster centroids should converge to their solutions and stop moving. You then take the final tally of the assignments and then you have your clusters.</div>
<h2>Committee of Machines</h2>
This algorithm, like many of the one we'll play with in this series, is susceptible to local optima. If you run the example below a few times you'll see that the clusters can end up in one of a few different configurations. These are various local optima that the solution gets stuck in. Algorithms that start with some sort of random seed state (like GAs or k-means) are particularly susceptible to local optima, because you never really know how the algorithm will start off and which path the solution will end up following. Will this seed state lead to a local or global optima? There's no way of knowing!
<p>Like in genetic algorithms, one way to shake out of local optima is to give the solution a little bit of mutation. In our k-means example, we could add a rule that gives a centroid a nudge in a random direction if it doesn't move after an iteration. It might settle back into its last resting place, or it may find a new solution. The nudge shouldn't be big enough that it restarts the solution from the beginning, but just enough to kick a centroid out of a local valley, if it's in one.</p>
<p>Another technique we could use is called the &quot;committee of machines&quot;, which works well if you're running an algorithm that finishes pretty quickly, or if you have parallel computing capabilities. It's simple: we run the k-means algorithm 3 or 5 or 51 or 10,000 times, and choose the solution that it returned the most often. The term &quot;committee of machines&quot; alludes to the fact that some people choose to actually run parallel algorithms on different pieces of hardware, and a literal committee of machines votes on the solution.</p>
<h2>The Code</h2>
Let's dive in. Unlike my other examples thus far, I'm going to forego an object-oriented implementation and just go straight procedural. There are many ways to skin a cat. I love OOP but it's important not to get too comfortable in habits!
<p>Additionally, while we're only working with 2 dimensional data in this example, I'd like to write this algorithm out to handle any number of dimensions (except for the canvas drawing functions).</p>
<p>Let's take a look at the data we're using -- a simple array of &quot;points&quot;, which are just represented by 2-element arrays (for X and Y values):</p>
<pre><code class="language-javascript">var data = [
	[1, 2],
	[2, 1],
	[2, 4], 
	[1, 3],
	[2, 2],
	[3, 1],
	[1, 1],

	[7, 3],
	[8, 2],
	[6, 4],
	[7, 4],
	[8, 1],
	[9, 2],

	[10, 8],
	[9, 10],
	[7, 8],
	[7, 9],
	[8, 11],
	[9, 9],
];
</code></pre>
<p>Next, we define two functions that are helpful to us, but not essential. Given a list of points, I'd like to know what the max and min values for each dimension are, and what the range of each dimension is. I want to know &quot;X ranges from 1 to 11, and Y ranges from 3 to 7&quot;. Knowing these figures helps us draw the graph on the canvas, and also helps when we initialize our random cluster centers (we'd like them to be within the range of the data points when we start them out).</p>
<p>Keeping in mind that we're writing this to be generic with regards to the number of dimensions they can handle:</p>
<pre><code class="language-javascript">function getDataRanges(extremes) {
	var ranges = [];

	for (var dimension in extremes)
	{
		ranges[dimension] = extremes[dimension].max - extremes[dimension].min;
	}

	return ranges;

}

function getDataExtremes(points) {
	
	var extremes = [];

	for (var i in data)
	{
		var point = data[i];

		for (var dimension in point)
		{
			if ( ! extremes[dimension] )
			{
				extremes[dimension] = {min: 1000, max: 0};
			}

			if (point[dimension] &lt; extremes[dimension].min)
			{
				extremes[dimension].min = point[dimension];
			}

			if (point[dimension] &gt; extremes[dimension].max)
			{
				extremes[dimension].max = point[dimension];
			}
		}
	}

	return extremes;
}
</code></pre>
<p>The <code>getDataExtremes()</code> method loops through all the points and each dimension in each point and finds the min and max values (note there's a hard-coded &quot;1000&quot; in there, which you should change if you're using large numbers). The <code>getDataRanges()</code> function is just a helper that takes that output and returns the range of each dimension (the maximum value minus the minimum value).</p>
<p>Next up, we define a function that initializes <em>k</em> random cluster centroids:</p>
<pre><code class="language-javascript">function initMeans(k) {

	if ( ! k )
	{
		k = 3;
	}

	while (k--)
	{
		var mean = [];

		for (var dimension in dataExtremes)
		{
			mean[dimension] = dataExtremes[dimension].min + ( Math.random() * dataRange[dimension] );
		}

		means.push(mean);
	}

	return means;

};
</code></pre>
<p>We're just creating new points with random coordinates within the range and dimensions of our dataset.</p>
<p>Once we have our randomly seeded centroids, we need to enter our k-means loop. As a reminder, the loop consists of first assigning all our data points to the centroid closest to it, then moving the centroids to the average position of all the data points assigned to it. We repeat that until the centroids stop moving.</p>
<pre><code class="language-javascript">function makeAssignments() {

	for (var i in data)
	{
		var point = data[i];
		var distances = [];

		for (var j in means)
		{
			var mean = means[j];
			var sum = 0;

			for (var dimension in point)
			{
				var difference = point[dimension] - mean[dimension];
				difference *= difference;
				sum += difference;
			}

			distances[j] = Math.sqrt(sum);
		}

		assignments[i] = distances.indexOf( Math.min.apply(null, distances) );
	}

}
</code></pre>
<p>The above function is called by our &quot;loop&quot; function and calculates the <a href="http://en.wikipedia.org/wiki/Euclidean_distance" target="_blank">Euclidean distance</a> between each point and the cluster center.</p>
<p>Note that the above algorithm loops through each point and then loops through each cluster centroid, making this an O(k*n) algorithm. It's not terrible, but it might be computationally intensive if you have a large number of data points or a large number of clusters or both. There are ways you can optimize this, which we'll perhaps discuss in a future article. For one, we can try to eliminate the expensive <code>Math.sqrt()</code> call; we could also try not to iterate through every point.</p>
<p>Once we have our list of assignments -- in this case, just an associative array of <code>point index =&gt; center index</code> -- we can go ahead and update the positions of the means (the cluster centers).</p>
<pre><code class="language-javascript">function moveMeans() {

	makeAssignments();

	var sums = Array( means.length );
	var counts = Array( means.length );
	var moved = false;

	for (var j in means)
	{
		counts[j] = 0;
		sums[j] = Array( means[j].length );
		for (var dimension in means[j])
		{
			sums[j][dimension] = 0;
		}
	}

	for (var point_index in assignments)
	{
		var mean_index = assignments[point_index];
		var point = data[point_index];
		var mean = means[mean_index];

		counts[mean_index]++;

		for (var dimension in mean)
		{
			sums[mean_index][dimension] += point[dimension];
		}
	}

	for (var mean_index in sums)
	{
		console.log(counts[mean_index]);
		if ( 0 === counts[mean_index] ) 
		{
			sums[mean_index] = means[mean_index];
			console.log(&quot;Mean with no points&quot;);
			console.log(sums[mean_index]);

			for (var dimension in dataExtremes)
			{
				sums[mean_index][dimension] = dataExtremes[dimension].min + ( Math.random() * dataRange[dimension] );
			}
			continue;
		}

		for (var dimension in sums[mean_index])
		{
			sums[mean_index][dimension] /= counts[mean_index];
		}
	}

	if (means.toString() !== sums.toString())
	{
		moved = true;
	}

	means = sums;

	return moved;

}
</code></pre>
<p>The <code>moveMeans()</code> starts by calling the <code>makeAssignments()</code> function. Once we have our assignments, we initialize two arrays: one called &quot;sums&quot; and the other called &quot;counts&quot;. Since we're calculating the arithmetic mean (or average), we'll need to know the sum of points' dimensions as well as the number of points whose dimensions we're averaging.</p>
<p>We then hit three loops:</p>
<p>First we loop through our means and prepare our <em>sums</em> and <em>counts</em> arrays. Our <em>sums</em> array will actually be multidimensional, because we're storing each dimension's sum of each point of each mean in this structure -- so we have to zero-out the second-depth level of this 2 dimensional array.</p>
<p>Then we loop through our assignments and increment the <em>counts</em> counter for each cluster center we have points assigned to, and additionally loop through the point's dimensions to fill in the <em>sums</em> array. At this point we have all the data we need to calculate the new positions of the cluster centers.</p>
<p>The final loop loops through our results, calculates the mean position for each cluster center, and moves it. The final loop also checks to see if a cluster center had <em>no</em> points assigned to it. If it didn't have any points assigned to it, we give it a new random position. This is just us trying to kick that cluster center back into the solution.</p>
<p>Finally, we wrap up this function by checking to see if any one of our cluster centers has moved -- and we return either true or false.</p>
<p>To get this algorithm started, we run the following setup functions:</p>
<pre><code class="language-javascript">function setup() {

	canvas = document.getElementById('canvas');
	ctx = canvas.getContext('2d');

	dataExtremes = getDataExtremes(data);
	dataRange = getDataRanges(dataExtremes);
	means = initMeans(3);

	makeAssignments();
	draw();

	setTimeout(run, drawDelay);
}

function run() {

	var moved = moveMeans();
	draw();

	if (moved)
	{
		setTimeout(run, drawDelay);
	}

}
</code></pre>
<p><code>setup()</code> initializes everything we need, and then our <code>run()</code> function checks to see if the algorithm has stopped, and loops based on a timer so that we can watch the algorithm do its work in a reasonable timeframe.</p>
<h2>k-medians</h2>
<p>One major issue with the k-means algorithm isn't a fault of the algorithm's, but rather of the concept of the arithmetic mean, or average. The average is a pretty bad metric when you have outlying data.</p>
<p>If you work at a company where 5 people make $50,000 a year but one person makes $1,000,000, the <em>median</em> salary is $50,000 (very representative of salary at that company), but the <em>mean</em> salary is $200,000 (not at all representative of salary at that company)!</p>
<p>This happens with all sorts of data, and can and will happen in the k-means algorithm too. If you have a dataset prone to outliers, you'll find that k-means gets &quot;stuck&quot; on the outlier and ends up yielding poor results. In that case, switch to k-medians! The algorithm is nearly the same; instead of calculating the mean for your cluster centers, use the median instead. I believe -- but I'm not certain -- that calculating the median also has a performance advantage over the mean.</p>
<h2>Results</h2>
<p>As you can see from the example below, k-means works very well for our nice, neat data. Obviously it'll have more difficulty with messy data, like any other algorithm.</p>
<p>If you run the example below a number of times (click the play button on the JSFiddle) you'll eventually see it fall into a local optimum. This should also demonstrate the usefulness of the &quot;committee of machines&quot; solving method: while a bad solution does pop up from time to time, it should be clear that a committee of machines will produce the correct solution reliably.</p>
<p>Finally, if you like this series, please sign up for the mailing list below and tell your friends! I also appreciate discussion, so feel free to use the commenting tool below. And make sure to check out the other <a href="http://burakkanber.com/blog/modeling-physics-in-javascript-introduction/" title="Modeling Physics in Javascript: Introduction" target="_blank">ML in JS articles</a>!</p>
<iframe id="fiddle" style="width: 100%; height: 500px; border:1px solid #ccc;" src="https://jsfiddle.net/bkanber/8NpNp/embedded/result,js,html,css/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<div id="mc_embed_signup">
<form action="http://burakkanber.us5.list-manage.com/subscribe/post?u=3269dc566d381f05852d92aa8&amp;id=3f5451bda5" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
	<h2>Email me when new ML in JS articles are posted</h2>
<div class="mc-field-group">
	<label for="mce-EMAIL">Email Address </label><input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group input-group">
    <strong>Survey: Would you buy an ML in JS e-book? </strong>
    <input type="checkbox" value="1" name="group[6613][1]" id="mce-group[6613]-6613-0"><label for="mce-group[6613]-6613-0">I would pay $10 for a DRM-free e-book with tons of ML lessons and JS examples.</label>
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>	<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<!--End mc_embed_signup--><!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Machine Learning: Genetic Algorithms in Javascript Part 2]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>Today we're going to revisit the genetic algorithm. If you haven't read <a title="Machine Learning: Genetic Algorithms Part 1 (Javascript)" href="http://burakkanber.com/blog/machine-learning-genetic-algorithms-part-1-javascript/">Genetic Algorithms Part 1</a> yet, I strongly recommend reading that now. This article will skip over the fundamental concepts covered in part 1 -- so if you're new to genetic algorithms you'll definitely want to start there.</p>
<!-- more -->
<p>Just</p>]]></description><link>https://burakkanber.com/blog/machine-learning-genetic-algorithms-in-javascript-part-2/</link><guid isPermaLink="false">59b43b8b934a21000178fc1d</guid><category><![CDATA[ML in JS]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Sat, 15 Sep 2012 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>Today we're going to revisit the genetic algorithm. If you haven't read <a title="Machine Learning: Genetic Algorithms Part 1 (Javascript)" href="http://burakkanber.com/blog/machine-learning-genetic-algorithms-part-1-javascript/">Genetic Algorithms Part 1</a> yet, I strongly recommend reading that now. This article will skip over the fundamental concepts covered in part 1 -- so if you're new to genetic algorithms you'll definitely want to start there.</p>
<!-- more -->
<p>Just looking for <a href="#fiddle">the example?</a></p>
<h2>The Problem</h2>
You're a scientist that has recently been framed for murder by an evil company. Before you flee the lab you have an opportunity to steal 1,000 pounds (or kilograms!) of pure elements from the chemical warehouse; your plan is to later sell them and survive off of the earnings.
<blockquote>Given the weight and value of each element, which combination should you take to maximize the total value without exceeding the weight limit?</blockquote>
This is called <a href="http://en.wikipedia.org/wiki/Knapsack_problem" target="_blank">the knapsack problem</a>. The one above is a one-dimensional problem, meaning the only constraint is weight. We could complicate matters by also considering volume, but we need to start somewhere. Note that in our version of the problem only one piece of each element is available, and each piece has a fixed weight. There are some knapsack problems where you can take unlimited platinum or up to 3 pieces of gold or something like that, but here we only have one of each available to us.
<p>Why is this problem tough to solve? We'll be using 118 elements. The brute-force approach would require that we test 2<sup>118</sup> or 3.3 * 10<sup>35</sup> different combinations of elements.</p>
<h2>Greedy Algorithm</h2>
A quick benchmark we'll use for our solution is called the "greedy" solution. The greedy algorithm grabs the most valued items and puts them into the knapsack until it can't fit any more.
<p>Sometimes this works great. Sometimes it doesn't. Imagine that there's a piece of gold in the warehouse that's valued at $1,000 but weighs 600 pounds. And there's also a piece of cadmium that has a value of $950 but only weighs 300 pounds, and there are a bunch of other elements that have a pretty high value but reasonably light weights. The greedy algorithm still tosses gold in there, and all that precious available weight is taken up by something that's not really worth it.</p>
<p>The &quot;naive&quot; greedy algorithm for our dataset will give us a total value of $3649 with a total weight of 998 pounds.</p>
<p>You may at this point be thinking &quot;why don't we just figure out value <em>per pound</em> for each element and use that?&quot; Sure, that works too! It will, in fact, work way better than the above.</p>
<p>Using that approach, the &quot;weighted&quot; greedy algorithm gives us a total value of $4901 and a total weight of 969.</p>
<p>So those are our numbers to beat: we should expect to handily beat $3,649, and we'll be happy if we also beat $4,901.</p>
<p>Why does the greedy algorithm work well for this type of problem? Because the greedy algorithm is solving for the &quot;highest value per unit weight&quot; and that's very close to what we want to fill our knapsack with. However, the greedy algorithm will not perform well in instances where there's a large range of weights and values. That is, the greedy algorithm will perform better if the range of values (and/or weights) of the elements is between $1 - $100, but will perform worse if the range is $1 - $500.</p>
<blockquote>Respond in the comments: why would the greedy algorithm perform worse with a larger range of weights and values?</blockquote>
Our GA might lose to the greedy algorithm from time to time, but that's ok. The GA will continue to perform well as complexity increases, but the greedy algorithm will not.
<p>So we're still tackling a pretty simplified and contrived problem here, but it's certainly more complex and useful than our &quot;Hello, World!&quot; from the last article. Let's get started.</p>
<h2>Key Differences From "Hello World"</h2>
There are some major differences between our problem and the previous "Hello, World!":
<ul>
	<li>We can't use elements (genes) more than once, while "Hello, World!" can (must!) use letters more than once.</li>
	<li>In the "Hello, World!" example, we knew that the string needed to be 13 characters long. Here we don't know how many elements to take.</li>
	<li>We don't know the highest possible value ("fitness" or "score") for this problem. It could be $4,901 like the greedy algorithm guessed, or it could be $10,000, or $23,304</li>
</ul>
<h2>Representing the Chromosome</h2>
The "Hello, World!" algorithm represented the chromosome as a string. Mutating involved randomly changing a letter. Mating (or crossover, as it's really called) involved splicing two strings together at the halfway point. We need to do things a little differently here.
<p>It turns out that representing our solution requires a little more finesse than &quot;Hello, World!&quot;. Since we don't know how many elements to choose, we can't use a fixed length string. (Just the first of our problems!)</p>
<p>Instead, I propose we use a &quot;bitmask&quot; of sorts. We don't have to use an actual bitmask, but my proposal is to use a representation of <em>all</em> of the available elements, and set each &quot;present&quot; or not.</p>
<p>Our chromosome could look like this:</p>
<pre class="code">Helium: present
Hydrogen: not present
Lithium: not present</pre>
<p>And et cetera for all 118 elements. Or if you want to go the bitmask route:</p>
<pre class="code">10000011000001000100000010000010010010000</pre>
<p>Where each bit represents a single element and the value of the bit indicates whether that element is in the knapsack or not.</p>
<p>Additionally, if we were to allow more than one of each element, the representation could look like so:</p>
<pre class="code">Helium: 0
Hydrogen: 4
Lithium: 2</pre>
<p>What would <em>not</em> work well is the following:</p>
<pre class="code">In Knapsack: Helium, Lithium, Lead, Tin</pre>
<p>The above makes mating more difficult. You can make it work, but it feels like you'd be jumping through hoops to pull it off. Structure feels better for this problem.</p>
<p>We have a specific difficulty with mating: we need to make sure that even after mating and mutation we still only have at most one of each element in the list. Using the bitmask approach will help us to that end, but that's a common pitfall when trying the list approach above.</p>
<blockquote>The difficulty of making sure something happens only once in a chromosome is a common one. If you're familiar with the traveling salesman problem, it's easy to imagine a scenario where you mate two solutions and end up visiting the same city twice. That city appeared in the first half of the first parent and the second half of the second parent -- therefore appearing nowhere in one child but twice in the other child.</blockquote>
<h2>Overweight Populations</h2>
For this problem we're going to keep track of three properties of the population: weight, value, and <em>score</em>.
<p>Score is the same thing as value, with one difference: score accounts for the population being overweight.</p>
<p>You may be tempted to throw out overweight populations completely. It's a natural instinct because overweight solutions are not acceptable solutions! But there's a good, practical reason we don't want to throw out overweight chromosomes: there will be some slightly overweight (1,001 pounds) chromosomes that have very high values and just need to be &quot;tweaked&quot; a little to bring them within the weight range.</p>
<p>There could be a lot of potential in some of the overweight chromosomes. Rather than killing them, we'll penalize them just enough that they still get to reproduce, but are unlikely to be the #1 pick. That's what we'll use &quot;score&quot; for. If you're underweight, then your score is just your total value. If you're overweight, however, we'll penalize you 50 points for every pound over weight. Feel free to play with this number.</p>
<p>Evolutionarily, this &quot;encourages&quot; promising chromosomes to drop some weight. All they need is a little tweaking. There's no use in throwing out a potentially strong candidate!</p>
<p>We'll cover the specifics of mating and mutation and the important of death (really called &quot;elitism&quot;) as we're looking at the code.</p>
<h2>The Code</h2>
First, let's take a look at the data set. I wrote a simple PHP script that generates random weights and values (ranged 1 - 500) for each element and outputs the set as JSON. It looks something like this:
<pre><code class="language-javascript">&quot;Hydrogen&quot;:{
	&quot;weight&quot;:389,
	&quot;value&quot;:400},
&quot;Helium&quot;:{
	&quot;weight&quot;:309,
	&quot;value&quot;:380},
&quot;Lithium&quot;:{
	&quot;weight&quot;:339,
	&quot;value&quot;:424},
&quot;Beryllium&quot;:{
	&quot;weight&quot;:405,
	&quot;value&quot;:387},
&quot;Boron&quot;:{
	&quot;weight&quot;:12,
	&quot;value&quot;:174},
</code></pre>
<p>And so on.</p>
<p>We then define three quick and easy helper functions:</p>
<pre><code class="language-javascript">function length(obj) {
	var length = 0;
	for (var i in obj)
		length++;
	return length;
}

function clone(obj) {
	obj = JSON.parse(JSON.stringify(obj));
	return obj;
}

function pickRandomProperty(obj) {
    var result;
    var count = 0;
    for (var prop in obj)
        if (Math.random() &amp;lt; 1 / ++count)
           result = prop;
    return result;
}
</code></pre>
<p>The 'length' property only exists for javascript arrays, so we create a length() function that works for objects.</p>
<p>We create a clone function that ensures our element objects aren't passed by reference.</p>
<p>Finally, we create a function that picks a random property of an object. This is an analog to PHP's 'array_rand' function, which returns a random array key.</p>
<h2>Chromosome Functions</h2>
```javascript
var Chromosome = function(members) {
	this.members = members;
	for (var element in this.members)
	{
		if (typeof this.members[element]['active'] == 'undefined')
		{
			this.members[element]['active'] = Math.round( Math.random() );
		}
	}
	this.mutate();
	this.calcScore();
};
<p>Chromosome.prototype.weight = 0;<br>
Chromosome.prototype.value = 0;<br>
Chromosome.prototype.members = [];<br>
Chromosome.prototype.maxWeight = 1000;<br>
Chromosome.prototype.mutationRate = 0.7;<br>
Chromosome.prototype.score = 0;</p>
<pre><code>
The chromosome constructor takes an object of 'members'. In this case, we'll either be passing our original list of elements data when we're creating a brand new chromosome, &lt;em&gt;or&lt;/em&gt; we'll be passing in the results of a mating operation.

The constructor randomly activates elements if the 'active' property isn't yet defined. The end result is that this will create a random chromosome if we're creating one from scratch, and it'll leave a pre-configured chromosome alone.

The prototype also specifies some defaults. The mutationRate property is the chance that a chromosome will mutate.
```javascript
Chromosome.prototype.mutate = function() {
	if (Math.random() &amp;gt; this.mutationRate)
		return false;
	var element = pickRandomProperty(this.members);
	this.members[element]['active'] = Number(! this.members[element]['active']);
};
</code></pre>
<p>The mutate method is most similar to the &quot;Hello, World!&quot; example. If the chromosome is to mutate then we simply pick an element at random and toggle its 'active' property. I cast to Number here. It would have been more semantic to cast the Math.random() in the constructor to Boolean. I'll ignore this, as I've already pasted all the code into this post.</p>
<pre><code class="language-javascript">Chromosome.prototype.calcScore = function() {
	if (this.score)
		return this.score;

	this.value = 0;
	this.weight = 0;
	this.score = 0;

	for (var element in this.members)
	{
		if (this.members[element]['active'])
		{
			this.value += this.members[element]['value'];
			this.weight += this.members[element]['weight'];
		}
	}

	this.score = this.value;

	if (this.weight &amp;gt; this.maxWeight)
	{
		this.score -= (this.weight - this.maxWeight) * 50;
	}

	return this.score;
};
</code></pre>
<p>The calcScore method starts with a tiny performance optimization: if we've calculated the score already, just serve the cached score -- it's just a nice way to not have to worry about at which point in the chromosome life cycle to calculate the score.</p>
<p>We then look through the elements and add up the value and weights for the active ones. We then apply a penalty of 50 points per overweight pound.</p>
<pre><code class="language-javascript">Chromosome.prototype.mateWith = function(other) {
	var child1 = {};
	var child2 = {};
	var pivot = Math.round( Math.random() * (length(this.members) - 1) );
	var i = 0;
	for (var element in elements)
	{
		if (i &amp;lt; pivot)
		{
			child1[element] = clone(this.members[element]);
			child2[element] = clone(other.members[element]);
		}
		else
		{
			child2[element] = clone(this.members[element]);
			child1[element] = clone(other.members[element]);
		}
		i++;
	}

	child1 = new Chromosome(child1);
	child2 = new Chromosome(child2);

	return [child1, child2];
};
</code></pre>
<p>In the &quot;Hello, World!&quot; example we picked the center point as the pivot point when mating two chromosomes; in this example we pick a random point instead.<br>
This adds a little more randomness to the system and can help avoid local optima.</p>
<p>Once we've picked our pivot point we create two children by splicing the parents at the pivot and combining. We then use our chromosome constructor to generate chromosome objects and return them.</p>
<h2>The Population</h2>
<pre><code class="language-javascript">var Population = function(elements, size)
{
	if ( ! size )
		size = 20;
	this.elements = elements;
	this.size = size;
	this.fill();
};

Population.prototype.elitism = 0.2;
Population.prototype.chromosomes = [];
Population.prototype.size = 100;
Population.prototype.elements = false;
</code></pre>
<p>The population constructor is straightforward: we give it the master list of elements and the desired population size. We also define the 'elitism' parameter; this is the percentage of chromosomes that will survive from one generation to the next.</p>
<pre><code class="language-javascript">Population.prototype.fill = function() {
	while (this.chromosomes.length &amp;lt; this.size)
	{
		if (this.chromosomes.length &amp;lt; this.size / 3)
		{
			this.chromosomes.push( new Chromosome( clone(this.elements) ) );
		}
		else
		{
			this.mate();
		}
	}
};
</code></pre>
<p>We use the fill method to initialize the population; we'll also use it to fill the population after killing the weakest chromosomes. A little bit of logic determines whether we should create random chromosomes or fill the population through mating instead. If our population size is 20, the first 6 chromosomes will be random and the remaining will be generated by mating. If the population size ever dips below 30% (perhaps due to death/elitism), new random chromosomes will be created until the population is diverse enough to create babies through mating.</p>
<p>Yes, 'this.chromosomes.length' in a while loop is bad form. If you expect to use a large population size -- or want this to be highly optimized -- do this the right way and cache the length.</p>
<pre><code class="language-javascript">Population.prototype.sort = function() {
	this.chromosomes.sort(function(a, b) { return b.calcScore() - a.calcScore(); });
};

Population.prototype.kill = function() {
	var target = Math.floor( this.elitism * this.chromosomes.length );
	while (this.chromosomes.length &amp;gt; target)
	{
		this.chromosomes.pop();
	}
};
</code></pre>
<p>The sort function above is just a helper; note that we use the calcScore method instead of accessing the 'score' property directly. If the score hasn't been calculated by this point, it will be now; if the score was already calculated we just use calcScore as an accessor.</p>
<p>After sorting, the kill method removes the weakest chromosomes from the bottom of the list by popping them until we reach our elitism value.</p>
<pre><code class="language-javascript">Population.prototype.mate = function() {
	var key1 = pickRandomProperty(this.chromosomes);
	var key2 = key1;

	while (key2 == key1)
	{
		key2 = pickRandomProperty(this.chromosomes);
	}

	var children = this.chromosomes[key1].mateWith(this.chromosomes[key2]);
	this.chromosomes = this.chromosomes.concat(children);
};
</code></pre>
<p>The mate method is always called after the kill method, so the only chromosomes allowed to reproduce are the elite ones in the population (in our example, the best 20%). Rather than mating only the best two chromosomes (like we did in &quot;Hello, World!&quot;), we pick any two random chromosomes to mate -- with the exception that we won't mate a chromosome with itself.</p>
<p>Again, this serves to add a little more randomness to the system, and will avoid stasis if the top two chromosomes remain the same for many generations -- we see that happen sometimes in the &quot;Hello, World!&quot; example and fix it here.</p>
<pre><code class="language-javascript">Population.prototype.generation = function(log) {
	this.sort();
	this.kill();
	this.mate();
	this.fill();
	this.sort();
};
</code></pre>
<p>Then we define a &quot;generation&quot;. The generation starts by sorting the chromosomes in terms of score. We then kill the weakest members.</p>
<p>Then we do something a little intriguing: we call mate() once and then call fill(), which we know will also call mate(). The reason we call mate() explicitly is as a bit of insurance: if the elitism parameter is less than 0.3 we want to mate at least once before potentially &quot;polluting&quot; the population with random members. This really depends on the elitism value; if you keep it over 0.3 you don't have to call mate() explicitly, because fill() will do that for you. But if you have elitism = 0.2 like we do, then we want to run at least one mating routine that involves only the elite, and not the new random chromosomes we introduce with fill().</p>
<p>Finally, we sort once more at the end of the generation. We could just as easily leave this part out, but it's nice to see the chromosomes in order after every generation if you're debugging.</p>
<h2>Running and Stopping</h2>
I briefly introduced this idea in the "Hello, World!" example: we don't know the best possible score in this problem, therefore we won't know when to stop.
<p>The technique (one of many) that we'll use is to stop when you've had 100 (or 1,000 or 1,000,000) generations with no improvement. We'll just call this the &quot;threshold&quot; or the &quot;stop threshold&quot;.</p>
<pre><code class="language-javascript">Population.prototype.run = function(threshold, noImprovement, lastScore, i) {
	if ( ! threshold )
		threshold = 1000;
	if ( ! noImprovement )
		noImprovement = 0;
	if ( ! lastScore )
		lastScore = false;
	if ( ! i )
		i = 0;

	if (noImprovement &amp;lt; threshold)
	{
		lastScore = this.chromosomes[0].calcScore();
		this.generation();

		if (lastScore &amp;gt;= this.chromosomes[0].calcScore())
		{
			noImprovement++;
		}
		else
		{
			noImprovement = 0;
		}

		i++;

		if (i % 10 == 0)
			this.display(i, noImprovement);
		var scope = this;
		setTimeout(function() { scope.run(threshold, noImprovement, lastScore, i) }, 1);

		return false;

	}
	this.display(i, noImprovement);
};
</code></pre>
<p>The run method is an iterative function. It doesn't need to be. The only reason it is in this example is because writing to the DOM in the middle of a fast-moving loop doesn't work -- the DOM doesn't update until execution is done. <a href="http://stackoverflow.com/questions/8110905/javascript-a-loop-with-innerhtml-is-not-updating-during-loop-execution">It's just a javascript thing.</a></p>
<p>To get around the DOM limitation, we use a short setTimeout and have the run method call itself iteratively until we're done. In general, however, this function could just use a while loop instead of calling itself -- but in that case you'd either need to use console.log or just wait until the loop is done to watch the results.</p>
<p>Other than that DOM messiness, the run method is straightforward. We compare last generation's best score to this generation's best. If there was improvement, then we reset the 'noImprovement' counter. If we have noImprovement equal to our stop threshold, we stop.</p>
<p>Not shown is a simple display method used to print the results to a table on the page. We only call it every 10 generations, and then once again when we're done.</p>
<h2>In Action</h2>
Our JSFiddle is below. You're given a slider that lets you set the stop tolerance and a big "Go" button. You then get to watch the population's evolution.
<p>Even with a 10-generation stop threshold, the GA consistently beats the naive greedy algorithm, though this is to be expected.</p>
<p>At a 50-generation stop threshold, the GA also consistently beats the weighted greedy algorithm. This is a happy result. There are some datasets where the GA will never beat the greedy algorithm, and other datasets where the greedy algorithm doesn't perform well at all. This seems like an in-between. We don't <em>crush</em> the greedy algorithm, but we do outperform it by a significant margin.</p>
<p>The best score I've observed so far is 5944, with a weight of 992. Please let me know in the comments below if you find a better score, and I'll post the updates here.</p>
<p><em>Update: </em>Sylvain Zimmer below found a solution with a score of 5968 and weight 998.</p>
<p>As always, feel free to fork and play with this example. I would encourage you to experiment with different values of population size, elitism, and mutation rate and observe the results.</p>
<iframe id="fiddle" style="width: 100%; height: 300px; border: 1px solid #CCC;" src="http://jsfiddle.net/bkanber/YAQzr/embedded/result,js,html,css/" frameborder="0" width="320" height="240"></iframe>
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<div id="mc_embed_signup">
<form action="http://burakkanber.us5.list-manage.com/subscribe/post?u=3269dc566d381f05852d92aa8&amp;id=3f5451bda5" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
	<h2>Email me when new ML in JS articles are posted</h2>
<div class="mc-field-group">
	<label for="mce-EMAIL">Email Address </label><input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group input-group">
    <strong>Survey: Would you buy an ML in JS e-book? </strong>
    <input type="checkbox" value="1" name="group[6613][1]" id="mce-group[6613]-6613-0"><label for="mce-group[6613]-6613-0">I would pay $10 for a DRM-free e-book with tons of ML lessons and JS examples.</label>
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>	<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<!--End mc_embed_signup--><!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Machine Learning in JS: k-nearest-neighbor Introduction]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p><em>This article is part of the <a title="Machine Learning in Javascript: Introduction" href="http://burakkanber.com/blog/machine-learning-in-other-languages-introduction/">Machine Learning in Javascript</a> series. My goal is to teach ML from fundamental to advanced topics using a common language. Javascript is an excellent choice because it requires no special environment to run, and its lack of ML libraries forces us to learn and</em></p>]]></description><link>https://burakkanber.com/blog/machine-learning-in-js-k-nearest-neighbor-part-1/</link><guid isPermaLink="false">59b43b8b934a21000178fc20</guid><category><![CDATA[ML in JS]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Fri, 07 Sep 2012 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p><em>This article is part of the <a title="Machine Learning in Javascript: Introduction" href="http://burakkanber.com/blog/machine-learning-in-other-languages-introduction/">Machine Learning in Javascript</a> series. My goal is to teach ML from fundamental to advanced topics using a common language. Javascript is an excellent choice because it requires no special environment to run, and its lack of ML libraries forces us to learn and write the code from scratch.</em></p>
<!-- more -->
<p>Just looking for the example code? The <a href="#fiddle">JSFiddle is at the bottom of the page</a>.</p>
<p>Today we're going to look at the k-nearest-neighbor algorithm (we'll abbreviate it kNN throughout this article). I love this algorithm because it's dead simple, but can still solve some exciting problems. Its strength doesn't lie in mathematical or theoretical sophistication, but rather in the fact that it can elegantly handle lots of different input parameters (&quot;dimensions&quot;).</p>
<p>k-nearest-neighbor also serves an ulterior motive of mine: it's a great way to introduce the concept of &quot;supervised learning&quot;. So let's go ahead and build the k-nearest-neighbor algorithm. And we'll graph our results, because I love visuals!</p>
<h2>Supervised Learning</h2>
There are two giant umbrella categories within Machine Learning: supervised and unsupervised learning. Briefly, <em>un</em>supervised learning is like data mining -- look through some data and see what you can pull out of it. Typically, you don't have much additional information before you start the process. We'll be looking at an unsupervised learning algorithm called k-means next week, so we can discuss that more in the next article.
<p>Supervised learning, on the other hand, starts with &quot;training data&quot;. Supervised learning is what we do as children as we learn about the world. We're in the kitchen with mom. Mom shows us an apple and says the word &quot;apple&quot;. You see an object and your mother has labeled it for you.</p>
<p>The next day, she shows you a different apple. It's smaller, it's less red, and it has a slightly different shape. But your mother shows it to you and says the word &quot;apple&quot;. This process repeats for a couple of weeks. Every day your mother shows you a slightly different apple, and tells you they're apples. Through this process you come to understand what an apple is.</p>
<p>Not every apple is exactly the same. Had you only ever seen one apple in your life, you might assume that every apple is <em>identical</em>. But instead, your mother has trained you to recognize the overall features of an apple. You're now able to create this category, or label, of objects in your mind. When you see an apple in the future you can recognize it as an apple because you've come to understand that while all apples share some features, they don't have to be identical to still be apples.</p>
<p>This is called &quot;generalization&quot; and is a very important concept in supervised learning algorithms. We would be useless if we couldn't recognize that an iPhone was an iPhone because it had a different case, or because it had a scratch across the screen.</p>
<p>When we build certain types of ML algorithms we therefore need to be aware of this idea of generalization. Our algorithms should be able to generalize but not <em>over</em>-generalize (easier said than done!). We want &quot;this is red and kind of round and waxy, it must be an apple&quot; and <em>not </em>&quot;this is red and round, it must be a ball; this other thing is orange and round, it must be a ball.&quot; That's overgeneralization and can be a problem. Of course, under-generalization is a problem too. This is one of the main difficulties with ML: being able to find the generalization sweet spot. There are some tests you can run as you're training an algorithm to help you find the sweet spot, but we'll talk about those in the future when we get to more advanced algorithms.</p>
<p>Many supervised learning problems are &quot;classification&quot; problems. The classification problem goes like this: there's a bucket of apples, oranges, and pears. Each piece of fruit has a sticker that tells you which fruit it is -- except one! Figure out which fruit the mystery fruit is by learning from the other fruits you're given.</p>
<p>The classification problem is usually very easy for humans, but tough for computers. kNN is one type of many different classification algorithms.</p>
<h2>Features</h2>
This is a great time to introduce another important aspect of ML: features. Features are what you break an object down into as you're processing it for ML. If you're looking to determine whether an object is an apple or an orange, for instance, you may want to look at the following features: shape, size, color, waxiness, surface texture, etc. It also turns out that sometimes an individual feature ends up not being helpful. Apples and oranges are roughly the same size, so that feature can probably be ignored and save you some computational overhead. In this case, size doesn't really add new information to the mix.
<p>Knowing what features to look for is an important skill when designing for ML algorithms. Sometimes you can get by on intuition, but most of the time you'll want to use a separate algorithm to determine which are the most important features of a data set (we'll talk about that in a much more advanced article).</p>
<p>As you can imagine, features aren't always as straightforward as &quot;color, size, shape&quot;. Processing documents is a tricky example. In some scenarios, each <em>word</em> in a document is an individual feature. Or maybe each pair of consecutive words (&quot;bigrams&quot;) is a feature. We'll talk about document classification in a future article as well.</p>
<h2>The Problem</h2>
Given the number of rooms and area (in square feet) of a type of dwelling, figure out if it's an apartment, house, or flat.
<p>As always, we're starting with the most contrived possible problem in order to learn the basics. The description of this problem has <em>given </em>us the features we need to look at: number of rooms, and square feet. We can also assume that, since this is a supervised learning problem, we'll be given a handful of example apartments, houses, and flats.</p>
<h2>What "k-nearest-neighbor" Means</h2>
I think the best way to teach the kNN algorithm is to simply define what the phrase "k-nearest-neighbor" actually means.
<p>Here's a table of the example data we're given for this problem:</p>
<table style="width:100%">
<thead>
<tr><th>Rooms</th><th>Area</th><th>Type</th></tr>
</thead>
<tbody>
	<tr><td>1</td><td>350</td><td>apartment</td></tr>
	<tr><td>2</td><td>300</td><td>apartment</td></tr>
	<tr><td>3</td><td>300</td><td>apartment</td></tr>
	<tr><td>4</td><td>250</td><td>apartment</td></tr>
	<tr><td>4</td><td>500</td><td>apartment</td></tr>
	<tr><td>4</td><td>400</td><td>apartment</td></tr>
	<tr><td>5</td><td>450</td><td>apartment</td></tr>
<pre><code>&lt;tr&gt;&lt;td&gt;7&lt;td&gt;850&lt;td&gt;house&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;7&lt;td&gt;900&lt;td&gt;house&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;7&lt;td&gt;1200&lt;td&gt;house&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;8&lt;td&gt;1500&lt;td&gt;house&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;9&lt;td&gt;1300&lt;td&gt;house&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;8&lt;td&gt;1240&lt;td&gt;house&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;10&lt;td&gt;1700&lt;td&gt;house&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;9&lt;td&gt;1000&lt;td&gt;house&lt;/tr&gt;

&lt;tr&gt;&lt;td&gt;1&lt;td&gt;800&lt;td&gt;flat&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;3&lt;td&gt;900&lt;td&gt;flat&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;2&lt;td&gt;700&lt;td&gt;flat&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;1&lt;td&gt;900&lt;td&gt;flat&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;2&lt;td&gt;1150&lt;td&gt;flat&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;1&lt;td&gt;1000&lt;td&gt;flat&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;2&lt;td&gt;1200&lt;td&gt;flat&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;1&lt;td&gt;1300&lt;td&gt;flat&lt;/tr&gt;
</code></pre>
</tbody>
</table>
<p>We're going to plot the above as points on a graph in two dimensions, using number of rooms as the x-axis and the area as the y-axis.</p>
<p>When we inevitably run into a new, unlabeled data point (&quot;mystery point&quot;), we'll put that on the graph too. Then we'll pick a number (called &quot;k&quot;) and just find the &quot;k&quot; closest points on the graph to our mystery point. If the majority of the points close to the new point are &quot;flats&quot;, then we'll guess that our mystery point is a flat.</p>
<p>That's what k-nearest-neighbor means. &quot;If the 3 (or 5 or 10, or 'k') nearest neighbors to the mystery point are two apartments and one house, then the mystery point is an apartment.&quot;</p>
<p>Here's the (simplified) procedure:</p>
<ul>
<li>Put all the data you have (including the mystery point) on a graph.
</li><li>Measure the distances between the mystery point and every other point.
</li><li>Pick a number. Three is usually good for small data sets.
</li><li>Figure out what the three closest points to the mystery point are.
</li><li>The majority of the three closest points is the answer.
</li></ul>
<p>If you're having trouble visualizing this, please take a quick break to scroll down to the bottom of the page and run the JS fiddle. That should illustrate the concept. Then come back up here and continue reading!</p>
<h2>The Code</h2>
<p>Let's start building this thing. There are a few fine points that will come out as we're implementing the algorithm, so please read the following carefully. If you skim, you'll miss out on another important concept!</p>
<p>I'll build objects of two different classes for this algorithm: the &quot;Node&quot;, and a &quot;NodeList&quot;. A Node represents a single data point from the set, whether it's a pre-labeled (training) point, or an unknown point. The NodeList manages all the nodes and also does some canvas drawing to graph them all.</p>
<p>The Node constructor has nothing to it. It just expects an object with the properties &quot;type&quot;, &quot;area&quot;, and &quot;rooms&quot;:</p>
<pre><code class="language-javascript">var Node = function(object) {
	for (var key in object)
	{
		this[key] = object[key];
	}
};
</code></pre>
<p>When I build these algorithms &quot;for realsies&quot; I usually abstract the features a little bit more. This example requires &quot;area&quot; and &quot;rooms&quot; to be hard-coded in certain places, but I usually build a generalized kNN algorithm that can work with arbitrary features rather than our pre-defined ones here. I'll leave that as an exercise for you!</p>
<p>Similarly, the NodeList constructor is simple:</p>
<pre><code class="language-javascript">var NodeList = function(k) {
	this.nodes = [];
	this.k = k;
};
</code></pre>
<p>The NodeList constructor takes the &quot;k&quot; from k-nearest-neighbor as its sole argument. Please fork the JSFiddle code and experiment with different values of k. Don't forget to try the number 1 as well!</p>
<p>Not shown is a simple NodeList.prototype.add(node) function -- that just takes a node and pushes it onto the this.nodes array.</p>
<p>At this point, we could dive right in to calculating distances, but I'd like to take a quick diversion.</p>
<h2>Normalizing Features</h2>
<p>Look at the data in the table above. The number of rooms varies from 1 to 10, and the area ranges from 250 to 1700. What would happen if we tried to graph this data onto a chart (without scaling anything)? For the most part, the data points would be lined up in a vertical column. That'll look pretty ugly, and hard to read.</p>
<p>Unfortunately, that's not just an aesthetic problem. This is an issue of a large discrepancy of scale of our data features. The difference between 1 room and 10 rooms is <em>huge</em> when you consider what it means for classifying a &quot;flat&quot; vs a &quot;house&quot;! But the same difference of 9, when you're talking about square feet, is <em>nothing</em>. If you were to measure distances between Nodes right now without adjusting for that discrepancy, you'd find that the number of rooms would have almost no effect on the results because those points are so close together on the x-axis (the &quot;rooms&quot; axis).</p>
<p>Consider the difference between a dwelling with 1 room and 700 square feet and 5 rooms and 700 square feet. Looking at the data table by eye, you'd recognize the first to be a flat and the second to be an apartment. But if you were to graph these and run kNN, it would consider them both to be flats.</p>
<p>So instead of looking at absolute values of number of rooms and area, we should normalize these values to be between 0 and 1. After normalization, the lowest number of rooms (1) becomes 0, and the largest number of rooms (10) becomes 1. Similarly, the smallest area (250) becomes 0 and the largest area (1700) becomes 1. That puts everything on the same playing field and will adjust for discrepancies of scale. It's a simple thing to do that makes all the difference in the world.</p>
<blockquote>Pro-tip: you don't need to scale things evenly (into a square) like I described above. If area is more important to the problem than the number of rooms, you can scale those two features differently -- this is called "weighting", and gives more importance to one feature or another. There are also algorithms that will determine the ideal feature weights for you. All in due time...</blockquote>
<p>To start normalizing our data we should give NodeList a way of finding the minimum and maximum values of each feature:</p>
<pre><code class="language-javascript">NodeList.prototype.calculateRanges = function() {
	this.areas = {min: 1000000, max: 0};
	this.rooms = {min: 1000000, max: 0};
	for (var i in this.nodes)
	{
		if (this.nodes[i].rooms &lt; this.rooms.min)
		{
			this.rooms.min = this.nodes[i].rooms;
		}

		if (this.nodes[i].rooms &gt; this.rooms.max)
		{
			this.rooms.max = this.nodes[i].rooms;
		}

		if (this.nodes[i].area &lt; this.areas.min)
		{
			this.areas.min = this.nodes[i].area;
		}

		if (this.nodes[i].area &gt; this.areas.max)
		{
			this.areas.max = this.nodes[i].area;
		}
	}

};
</code></pre>
<p>As I mentioned earlier, the best approach would be to abstract the features and not have areas or rooms hard-coded. But doing it this way reads a little more clearly to me.</p>
<p>Now that we have our minimum and maximum values, we can move along to the meat and berries of the algorithm. After we've added all our Nodes to the NodeList:</p>
<pre><code class="language-javascript">NodeList.prototype.determineUnknown = function() {

	this.calculateRanges();

	/*
	 * Loop through our nodes and look for unknown types.
	 */
	for (var i in this.nodes)
	{

		if ( ! this.nodes[i].type)
		{
			/*
			 * If the node is an unknown type, clone the nodes list and then measure distances.
			 */
			
			/* Clone nodes */
			this.nodes[i].neighbors = [];
			for (var j in this.nodes)
			{
				if ( ! this.nodes[j].type)
					continue;
				this.nodes[i].neighbors.push( new Node(this.nodes[j]) );
			}

			/* Measure distances */
			this.nodes[i].measureDistances(this.areas, this.rooms);

			/* Sort by distance */
			this.nodes[i].sortByDistance();

			/* Guess type */
			console.log(this.nodes[i].guessType(this.k));

		}
	}
};
</code></pre>
<p>That's a mouthful. First off, we calculate the min and max ranges so that the NodeList is aware of it.</p>
<p>We then loop through the Nodes and look for any unknown nodes (yes, this can do more than one mystery node at a time).</p>
<p>When we find an unknown Node, we clone the Nodes in the NodeList and make the Node aware of them. The reason we do this is because each unknown Node will have to calculate its own distance to every other Node -- so we can't use global state here.</p>
<p>Finally, we call three Node methods in succession on the unknown Node: measureDistances, sortByDistance, and guessType.</p>
<pre><code class="language-javascript">Node.prototype.measureDistances = function(area_range_obj, rooms_range_obj) {
	var rooms_range = rooms_range_obj.max - rooms_range_obj.min;
	var area_range  = area_range_obj.max  - area_range_obj.min;

	for (var i in this.neighbors)
	{
		/* Just shortcut syntax */
		var neighbor = this.neighbors[i];

		var delta_rooms = neighbor.rooms - this.rooms;
		delta_rooms = (delta_rooms ) / rooms_range;

		var delta_area  = neighbor.area  - this.area;
		delta_area = (delta_area ) / area_range;

		neighbor.distance = Math.sqrt( delta_rooms*delta_rooms + delta_area*delta_area );
	}
};
</code></pre>
<p>The measureDistances function takes the NodeList's set of ranges for min and max rooms and areas. If you've abstracted away from hard-coding features, the argument to this method would just be an array of ranges for features, but here we've hardcoded it.</p>
<p>We quickly calculate the rooms_range (here, it'll be 9) and area_range (here, it'll be 1450).</p>
<p>Then we loop through our Node's neighbors (we gave this Node the neighbors property above when we cloned the Nodes from NodeList). For each one of the neighbors we calculate the difference in number of rooms and area. After each of those calculations, we normalize by dividing each feature by its range.</p>
<p>If the difference between the number of rooms turns out to be 3 and the total range is 9 we end up for 0.333 for the value of that delta. This number should always be between -1 and +1, since we've normalized to a square for this problem.</p>
<p>Finally, we calculate the distance using the Pythagorean theorem. Note that if you have more than 2 features (dimensions), you still keep the Math.sqrt -- you just add all the squared features like so:</p>
<pre><code class="language-javascript">Math.sqrt( a*a + b*b + c*c + d*d + ... + z*z );
</code></pre>
<p>It should be pretty clear now what the true strength of this algorithm is. While our feeble minds may only be able to figure out correlations involving 5 or 10 different features, this algorithm can do that for hundreds or thousands of dimensions.</p>
<pre><code class="language-javascript">Node.prototype.sortByDistance = function() {
	this.neighbors.sort(function (a, b) {
		return a.distance - b.distance;
	});
};
</code></pre>
<p>This above sortByDistance is just a helper function to sort the Node's neighbors by distance.</p>
<pre><code class="language-javascript">Node.prototype.guessType = function(k) {
	var types = {};

	for (var i in this.neighbors.slice(0, k))
	{
		var neighbor = this.neighbors[i];

		if ( ! types[neighbor.type] )
		{
			types[neighbor.type] = 0;
		}

		types[neighbor.type] += 1;
	}

	var guess = {type: false, count: 0};
	for (var type in types)
	{
		if (types[type] &gt; guess.count)
		{
			guess.type = type;
			guess.count = types[type];
		}
	}

	this.guess = guess;

	return types;
};
</code></pre>
<p>The final piece of the algorithm is the guessType method. This method accepts the value of &quot;k&quot; from NodeList and slices out the k closest neighbors. It then tallies up the types of the neighbors, picks the most common one, and returns the result.</p>
<p>Algorithm finished. Congratulations! Now let's figure out how to graph this thing.</p>
<h2>Graphing it With Canvas</h2>
<p>Graphing our results is pretty straightforward, with a few exceptions:</p>
<ul>
<li>We'll color code apartments = red, houses = green, flats = blue.</li>
<li>We have to scale the graph into a square (for the same reasons we had to normalize the features).</li>
<li>We'll also add a little bit of padding to the edges of the graph.</li>
<li>We'll display the result of the kNN guess by drawing the radius that encompasses the "k" nearest neighbors, and coloring that radius with the result's color.</li>
</ul>
<pre><code class="language-javascript">NodeList.prototype.draw = function(canvas_id) {
	var rooms_range = this.rooms.max - this.rooms.min;
	var areas_range = this.areas.max - this.areas.min;

	var canvas = document.getElementById(canvas_id);
	var ctx = canvas.getContext(&quot;2d&quot;);
	var width = 400;
	var height = 400;
	ctx.clearRect(0,0,width, height);

	for (var i in this.nodes)
	{
		ctx.save();

		switch (this.nodes[i].type)
		{
			case 'apartment':
				ctx.fillStyle = 'red';
				break;
			case 'house':
				ctx.fillStyle = 'green';
				break;
			case 'flat':
				ctx.fillStyle = 'blue';
				break;
			default:
				ctx.fillStyle = '#666666';
		}

		var padding = 40;
		var x_shift_pct = (width  - padding) / width;
		var y_shift_pct = (height - padding) / height;

		var x = (this.nodes[i].rooms - this.rooms.min) * (width  / rooms_range) * x_shift_pct + (padding / 2);
		var y = (this.nodes[i].area  - this.areas.min) * (height / areas_range) * y_shift_pct + (padding / 2);
		y = Math.abs(y - height);


		ctx.translate(x, y);
		ctx.beginPath();
		ctx.arc(0, 0, 5, 0, Math.PI*2, true);
		ctx.fill();
		ctx.closePath();
		

		/* 
		 * Is this an unknown node? If so, draw the radius of influence
		 */

		if ( ! this.nodes[i].type )
		{
			switch (this.nodes[i].guess.type)
			{
				case 'apartment':
					ctx.strokeStyle = 'red';
					break;
				case 'house':
					ctx.strokeStyle = 'green';
					break;
				case 'flat':
					ctx.strokeStyle = 'blue';
					break;
				default:
					ctx.strokeStyle = '#666666';
			}

			var radius = this.nodes[i].neighbors[this.k - 1].distance * width;
			radius *= x_shift_pct;
			ctx.beginPath();
			ctx.arc(0, 0, radius, 0, Math.PI*2, true);
			ctx.stroke();
			ctx.closePath();

		}

		ctx.restore();

	}

};
</code></pre>
<p>I won't describe the above in detail, but rather point out two lines that I want you to look at and figure out on your own:</p>
<ul>
<li>The line starting "var x = "
</li><li>The line starting "var radius = "
</li></ul>
<p>It's a good but potentially frustrating exercise to try and figure out what's going on in those two lines, but please don't give up until you understand them!</p>
<p>Finally, we'll throw some code together to create random mystery points and do that every 5 seconds:</p>
<pre><code class="language-javascript">var run = function() {
	nodes = new NodeList(3);
	for (var i in data)
	{
		nodes.add( new Node(data[i]) );
	}
	var random_rooms = Math.round( Math.random() * 10 );
	var random_area = Math.round( Math.random() * 2000 );
	nodes.add( new Node({rooms: random_rooms, area: random_area, type: false}) );

	nodes.determineUnknown();
	nodes.draw(&quot;canvas&quot;);
};

window.onload = function() {
	setInterval(run, 5000);
	run();
};
</code></pre>
<p>If you want to play with the value of &quot;k&quot;, do it in the run() function above.</p>
<p>The kNN algorithm isn't the most sophisticated classifier there is, but it has some excellent uses. What's even more exciting is that you don't <em>have</em> to use kNN as a classifier; the concepts behind kNN are very flexible and can be used for non-classification problems. Consider the following problems that kNN might be a good candidate for (list includes both classification problems and otherwise):</p>
<ul>
<li>What named color (blue, red, green, yellow, grey, purple, etc) is a given RGB value closest to? This is useful if you have an image search application and want to "search for purple images" for instance.</li>
<li>You're building a dating site and want to rank matches for a given profile. The features could be location, age, height, and weight, for instance. Pick the 20 closest neighbors and rank them by kNN distance.</li>
<li>Quickly find 5 documents similar to a given document. Features are words in this case. Not the most sophisticated algorithm to solve this problem, but it works in a pinch.</li>
<li>Given data for previous e-shoppers, figure out if the person currently browsing your site is likely to make a purchase. Features could be time of day, number of pages browsed, location, referral source, etc.</li>
</ul>
<h2>Drawbacks, caveats</h2>
<p>There are two issues with kNN I'd like to briefly point out. First of all, it should be pretty clear that if your training data is all over the place, this algorithm won't work well. The data needs to be &quot;separable&quot;, or clustered somehow. Random speckles on the graph is no help, and very few ML algorithms can discern patterns from nearly-random data.</p>
<p>Secondly, you'll run into performance problems if you have thousands and thousands of Nodes. Calculating all those distances adds up! One way around this is to pre-filter out Nodes outside of a certain feature's range. For example, if our mystery point has # of rooms = 3, we might not even calculate distances for points with # of rooms &gt; 6 at all.</p>
<p>Here's the JSFiddle. The known points are colored, the mystery point is grey, and the result of the kNN guess is signified by the colored radius around the mystery point. The radius encapsulates the 3 nearest neighbors. A new random mystery point is solved for every 5 seconds:</p>
<iframe id="fiddle" style="width: 100%; height: 510px; border:1px solid #CCC;" src="http://jsfiddle.net/bkanber/hevFK/embedded/result,js,html,css/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<div id="mc_embed_signup">
<form action="http://burakkanber.us5.list-manage.com/subscribe/post?u=3269dc566d381f05852d92aa8&amp;id=3f5451bda5" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
	<h2>Email me when new ML in JS articles are posted</h2>
<div class="mc-field-group">
	<label for="mce-EMAIL">Email Address </label><input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group input-group">
    <strong>Survey: Would you buy an ML in JS e-book? </strong>
    <input type="checkbox" value="1" name="group[6613][1]" id="mce-group[6613]-6613-0"><label for="mce-group[6613]-6613-0">I would pay $10 for a DRM-free e-book with tons of ML lessons and JS examples.</label>
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>	<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<!--End mc_embed_signup--><!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Machine Learning: Introduction to Genetic Algorithms]]></title><description><![CDATA[In this post, we'll learn the basics of one of the most interesting machine learning algorithms, the genetic algorithm. This article is part of a series.]]></description><link>https://burakkanber.com/blog/machine-learning-genetic-algorithms-part-1-javascript/</link><guid isPermaLink="false">59b43b8b934a21000178fc24</guid><category><![CDATA[ML in JS]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Tue, 04 Sep 2012 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>I like starting my machine learning classes with genetic algorithms (which we'll abbreviate &quot;GA&quot; sometimes). Genetic algorithms are probably the least practical of the ML algorithms I cover, but I love starting with them because they're fascinating and they do a good job of introducing the &quot;cost function&quot; or &quot;error function&quot;, and the idea of local and global optima -- concepts both important and common to most other ML algorithms.</p>
<!-- more -->
<blockquote>
<p>The <a href="http://burakkanber.com/blog/machine-learning-in-other-languages-introduction/">Introduction to &quot;Machine Learning in Javascript&quot;</a> post provides a nice introduction and context for this post and the rest of the series.</p>
</blockquote>
<p>Genetic algorithms are inspired by nature and evolution, which is seriously cool to me. It's no surprise, either, that artificial neural networks (&quot;NN&quot;) are also modeled from biology: evolution is the best general-purpose learning algorithm we've experienced, and the brain is the best general-purpose problem solver we know. These are two very important pieces of our biological existence, and also two rapidly growing fields of artificial intelligence and machine learning study. While I'm tempted to talk more about the distinction I make between the GA's &quot;learning algorithm&quot; and the NN's &quot;problem solver&quot; terminology, we'll drop the topic of NNs altogether and concentrate on GAs... for now.</p>
<p>One phrase I used above is profoundly important: &quot;general-purpose&quot;. For almost any specific computational problem, you can probably find an algorithm that solves it more efficiently than a GA. But that's not the point of this exercise, and it's also not the point of GAs. You use the GA not when you have a complex problem, but when you have a complex problem of problems. Or you may use it when you have a complicated set of disparate parameters.</p>
<p>One application that comes to mind is bipedal robot walking. It's damn hard to make robots walk on two legs. Hand-coding a walking routine will almost certainly fail. Even if you succeed in making a robot walk, the next robot that comes off the line might have a slightly different center of balance, and that algorithm you slaved over no longer works. Instead of enduring the inevitable heartbreak, you might use a GA to &quot;teach the robot to learn to walk&quot; rather than simply &quot;teaching the robot to walk&quot;.</p>
<p>Let's build a GA in Javascript.</p>
<blockquote>
<p>If you want to learn a whole lot more about machine learning, try my book <a href="https://www.amazon.com/gp/product/1788998243/ref=as_li_tl?ie=UTF8&amp;tag=bkanber-20&amp;camp=1789&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=1788998243&amp;linkId=0153fc70395cfa54a0955fd88b7df824">Hands-on Machine Learning in JavaScript</a>.</p>
</blockquote>
<h3>The Problem</h3>
<p>Build a genetic algorithm in Javascript that reproduces the text &quot;Hello, World!&quot;.</p>
<p>Naturally, everything starts with &quot;Hello, World!&quot; and so building a GA to reproduce that phrase is apropos. Note that this problem is highly contrived. At one point we're even going to type the phrase &quot;Hello, World!&quot; into the source code! Now that seems silly -- if you know the desired result, why program the algorithm in the first place? The answer is simple: this is a learning exercise. The next GA exercise (which will be in PHP) will be a little less contrived, but we need to start somewhere.</p>
<h3>Genetic Algorithm Basics</h3>
<p>The basic approach to GAs is to generate a bunch of &quot;answer candidates&quot; and use some sort of feedback to figure out how close the candidate is to optimal. Far-from-optimal candidates literally die and are never seen again. Close-to-optimal candidates combine with each other and maybe mutate slightly; this is an attempt to modify the candidates from time to time and see if they get closer to optimal or farther from optimal.</p>
<p>These &quot;answer candidates&quot; are called <strong><s>genes</s> chromosomes</strong>. (<em>Note: my terminology here was incorrect. Genes are technically the individual characters of the solution candidate, while the whole thing is called a chromosome. Semantics are important!</em>)</p>
<p>Chromosomes mate, produce offspring, and mutate. They either die due to survival of the fittest, or are allowed to produce offspring who may have more desirable traits and adhere to natural selection.</p>
<p>This may be a strange way to think about solving for &quot;Hello, World!&quot; but stick with it. This example isn't the only problem that can be solved with GAs!</p>
<h3>The Chromosome</h3>
<p>The chromosome is a representation of a solution candidate. In our case, the chromosome itself is a string. Let's assume that all chromosomes have a length of 13 characters (the same as &quot;Hello, World!&quot;). Here are some possible chromosomes that could be solution candidates for our problem:</p>
<ul>
	<li>Gekmo+ xosmd!</li>
	<li>Gekln, worle"</li>
	<li>Fello, wosld!</li>
	<li>Gello, wprld!</li>
	<li>Hello, world!</li>
</ul>
<p>Obviously that last one is the &quot;correct&quot; (or globally-optimum) chromosome. But how do we measure the optimality of a chromosome?</p>
<h4>Cost Function</h4>
<p>The cost function (or error function, or fitness function as the inverse) is some sort of measure of the optimality of a chromosome. If we're calling it &quot;fitness function&quot; then we're shooting for higher scores, and if we're using &quot;cost function&quot; then we're looking for low scores.</p>
<p>In this case, we might define a cost function to be something like the following:</p>
<blockquote>For each character in the string, figure out the difference in ASCII representation between the candidate character and the target character, and then square it so that the "cost" is always positive.</blockquote>
<p>For example, if we have a capital &quot;A&quot; (ASCII 65) but it's supposed to be a capital &quot;C&quot; (ASCII 67), then our cost for that character is 4 (67 - 65 = 2, and 2^2 = 4).</p>
<p>Again, the reason we're using the square of the difference is so that we never end up with a negative cost. You could just use absolute value if you want, too. Please experiment with different approaches -- that's how you learn!</p>
<p>Using that rule as a cost function, we can calculate the costs of the above 5 example chromosomes (in parentheses):</p>
<ul>
	<li>Gekmo+ xosmd! <strong>(7)</strong></li>
	<li>Gekln, worle" <strong>(5)</strong></li>
	<li>Fello, wosld! <strong>(5)</strong></li>
	<li>Gello, wprld! <strong>(2)</strong></li>
	<li>Hello, world! <strong>(0)</strong></li>
</ul>
In this case, since this problem is easy and contrived, we know that we're shooting for a cost of 0 and that we can stop there. Sometimes that's not the case. Sometimes you're just looking for the lowest cost you can find, and need to figure out different ways to end the calculation. Other times you're looking for the <em>highest</em> "fitness score" you can find, and similarly need to figure out some other criteria to use to stop the calculation.
<p>The cost function is a very important aspect of GAs, because if you're clever enough, you can use it to reconcile <em>completely disparate parameters.</em> In our case, we're just looking at letters. But what if you're building a driving directions app and need to weigh tolls vs distance vs speed vs traffic lights vs bad neighborhoods vs bridges? Those are completely disparate parameters that you can reduce into one, neat, tidy cost function for a route by applying different weights to each parameter.</p>
<h4>Mating and Death</h4>
<p>Mating is a fact of life, and we use it tons in GAs. Mating is a magical moment that two chromosomes in love with each other share. The technical term for mating is &quot;crossover&quot;, but I'll continue calling it &quot;mating&quot; here, because that paints a more intuitive picture.</p>
<p>We haven't talked about &quot;populations&quot; in GAs yet (we'll get to that a bit later) but for now I'll just say that when you run a GA, you don't just look at one chromosome at a time. You might have a population of 20 or 100 or 5,000 going all at once. Just like in evolution, you might be inclined to have the best and strongest chromosomes of the population mate with each other, with the hope that their offspring will be even healthier than either parent.</p>
<p>Mating strings, like in our &quot;Hello, World!&quot; example is pretty easy. You can pick two candidates (two strings; two chromosome) and pick a point in the middle of the string. This point can be dead-center if you want, or randomized if you prefer. Experiment with it! Take that middle point (called a &quot;pivot&quot; point), and make two new chromosomes by combining the first half of one with the second half of the other and vice versa.</p>
<p>Take these two strings for example:</p>
<ul>
	<li>Hello, wprld! <strong>(1)</strong></li>
	<li>Iello, world! <strong>(1)</strong></li>
</ul>
<div>Cutting them in half and making two new strings from the alternating halves gives us these two new "children":</div>
<div>
<ul>
	<li>Iello, wprld! <strong>(2)</strong></li>
	<li>Hello, world! <strong>(0)</strong></li>
</ul>
</div>
As you can see, the offspring includes one bastard child that has the worst traits of both parents, but also an angel child that has the best traits of both.
<p>Mating is how you get from one generation of genes to the next.</p>
<h4>Mutation</h4>
<p>Mating alone has a problem: in-breeding. If all you do is mate your candidates to go from generation to generation, you'll get stuck near a &quot;local optimum&quot;: an answer that's <em>pretty good</em> but not necessarily the &quot;global optimum&quot; (the best you can hope for).</p>
<p>(<em>I was recently informed that the above paragraph is misleading. Some readers got the impression that the most important aspect of chromosome evolution is the mating, when in actuality a GA would achieve very little if not for the combined effects of both mating and mutation. The mating helps discover more optimal solutions from already-good solutions [many problems' solutions, like our Hello World problem, can be divided into optimal sub-solutions, like &quot;Hello&quot; and &quot;world&quot; separately], but it's the mutation that pushes the search for solutions in new directions.</em>)</p>
<p>Think of the world that these genes are living in as a physical setting. It's really hilly with all sorts of weird peaks and valleys. There is one valley that's the lowest of all, but there are also tons of other little valleys -- while these other valleys are lower than the land directly around them, they're still above sea-level overall. Searching for a solution is like starting a bunch of balls on the hills in <em>random places</em>. You let the balls go and they roll downhill. Eventually, the balls will get stuck in the valleys -- but many of them will get stuck in the random mini-valleys that are stilly pretty high up the hill (the local optima). It's your job to make sure at least one of the balls ends up in the lowest point on the whole map: the global optimum. Since the balls all start in random places, it's hard to do this from the outset, and it's impossible to predict which ball will get stuck where. But what you <em>can </em>do is visit a bunch of the balls <em>at random</em> and give them a kick. Maybe the kick will help, maybe it'll hurt -- but the idea here is to shake up the system a little bit to make sure things aren't getting stuck in local optima for too long.</p>
<p>This is called <strong>mutation</strong>. It's a completely random process by which you target an unsuspecting chromosome and blast it with just enough radiation to make one of its letters randomly change.</p>
<p>Here's an example to illustrate. Let's say you end up with these two chromosomes:</p>
<ul>
	<li>Hfllp, worlb!</li>
	<li>Hfllp, worlb!</li>
</ul>
Again, a contrived example, but it happens. Your two chromosomes are exactly the same. That means that their children will be exactly the same as the parents, and no progress will ever be made. But if 1 in 100 chromosomes has one letter randomly mutated, it's only a matter of time before chromosome #2 above turns into "Ifllp, worlb!" -- and then the evolution continues because the children will finally be different from the parents once again. Mutation pushes the evolution forward.
<p>How and when you mutate is up to you. Again, experiment. The code I'll give you later has a very high mutation rate (50%), but that's really just for demonstration. You might make it low, like 1%. My code makes only <em>one letter</em> move by <em>one ASCII code</em> but you can have yours be more radical. Experiment, test, and learn. It's the only way.</p>
<h4>Chromosomes: Summary</h4>
<p>Chromosomes are representations of candidate solutions to your problem. They consist of the representation itself (in our case, a 13-character string), a cost or fitness score and function, the ability to mate (&quot;crossover&quot;), and the ability to mutate.</p>
<p>I like thinking about these things in OOP terms. The &quot;Chromosome&quot; class therefore has the following properties:</p>
<p><strong>Properties:</strong></p>
<ul>
	<li>Genetic code</li>
	<li>Cost/fitness score</li>
</ul>
<strong>Methods:</strong>
<ul>
	<li>Mate</li>
	<li>Mutate</li>
	<li>Calculate Fitness Score</li>
</ul>
<p>We'll now look at how to have genes interact with each other in the final piece of the GA puzzle: the &quot;Population&quot;.</p>
<h3>The Population</h3>
<p>The population is a group of chromosomes. The population generally remains the same size but will typically evolve to better average cost scores over time.</p>
<p>You get to choose your population size. I picked 20 for mine below, but you could choose 10 or 100 or 10,000 if you want. There are advantages and disadvantages, but as I've said a few times by now: experiment and learn for yourself!</p>
<p>The population experiences &quot;generations&quot;. A typical generation may consist of:</p>
<ul>
	<li>Calculating the cost/fitness score for each chromosome</li>
	<li>Sorting the chromosome by cost/fitness score</li>
	<li>Killing a certain number of the weakest members -- you pick the number of chromosome that will die</li>
	<li>Mating a certain number of the strongest members -- again, you pick how you do this</li>
	<li>Mutating members at random</li>
	<li>Some kind of completeness test -- ie, how do you determine when to consider the problem "solved"?</li>
</ul>
<h4>Starting and Finishing</h4>
<p>Starting a population is easy. Just fill it with completely random chromosomes. In our case, the cost scores for completely random strings will be <em>horrendous.</em> My code starts at an average cost score of 30,000. But that's ok -- that's what evolution is for. This is why we're here.</p>
<p>Knowing when to stop the population is a little trickier. Today's example is pretty simple: stop when you get a cost of 0. But this isn't always the case. Sometimes you don't know the minimum achievable cost. Or, if you're using fitness instead of cost, you may not know the maximum possible fitness.</p>
<p>In those cases you should specify a completeness criteria. This can be anything you want, but here's a starting suggestion to jump off from:</p>
<blockquote>Stop the algorithm if the best score hasn't changed in 1,000 generations, and use that as your answer.</blockquote>
<p>Criteria like that may mean that you never achieve the global optimum, but in many cases you don't <em>need</em> to achieve the global optimum. Sometimes &quot;close enough&quot; really is good enough.</p>
<p>I'll soon be writing another article on GAs (for PHP this time) with a slightly different problem, and that one will have a completeness rule similar to the above. It might be hard to swallow that &quot;close enough is good enough&quot; right now, but once you see the example in action hopefully you'll believe me.</p>
<h3>The Code</h3>
<p>Finally! I like OOP methods, but I also like rough and simple code, so I'll do this as straight-forwardly as possible though it may be a little rough around the edges.</p>
<p>(<em>Note that while I changed the occurrences of the term &quot;gene&quot; to &quot;chromosome&quot; in the text above, the code below still uses the incorrect &quot;gene&quot; terminology. It's a semantic and pedantic difference, but where would we be without semantic pedantics?</em>)</p>
<pre><code class="language-javascript">var Gene = function(code) {
        if (code)
                this.code = code;
        this.cost = 9999;
};
Gene.prototype.code = '';
Gene.prototype.random = function(length) {
        while (length--) {
                this.code += String.fromCharCode(Math.floor(Math.random()*255));
        }
};
</code></pre>
<p>Simple. It's just a class that takes a string as a constructor, sets a cost, and has a helper function to create a new, random chromosome.</p>
<pre><code class="language-javascript">Gene.prototype.calcCost = function(compareTo) {
        var total = 0;
        for(i = 0; i &amp;lt; this.code.length; i++) {
                total += (this.code.charCodeAt(i) - compareTo.charCodeAt(i)) * (this.code.charCodeAt(i) - compareTo.charCodeAt(i));
        }
        this.cost = total;
};
</code></pre>
<p>The cost function takes the &quot;model&quot; string as an argument, finds the differences between ASCII codes, and squares them.</p>
<pre><code class="language-javascript">Gene.prototype.mate = function(gene) {
        var pivot = Math.round(this.code.length / 2) - 1;

        var child1 = this.code.substr(0, pivot) + gene.code.substr(pivot);
        var child2 = gene.code.substr(0, pivot) + this.code.substr(pivot);

        return [new Gene(child1), new Gene(child2)];
};
</code></pre>
<p>The mating function takes another chromosome as an argument, finds the center point, and returns an array of two new children.</p>
<pre><code class="language-javascript">Gene.prototype.mutate = function(chance) {
        if (Math.random() &amp;gt; chance)
                return;

        var index = Math.floor(Math.random()*this.code.length);
        var upOrDown = Math.random()
</code></pre>
<p>The mutate method takes a float as an argument -- the percent chance that the chromosome will mutate. If the chromosome is to mutate we randomly decide if we're going to add or subtract one from the randomly-selected character code. I was going too fast to write a proper String.prototype.replaceAt method, so I just took an easy shortcut there.</p>
<pre><code class="language-javascript">var Population = function(goal, size) {
        this.members = [];
        this.goal = goal;
        this.generationNumber = 0;
        while (size--) {
                var gene = new Gene();
                gene.random(this.goal.length);
                this.members.push(gene);
        }
};
</code></pre>
<p>The Population class constructor takes the target string and population size as arguments, then fills the population with random chromosomes.</p>
<pre><code class="language-javascript">Population.prototype.sort = function() {
        this.members.sort(function(a, b) {
                return a.cost - b.cost;
        });
}
</code></pre>
<p>I define a Population.prototype.sort method as a helper function to sort the population by their cost score.</p>
<pre><code class="language-javascript">Population.prototype.generation = function() {
        for (var i = 0; i &amp;lt; this.members.length; i++) {
                this.members[i].calcCost(this.goal);    
        }

        this.sort();
        this.display();
        var children = this.members[0].mate(this.members[1]);
        this.members.splice(this.members.length - 2, 2, children[0], children[1]);

        for (var i = 0; i &amp;lt; this.members.length; i++) {
                this.members[i].mutate(0.5);
                this.members[i].calcCost(this.goal);
                if (this.members[i].code == this.goal) { 
                        this.sort();
                        this.display();
                        return true;
                }
        }
        this.generationNumber++;
        var scope = this;
        setTimeout(function() { scope.generation(); } , 20);
};
</code></pre>
<p>The meatiest population method is the generation method. There's no real magic here. The display() method (not shown on this page) just renders output to the page, and I set a timeout between generations so that things don't explode.</p>
<p>Note that in this example I'm only mating the top two chromosomes. This doesn't have to be your approach.</p>
<pre><code class="language-javascript">window.onload = function() {
        var population  = new Population(&quot;Hello, world!&quot;, 20);
        population.generation();
};
</code></pre>
<p>That gets the ball rolling. See it in action:</p>
<iframe style="width: 100%; height: 600px; border: 1px solid #333;" src="https://jsfiddle.net/bkanber/BBxc6/embedded/" frameborder="0" width="320" height="240"></iframe>
<p>It's slow -- but it's not too difficult to figure out where the inefficiencies are. If you're clever enough you can certainly make it lightning fast. As always, I encourage you to fork and experiment and learn on your own.</p>
<p>Notice that there's nothing in the above that can't be done in <em>any</em> programming language. But you probably expected that, since this is &quot;Machine Learning in All Languages&quot;, after all.</p>
<p>Happy learning! The next post in this series is <a title="Machine Learning in JS: k-nearest-neighbor Introduction" href="http://burakkanber.com/blog/machine-learning-in-js-k-nearest-neighbor-part-1/">ML in JS: k-nearest-neighbor</a>.</p>
<p>There's also a <a title="Machine Learning: Genetic Algorithms in Javascript Part 2" href="http://burakkanber.com/blog/machine-learning-genetic-algorithms-in-javascript-part-2/">Genetic Algorithms Part 2</a>, which you should read if you want to get a little more advanced.</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Machine Learning in Javascript: Introduction]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>I love machine learning algorithms. I've taught classes and seminars and given talks on ML. The subject is fascinating to me, but like all skills fascination simply isn't enough. To get good at something, you need to practice!</p>
<!-- more -->
<p>I also happen to be a PHP and JavaScript developer. I've taught</p>]]></description><link>https://burakkanber.com/blog/machine-learning-in-other-languages-introduction/</link><guid isPermaLink="false">59b43b8b934a21000178fc25</guid><category><![CDATA[ML in JS]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Mon, 03 Sep 2012 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>I love machine learning algorithms. I've taught classes and seminars and given talks on ML. The subject is fascinating to me, but like all skills fascination simply isn't enough. To get good at something, you need to practice!</p>
<!-- more -->
<p>I also happen to be a PHP and JavaScript developer. I've taught classes on both of these as well -- but like any decent software engineer I have experience with Ruby, Python, Perl, and C. I just prefer PHP and JS. (Before you flame PHP, I'll just say that while it has its problems, I like it because it gets stuff done.)</p>
<p>Whenever I say that Tidal Labs' ML algorithms are in PHP, they look at me funny and ask me how it's possible. Simple: it's possible to write ML algorithms in just about any language. Most people just don't care to learn the fundamentals strongly enough that they can write an algorithm from scratch. Instead, they rely on Python libraries to do the work for them, and end up not truly grasping what's happening inside the black box. Other people only know ML academically, using Octave or Matlab.</p>
<p>Through this series of articles, I'll teach you the fundamental machine learning algorithms using Javascript -- not Python or Octave -- as the example language. Originally I intended to write these articles in a variety of languages (PHP, JS, Perl, C, Ruby), but decided to stick with Javascript for the following reasons:</p>
<ul>
	<li>If you're a web developer you probably already know JS, regardless of your backend expertise.</li>
	<li>Javascript has JSFiddle, a great tool that lets me embed executable Javascript right in my posts (hard to do that with C or Perl!)</li>
	<li>Several people asked me to stick to just one language.</li>
</ul>
While I'll be writing these articles with Javascript in mind, <em>please</em> re-write the examples in your language of choice as homework! Practice is how you get better, and writing the same algorithm several times in different languages really helps you understand the paradigms better.
<p>It's possible to get excellent performance out of ML algorithms in languages like PHP and Javascript. I advocate writing ML algorithms in other languages because the practice of writing ML algorithms from scratch helps you learn them fundamentally, and it also helps you unify your backend by not requiring a Python script to do processing in the middle of a PHP application. You can do it in PHP, and cut out the (mental and computational) overhead of using another language.</p>
<p>... well, most of the time. There are some things you really can't do in PHP or Javascript, but those are the more advanced algorithms that require heavy matrix math. While you <em>can </em>do matrix math in JS, there is a big difference between simply &quot;doing matrix math&quot; and doing it efficiently. The advantage of NumPy or Matlab is not in their ability to do matrix operations, it's in the fact that they use optimized algorithms to do so -- things you wouldn't be able to do yourself unless you dedicate yourself to learning computational linear algebra. And that's not my field, so we'll just stick to the ML that doesn't require the advanced matrix math. You could try brute-forcing the matrix operations, but you'll end up with a relatively inefficient system. It's great for learning, so I'm not discouraging it -- I would just be wary of doing that in a production environment.</p>
<p>Keep in mind that most of the algorithms we'll look at can be solved both with and without matrix math. We'll use iterative or functional approaches here, but most of these algorithms can be done with linear algebra as well. There's more than one way to skin a cat! I encourage you to also go and learn (or figure out) the linear algebra approaches, but since that's not my strong suit I'll use other approaches.</p>
<p>Here are some of the algorithms I intend to cover. I'll update this list with links to the relevant articles as they're published:</p>
<ul>
	<li>k-nearest-neighbor (<a title="Machine Learning in JS: k-nearest-neighbor Introduction" href="http://burakkanber.com/blog/machine-learning-in-js-k-nearest-neighbor-part-1/">Introduction</a>)</li>
	<li>k-means clustering (<a title="Machine Learning: k-Means Clustering in Javascript Part 1" href="http://burakkanber.com/blog/machine-learning-k-means-clustering-in-javascript-part-1/" target="_blank">Part 1</a>)</li>
	<li>Genetic algorithms (<a href="http://burakkanber.com/blog/machine-learning-genetic-algorithms-part-1-javascript/">Part 1</a>, <a title="Machine Learning: Genetic Algorithms in Javascript Part 2" href="http://burakkanber.com/blog/machine-learning-genetic-algorithms-in-javascript-part-2/">Part 2</a>)</li>
	<li>Naive Bayes classifier (<a href="http://burakkanber.com/blog/machine-learning-naive-bayes-1/">Part 1: Document Classification</a>)</li>
	<li>Sentiment Analysis (<a title="Machine Learning: Sentiment Analysis" href="http://burakkanber.com/blog/machine-learning-sentiment-analysis/">Part 1</a>)</li>
        <li>Full-text Search (<a title="Machine Learning: Full-Text Search" href="http://burakkanber.com/blog/machine-learning-full-text-search-in-javascript-relevance-scoring/">Part 1: Relevance Scoring</a>)</li>
	<li>Neural network</li>
</ul>
Happy learning!<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>