<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wayne Polatkan on Medium]]></title>
        <description><![CDATA[Stories by Wayne Polatkan on Medium]]></description>
        <link>https://medium.com/@nixalo?source=rss-febe20a208a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vBuCQaHa99_hkpRrTuzRtA.jpeg</url>
            <title>Stories by Wayne Polatkan on Medium</title>
            <link>https://medium.com/@nixalo?source=rss-febe20a208a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:10:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nixalo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Datacleaning fighter jets]]></title>
            <link>https://medium.com/data-science/datacleaning-fighter-jets-687919b10a7e?source=rss-febe20a208a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/687919b10a7e</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[iteration]]></category>
            <dc:creator><![CDATA[Wayne Polatkan]]></dc:creator>
            <pubDate>Thu, 06 Dec 2018 14:04:55 GMT</pubDate>
            <atom:updated>2018-12-06T14:04:55.798Z</atom:updated>
            <content:encoded><![CDATA[<p>When I finally got around to starting on the <a href="http://xviewdataset.org/">xView</a> dataset, I found out that the test set and evaluation page were locked… which lobbed a bit of a torpedo at what I was planning. It can be used as training data for any satellite imagery task, but if you’re looking to see how your model ranks up like in a <a href="https://www.kaggle.com/c/planet-understanding-the-amazon-from-space/leaderboard">completed Kaggle competition</a>: that’s just not in the cards right now.</p><p>So I came back around to a paused homework project for fast.ai: the fighter jet detector. The idea is simple: train an aircraft classifier, then turn it into a detector. Why fighter jets? I won’t go crazy if I have to look at them for hours.</p><blockquote><strong><em>Note</em></strong>: You can follow along with the work notebook I used, <a href="https://nbviewer.jupyter.org/github/WNoxchi/course-v3/blob/master/nbs/dl1/fighter-jets-datacleaning_20181203-4.ipynb">here</a>.</blockquote><h3>1. Getting the Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*IyvuR1L6WmarF2am1VQb3Q.png" /><figcaption><a href="https://github.com/WNoxchi/course-v3/blob/master/nbs/dl1/fighter-jets-datacleaning.ipynb">fighter-jets-datacleaning.ipynb</a></figcaption></figure><p>I started this project in October, but wanted to give it a fresh start. I already downloaded and cleaned data, and it was an experience I didn’t want to repeat. The main obstacle was the lack of a <a href="https://en.wikipedia.org/wiki/Graphical_user_interface">GUI</a> on the cloud machine. I used Jupyter to get around this by displaying images in batches of 16 with matplotlib. There were problems. I couldn’t find a way to enter input without taking the time to learn about <a href="https://ipywidgets.readthedocs.io/en/stable/">widgets</a>, so I had to break a 2-layer for-loop into a series of cells that had to be run in the right order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*VGBTRT64YPViyPjrmgPmiA.png" /><figcaption>This is not how you want to do things.</figcaption></figure><p>I assigned numbers to files, and entered the number of the image that didn’t belong. This was time consuming and complicated. The worst part was that the process was hard to repeat or alter. You do it once and never come back. <em>That’s not how work is supposed to be done</em>. As I went along, I made notes on ways things could be done better, but were too late then to implement.</p><blockquote><strong>Aside</strong>: What’s interesting looking back on work you did while learning is that it’s as if you kept finding the single hardest way to do a task. I often hear researchers express surprise when they discover a simpler algorithm outperforming previous more complex ones, such as with <a href="https://blog.openai.com/openai-baselines-ppo/">OpenAI’s PPO</a>. But I feel like complexity is often the result of an imperfect approximation to an ideal solution.</blockquote><p>This time I approached things more methodically. The search term I used in my old script for the <a href="https://en.wikipedia.org/wiki/Panavia_Tornado">Panavia Tornado</a> was just ‘tornado’. Guess what happens when you do a Google image search for that? This time I used a <a href="https://github.com/WNoxchi/course-v3/blob/master/nbs/dl1/fighterjet/fighter-jets-classes-to-dl.md">javascript command</a> that captures links to the images you can see, instead of the <a href="http://chromedriver.chromium.org/">chromedriver</a>-based <a href="https://github.com/hardikvasa/google-images-download">command-line script</a>. This let me refine the search.</p><p>Getting the data was very easy. You build your url files by entering the javascript command in your browser’s console (cmd-alt-i or -j) when you see the images you want. You then run a for-loop over them, calling fastai’s download_images function:</p><pre><em># download dataset</em><br><em>for url_path in urls.ls():</em><br><em>    aircraft_type = url_path.name.split(&#39;.&#39;)[0] # get class name</em><br><em>    print(f&#39;downloading: {aircraft_type}&#39;)</em><br><em>    dest = path/aircraft_type; dest.mkdir(parents=True, exist_ok=True) # set &amp; create class folder</em><br><em>    download_images(url_path, dest)</em></pre><p>Where url_path is a <a href="https://docs.python.org/3/library/pathlib.html">pathlib</a> path to your url files (.csv or .txt), assuming they’re named by class. I’m printing a python <a href="https://hackernoon.com/a-closer-look-at-how-python-f-strings-work-f197736b3bdb">f-string</a>, which is <em>very</em> useful.</p><h4>1.1 Keeping track of Data</h4><p>Now there’s an issue when you do this. The purpose of me doing this on my Mac, is that I can take advantage of my OS’s GUI to quickly delete images I don’t want. For this project to feel professional to me, I can’t just copy all the cleaned images up to my cloud machine. I need to build a list of good links to download. The issue is fastai’s download_images renames files as consecutive integers: 0000001.jpg, 00000002.jpg, etc. There are 2 solutions to this: save url-filenames, or store a mapping between filenames and urls.</p><p>I tried the former first. I got it to work, but it wasn’t pretty and introduced 2 new problems:</p><ol><li>non-latin alphabets encoded as utf8 bytes</li><li>links using the same filename</li></ol><p>The character-encoding issue was very confusing at first, especially since the urls appeared decoded in the address bar, and only showed themselves when I copied the <em>entire</em> address, not just a part of it. That was <a href="https://stackoverflow.com/a/16566128">a simple fix</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F31ZxTqiNtoJ2RuZKD9rGw.png" /></figure><p>The second issue wasn’t going anywhere. So I decided to figure out how to map filenames with urls. I crashed into a very confusing set of problems here. To save url-filenames I had to change the way fastai saved the images it downloaded. To do that I had to edit _download_image_inner which is called by download_images, all from fastai.vision.data. Decoding utf8 bytes was necessary for this (<em>on second thought I’m not sure if it was</em>), but it was pretty straight forward from there. To map filenames to urls I had to go a layer deeper and edit download_image which is called by _download_image_inner.</p><p>I first tried to define a dictionary in <a href="https://www.youtube.com/watch?v=GiFbdVGjF9I">global scope</a> (outside of any functions) and just have download_image update it. But that didn’t work. I defined the dictionary in the format:</p><pre>{class : {filepath : url}}</pre><p>where the current class of aircraft is assigned in download_images, with an empty dict as its value, and that dict is filled in with filepath:url pairs inside download_image.</p><p>The top-level class-keys would be assigned, but the underlying dicts were all empty. Nothing was being stored in download_image. I didn’t want to take the time to understand python’s global keyword, and I figured it was because a copy of my url_fname_dict was being written to in the lower-level function. I did a print-out, and indeed key:value pairs <em>were</em> being assigned within download_image, but the original dictionary remained empty at the end.</p><p>So I created a class object to hold onto the dictionary and not have to worry about scope. After some debugging I got it to work and felt proud of my class.</p><blockquote><strong>Aside</strong>: This is actually how I first really started working with objected-oriented programming. I never really understood what was going on in course lectures. In deep learning with fastai and my own projects, I ran into the wall of having to pass data way up and down a stack of functions. You either have to have a huge number of arguments — which easily leads to confusion and restricts the way you can work — or you use a class object that has attached data you can just access.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rb9p-Py14YGjFOF2-gkEDQ.png" /><figcaption>ImageDownloader class at the end of a debugging session. Downloading is commented out, and I’m testing if anything gets stored in the dictionary</figcaption></figure><p>And the new downloader.url_fname_dict … was still empty. I spent a few hours on this problem, and found a dozen ways to poke and prod at it until I had a thought:</p><blockquote>“I had issues with download_images using multiple processes in the past, right? Wait, with max_workers=8 there are 8 processes trying to store data in the dictionary at the same time… does Python handle that? I feel like it’d just …not.”</blockquote><p>I tested this, setting max_workers to -1, 0, and 1 (I don’t know if 0 and -1 mean use every core and a lot of processes, or just one, so I tested them). And it worked like a charm.</p><p>There’s a thread on <a href="https://stackoverflow.com/questions/6832554/multiprocessing-how-do-i-share-a-dict-among-multiple-processes">stack overflow</a>. I don’t know <em>per se</em> if it’s related to my issue, but it felt right enough and I didn’t want to dive into multiprocessing / threading. So it turns out I didn’t even need a class at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*zFtbiq0L387FUDSeBATmMg.png" /><figcaption>399 file-url maps stored when `max_workers` ≤ 1; 0 stored when &gt; 1</figcaption></figure><p>So this worked. <em>And took. Forever</em>. Only 1 process, remember? That means if a link takes 10 seconds to download… you’re waiting. And there are about 10,500 images in the dataset. Then I realized something great.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMpbVkYHV62gfZpLGe_PsA.png" /></figure><p>I can just print the whole damn thing out. At full speed.</p><blockquote><strong>Aside</strong>: I’m trying to hone-in ways of doing things, for when I’m running a company. So the question becomes: would I be okay with doing this in my own company? Funny enough: the answer for brute-force quick ‘just get it done’ type deals, is not always no. Sometimes you can gain a <strong>lot</strong> of flexibility by sacrificing a little ‘elegance’ or automation. In this case the simple solution was a lot more powerful because it could run on the command-line and write to disk. I was stuck in the Jupyter notebook paradigm, and gained a lot by letting go.</blockquote><p>Then copy-paste to a text file, and run a few <a href="https://www.youtube.com/watch?v=DRR9fOXkfRE">regex</a> filters to extract the filepath and its corresponding url, then put them into your dictionary.</p><p>I made 4 regex filters:</p><pre>fail_pat = re.compile(r&#39;Error \S+&#39;) <em># split</em><br>clas_pat = re.compile(r&#39;downloading: \S+&#39;) <em># split</em><br>save_pat = re.compile(r&#39;data/\S+&#39;)<br>link_pat = re.compile(r&#39;\s-\s\S+&#39;) <em># split</em></pre><p>The ones with ‘split’ comments need part of their filtered text removed, since I don’t know how to do that in regex yet. The dictionaries are just <a href="https://docs.python.org/3/library/collections.html">defaltdicts</a>:</p><pre>removal_urls = defaultdict(<strong>lambda</strong>:[])<br>file_mapping = defaultdict(<strong>lambda</strong>:{})</pre><p>Then building the file-url mapping, and the first bit of urls to remove:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JmWDeE7HdWguAmdw1Duaqw.png" /><figcaption>urls that don’t download are the first additions to `remove_urls`</figcaption></figure><p>Everything’s finally ready for cleaning.</p><h3>2. Datacleaning</h3><p>There are 3 parts to cleaning this dataset:</p><ol><li>Verify downloads (remove corrupted/incomplete images)</li><li>Visual inspection</li><li>Update URL files</li></ol><p>In practice, I did parts of 2. before 1., but the result is the same. FastAI has a useful function to verify images are viewable and have 3 color channels, and which also lets you resize them. The original dataset was about 2.27GB, resizing to a max of 500px on a side brought it down to 141MB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnNZuz0syeuOdtintFfmdw.png" /></figure><blockquote><strong>Aside</strong>: I love that there are a lot of Deep Learning tasks that you can do on a laptop. The GPUs are only for training intensive models &amp; data. Resizing and scanning 6–10k images, +2GB worth, took only a minute or two, if that.</blockquote><h4>2.1 Visual Inspection</h4><p>This was interesting, and touches a dull and controversial part of AI.</p><p>I have opinions.</p><p>A lot of people use Amazon’s Mechanical Turk (perhaps a <a href="https://en.wikipedia.org/wiki/The_Turk">questionable</a> name, by the way) to bulk label data. I don’t like the idea of paying someone pennies for mindless work. So imagine the constraint:</p><blockquote>you’re on your own and you have no money. find a smart way to do this.</blockquote><p>Now, I can’t apply the assumption that the funds and resources always exist to tackle a problem directly, because when I look at my bank account the assumption doesn’t hold. So instead of buying off the problem, you have to consider more moving parts and how they fit together. If you’re a <em>part</em> of this system, besides being its architect, where do you fit in?</p><p>For vision we’re very good at picking the odd-one-out. Other fast.ai students put together a Jupyter widget that lets you review and delete or re-classify images. It creates a .csv file reflecting your changes so the dataset isn’t altered. This is definitely how I’d do it. One problem: the interface is made for smaller datasets, and there isn’t a way to turn off training-set shuffling without playing with PyTorch dataloaders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRVeI1pQ7LioqCI_g0IKBA.png" /><figcaption>A step in the right direction; but this just isn’t going to cut if for 10,000+ images.</figcaption></figure><p>What would be <em>perfect</em> is if I could have a full screen of images to review, and if I could do so by class. That requires likely-major edits to the ImageCleaner widget and another side-quest into learning how to build Jupyter widgets. I dont want to spend time on that. It’s also likely quixotic because that’s probably what the ImageCleaner will evolve into anyway.</p><p>But by letting go of a little functionality, I can gain a lot of usability.</p><p>Turns out I can pretty much get what I need, and how I want it, on my OS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EJRMwTAT1xYwIUTcdOveg.png" /><figcaption>A bit small though. Can we get a balance between ‘batch size’ and visibility?</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yu85NGMlkBRg-qa-jFXJag.png" /><figcaption>Perfect.</figcaption></figure><p>This is where the work of mapping filenames to urls pays off. I can delete any images I want, and record the changes to the dataset. I started by scrolling through and picking out corrupted images (file-icon with no picture) and images that obviously didn’t belong. For 10,241 images in 27 classes this took 20 minutes. FastAI’s image verifier handles this in 1/20th the time.</p><p>I wanted finer control so I used macOS’s gallery view to scan each image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDDQQTr0xE0heYRjByzZLA.png" /><figcaption>Do I want to recognize silhouettes? I don’t know if this would hurt or help the model so I’ll leave it in. Oh, and I think the artist is <a href="https://fineartamerica.com/profiles/ivan-krpan.html?tab=artworkgalleries&amp;artworkgalleryid=762446">Ivan Krpan</a>.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jMtJWlNRkHRytQWKgBncw.png" /><figcaption>That is definitely an <a href="https://en.wikipedia.org/wiki/Sukhoi_Su-30">Su-30</a>, not an <a href="https://en.wikipedia.org/wiki/Sukhoi_Su-34">Su-34</a>.</figcaption></figure><p>It took about 3 and a quarter hours to go through every image. What’s important is I could choose how fine-grained I wanted control. I could run through the whole dataset in under an hour if I kept the icon-view.</p><h4>2.2 Updating the Dataset</h4><p>I’m using a folder of text files containing the URLs of the images that make up my dataset. Thanks to the work done earlier, that’s very easy to update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjFrAQGQnfwb7bjvZKmPxw.png" /><figcaption>a more efficient way to lookup filenames is to store in a `<a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries">dict</a>` then lookup instead of searching an <a href="https://docs.python.org/3/tutorial/datastructures.html#more-on-lists">array</a>. This is <a href="http://cooervo.github.io/Algorithms-DataStructures-BigONotation/big-O-notation.html">O(1) instead of O(n/c)</a></figcaption></figure><p>This is mostly reusing and modifying previous code. First you build a list of filepaths for each class folder. Then for each filepath key in your dictionary — corresponding to the current class — you check if it’s in your list. If not: add its URL to the removal_urls dictionary.</p><p>Then, for each class, you open and read the URLs file to a list — <em>not</em> adding URLs that exist in your removal_urls dictionary — and then overwrite the file.</p><p>Now you have a set of URL files containing links to images that belong in your dataset. You can choose to save the dictionaries if you want. <a href="https://pytorch.org/docs/stable/torch.html?#torch.save">PyTorch is useful for this</a> (if you defined a defaultdict with a lambda function <a href="https://stackoverflow.com/a/38456371">you’ll have to convert it to a </a><a href="https://stackoverflow.com/a/38456371">dict</a>):</p><pre>torch.save(dict(file_mapping), path/&#39;file_mapping.pkl&#39;)<br>torch.save(dict(removal_urls), path/&#39;removal_urls.pkl&#39;)</pre><p>And that’s it. You can use github or anything else to copy the URL files to the cloud GPU machine, then download the images there. I ran a final check to see how large the cleaned dataset was:</p><pre>tot = 0<br>for clas in aircraft_types: tot += len((path/clas).ls())<br>tot</pre><p>It was 6,373. From an original 10,241.</p><h3>3. Doing it again</h3><p>For zero-to-start on a 10k-image dataset, I’d estimate 1 hour with a cursory visual inspection, or 4+ with a detailed one. I showed a lot of code here, but that was the discovery process. To do it again — after modifying the download code to print filepaths and urls, (and getting your urls)— all you really need is: a download block,</p><pre><em>for url_path in urls.ls():</em><br><em>    aircraft_type = url_path.name.split(&#39;.&#39;)[0] # get class name</em><br><em>    print(f&#39;downloading: {aircraft_type}&#39;)</em><br><em>    dest = path/aircraft_type; dest.mkdir(parents=True, exist_ok=True) # set &amp; create class folder</em><br><em>    download_images(url_path, dest)</em></pre><p>(save the printout to a text file). One line for verification,</p><pre><strong>for</strong> c <strong>in</strong> aircraft_types:<br>    verify_images(path/c, delete=<strong>True</strong>, max_size=500)</pre><p>(do a visual inspection); then the regex filters:</p><pre>fail_pat = re.compile(r&#39;Error \S+&#39;) <em># split</em><br>clas_pat = re.compile(r&#39;downloading: \S+&#39;) <em># split</em><br>save_pat = re.compile(r&#39;data/\S+&#39;)<br>link_pat = re.compile(r&#39;\s-\s\S+&#39;) <em># split</em></pre><p>The work is done by three blocks. One to record broken links (from printout):</p><pre><strong>with</strong> open(download_printout_path) <strong>as</strong> f:<br>    <strong>for</strong> line <strong>in</strong> f:<br>        <em># update class</em><br>        aircraft_type = clas_pat.findall(line)<br>        clas = aircraft_type[0].split()[-1] <strong>if</strong> aircraft_type <strong>else</strong> clas<br>        <em># search download path &amp; url</em><br>        save,link = save_pat.findall(line), link_pat.findall(line)<br>        <strong>if</strong> save <strong>and</strong> link: <br>            link = link[0].split(&#39; - &#39;)[-1]<br>            file_mapping[clas][save[0]] = link<br>        <em># search failed download url</em><br>        fail_link = fail_pat.findall(line)<br>        <strong>if</strong> fail_link: removal_urls[clas].append(fail_link[0])</pre><p>another to record the cleaned-out files:</p><pre><em># lookup urls of missing files in file_mapping &amp; add to removal_urls</em><br><strong>for</strong> clas <strong>in</strong> aircraft_types:<br>    flist = (path/clas).ls() <em># pull all filepaths in class folder</em><br>    <strong>for</strong> fpath <strong>in</strong> file_mapping[clas].keys():<br>        <strong>if</strong> Path(fpath) <strong>not</strong> <strong>in</strong> flist:<br>            removal_urls[clas].append(file_mapping[clas][fpath])</pre><p>and a final block to update the url files:</p><pre><strong>for</strong> aircraft_type <strong>in</strong> removal_urls.keys():<br>    fpath = path/&#39;fighterjet-urls&#39;/(aircraft_type + &#39;.txt&#39;)<br><em>    # open file; read lines<br></em>    <strong>with</strong> open(fpath) <strong>as</strong> f: text_file = [line <strong>for</strong> line <strong>in</strong> f]<br>    <strong>for</strong> i,line <strong>in</strong> enumerate(text_file):<br>        line = line.rstrip() <em># remove trailing /n for searching<br>        # remove line from text file</em><br>        <strong>if</strong> line <strong>in</strong> removal_urls[aircraft_type]: text_file.pop(i)<br>    # overwrite url files<br>    <strong>with</strong> open(fpath, mode=&#39;wt&#39;) <strong>as</strong> f: <br>        <strong>for</strong> line <strong>in</strong> text_file: f.write(line)</pre><p>The entire process is: download &amp; print → verify &amp; inspect → record broken links &amp; removed files → update url files.</p><p>And there you have it. Time to ID some fighter jets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=687919b10a7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/datacleaning-fighter-jets-687919b10a7e">Datacleaning fighter jets</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Planet, revisted 2]]></title>
            <link>https://medium.com/data-science/planet-revisted-2-b47995a8567?source=rss-febe20a208a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b47995a8567</guid>
            <category><![CDATA[satellite-imagery]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Wayne Polatkan]]></dc:creator>
            <pubDate>Sun, 25 Nov 2018 15:50:15 GMT</pubDate>
            <atom:updated>2018-11-25T15:50:15.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>Planet, revisited 2</h3><p>satellite imagery analysis with fastai 1.0</p><p>[<a href="http://medium.com/@nixalo/planet-revisited-ca37faefab45/">Part 1</a>]</p><p>This post is a bit of an experiment. I’m consistently impressed and confused by researchers like Leslie Smith and Jeremy Howard for the quality, and quantity of their work — and how complicated <a href="https://www.fast.ai/2018/04/30/dawnbench-fastai/">their experiments</a> seem from the outside. One of the biggest challenges in learning AI is simply keeping track of what I’m doing and <em>why</em>. How do you organize a project when you’re running multiple experiments in parallel and also have other things to do? <em>Keeping notes may be a good idea…</em></p><p>To experiment with doing better experimenting, this post is largely the result of running notes while working. It already helped me spot a few errors and hone in a few thoughts. First though, a recap on some important work-infrastructure developments since last time.</p><h3>Part 1.5:</h3><p>This is a bit of a jump from part 1. Long story short: there was a lot of fighting to get the planet data downloaded to the virtual machine, and a lot more fighting to get Kaggle’s API working. All this was replaced by a few lines of code in the new fast.ai course notebook. Adapting that a bit, made for a very fast setup process (these are done inside a Jupyter notebook on a Linux machine):</p><p>install the Kaggle API in your environment:</p><pre>! pip install kaggle --upgrade</pre><p>move your Kaggle API key where it needs to be after creating it:</p><pre>! mkdir -p ~/.kaggle/<br>! chmod 600 kaggle.json<br>! mv kaggle.json ~/.kaggle/</pre><p>Make a data directory (after from fastai import *):</p><pre>path = Config.data_path()/&#39;planet&#39;<br>path.mkdir(parents=True, exist_ok=True)</pre><p>Download the data:</p><pre>! kaggle competitions download -c planet-understanding-the-amazon-from-space -f train-jpg.tar.7z -p {path}</pre><p>(&amp; do the same for test-jpg.tar.7z, train_v2.csv, and test_v2_file_mapping.csv)</p><p>Unzip the .zip’s like so:</p><pre>! unzip {path}/train_v2.csv.zip -d {path}</pre><p>Unzip the .tar.7z’s like so:</p><pre>! 7za -bd -y x {path}/train-jpg.tar.7z -o{path}<br>! tar -xf {path}/train-jpg.tar -C {path}</pre><p>And clean out the archive files (this deletes all .zip, .7z, and .tar files in {path} recursively and without asking for confirmation):</p><pre>! rm -rf {path}/*.zip<br>! rm -rf {path}/*.7z<br>! rm -rf {path}/*.tar</pre><p>That’s about it. The other big takeaways were learning how to do some basic things in the fastai library, and finding better ways to enable quick experimentation (like specifying classification-cutoff thresholds, automatically creating a submission file based on those, and uploading to Kaggle). I think I’ll do a mini-post just on that, since mechanical/infrastructural things like that are the hardest part of a project before you get them working, after afterwards seem so straightforward you almost forget about them. <em>I’ll put a link here when I do that</em>.</p><h3>Part 2:</h3><p>The goal is to ‘win’ the <a href="https://www.kaggle.com/c/planet-understanding-the-amazon-from-space/">Planet Amazon Kaggle</a> competition before continuing on to the <a href="http://xviewdataset.org/">xView</a> dataset. My idea is to use <a href="http://blog.kaggle.com/2017/10/17/planet-understanding-the-amazon-from-space-1st-place-winners-interview/">the winning solution</a> as a starting point. But before that, I want to beat an artificial benchmark: <strong>0.93</strong> (private leaderboard) with ResNet34, just to make sure I have a solid model working.</p><p>I wasn’t able to improve much over the fast.ai course implementation at first. I tried “progressive refreezing” which is locking in layers after unfreezing a model, and that failed badly both times, despite the validation metrics appearing alright. This resulted in a leaderboard score drop from ~0.92 to 0.3 — 0.5 if I played with thresholds. That’s a drop from about 100th place, to 920th…out of 938. Crashes like that are usually the result of messing up the submissions file, but I haven’t tested to find out exactly what happened yet.</p><p>I was about to move on, until I got my 4th best score <em>twice</em> in a night. And one of those scores was trained on only 80% of the data. Currently that’s at <strong>0.92638</strong>. But why 4th? Because in 2017 following along an earlier version of the class, I got <strong>0.92873</strong> with a ResNet34. How did I get a better score with the same model and a more limited version of the fastai library (0.7)?</p><p>Looking <a href="https://github.com/WNoxchi/Kaukasos/blob/master/FADL1/L3CA_lesson2-image-models.ipynb">at that notebook</a>, there was an important bit of intuition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5B7KaJwRAQI5IlYrFJ6SRQ.png" /><figcaption><a href="https://github.com/WNoxchi/Kaukasos/blob/master/FADL1/L3CA_lesson2-image-models.ipynb">https://github.com/WNoxchi/Kaukasos/blob/master/FADL1/L3CA_lesson2-image-models.ipynb</a></figcaption></figure><p>The convolutional layers are trained more aggressively than normal, because they were pretrained on ImageNet — which doesn’t contain <em>any</em> satellite imagery. <em>Well that makes sense</em>. Instead of the typical 10x change to the learning rate per layer group, I used a 3x. And also very large initial learning rates (lr=0.2). (looks like you also finetune the linear layer more, but I missed that bit at first)</p><p>The next day (today, actually) I came back to test this idea. It seemed like the more aggressive discriminative learning rates (DLRs) did better early on, compared to the older learning rates. The loss fell quickly… but it seemed to fall from and to a higher value.</p><blockquote><strong>Note:</strong> I’m going to be referring to the same model trained a few different ways. So that this is less confusing: norm-1 is the model trained ‘normally’ before I started looking at larger learning rates. aggr-n is the n’th more aggressively-trained model. Typically the aggr&#39;s will have a difference of power-3 between layer groups (say: LR/9, LR/3, LR), and norm-1 will have power-10. Unless otherwise noted, all runs train for a total of 24 epochs: a length-6 1-cycle for each stage (1:linear, 2:full-conv), for each size.</blockquote><p>A graph of the aggressive run’s size128 2nd stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*2m4oJqxSx0O2SaZ5B408BA.png" /><figcaption>f1. the aggressive model experiences a sharp loss drop, but froma higher starting point</figcaption></figure><p>and compare that with the first run (norm-1)’s size128 2nd stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*NUX8m05BMCsnsZF2nSh_xg.png" /><figcaption>f2. the ‘normally-trained’ model has a shallower loss drop, but from and too lower values</figcaption></figure><p>and the final loss plots (orange is validation) of the aggressive run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*KkZtRBy32Zk3C_c92PU17A.jpeg" /><figcaption>f3. final loss plot of the aggressive run, aggr1</figcaption></figure><p>compare that to the normal run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*DP1JpOx3tzHfgieT-hVTcg.png" /><figcaption>f4. final loss plot of the normally-trained run, norm1</figcaption></figure><p>What you want is something like the latter. <a href="https://sgugger.github.io/the-1cycle-policy.html">OneCycle</a> explores the ‘solution space’ and gives a bump in loss, and then settles to a near-constant low value. This is not quite what’s going on in the new run… so either I’m being <em>too</em> aggressive, or maybe I need longer training to settle things down a bit; because that top graph looks like things are very much in flux.</p><blockquote><strong>Aside</strong>: Also if you’re wondering, I’m using the material-dark theme in jupyter lab. I find myself using jupyter lab more than notebook because, although it has fewer useful extensions than notebook, it comes inbuilt with views so you can look at multiple notebooks, or multiple parts of notebooks at the same time.</blockquote><p>After submitting predictions to Kaggle … the new model doesn’t do better. I have a hunch that it’s because I made the learning rates — all of them — <em>too</em> aggressive. For size128 stage2 I used learn.lr_range(slice(lr/2/9, lr/2)) = lr/2/9, lr/2/3, lr/2, but in size256 stage2 I used: lr/9, lr/3, lr.</p><p>Putting the results into a readable form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*23XRQB3L39PT9BzxZt3pKw.png" /><figcaption>f5. results for norm-1 and aggr-1</figcaption></figure><p>norm-1 is the ResNet model that follows the fastai course notebook. aggr-1 is the first ‘aggressive’ model. I think I went <em>way</em> too hard with my DLRs in the new model. In some cases I was training at <em>3 orders-of-magnitude</em> higher LRs than before.</p><p>But here’s another thought: how much of that ‘aggressive finetuning’ has to be done after the first go? Could you start with that hard turn to adjust weights from real-world to satellite-imagery ‘mode’, then go back to a ‘calmer’ training schedule? I’m going to try that now.</p><blockquote><strong>Intermission</strong>…</blockquote><p>I tried that (aggr-2), and it worked worse than either the norm-1 or aggr-1… The loss plots looked good, but I think it just wasn’t trained <em>enough</em>. Looking at the numbers, the model looks <em>underfit</em>. Training loss is 1.8% higher than validation: 0.083386 vs 0.081870, threshold-accuracy dropped on the order of a hundredth of a percent, and fbeta score rose by about 0.3% from 0.924608 to 0.927831.</p><blockquote><strong>Note</strong>: it looks like the biggest difference with the <a href="https://github.com/WNoxchi/Kaukasos/blob/master/FADL1/L3CA_lesson2-image-models.ipynb">original notebook</a> is <em>additional progressive resizings</em>. Other than that it seems to follow the 6-epochs per stage, and 2-stages (freeze, unfreeze) per size, training format.</blockquote><blockquote>The old notebook starts with size 64, then 128, then 256.<strong> I may want to try this</strong>.</blockquote><p>But before that…. extra training on aggr2 …. an extra 6-length 256-stage-2 cycle with halved LRs… is actually performing better than aggr2 instead of crashing. The final loss plot looks like what you’d expect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*6rN1W-5xMihT9-eV8_UE_A.png" /><figcaption>f6. final losses of aggr2 trained for an extra cycle at 1/2 DLR</figcaption></figure><p><em>Well that’s interesting</em>…</p><p>A few notes here. I originally thought that aggr1 was outperforming norm1 because I mixed up the values for those two (I corrected the results up at f5). Turns out it isn’t, but the extra training does consistently help aggr2x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*WWFLRUMv7ZMivQRDY9uCrA.png" /><figcaption>f7. private leaderboard results for all models</figcaption></figure><p>Aggressive training is working, and it doesn’t look like I was being all too aggressive with the LRs. And despite confusing experiences in the past, training a 2nd stage2 cycle at the end actually helps the model a bit.</p><p>Now time to train aggr1 (since I saved the weights, I can just reload it) for an extra cycle and see what happens. Next I’ll try progressive resizing through 64–128–256.</p><blockquote><strong>Intermission</strong>…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*SZ0M8xbQ4c_SuALA75YVlQ.png" /><figcaption>f8. That’s an interesting looking plot..</figcaption></figure><p>The funny thing about this is, at 96% accuracy we’re really just chasing a number. This is 96% accuracy is calculated by:</p><p>((preds&gt;thresh).float()==targs).float().mean()</p><p>This creates a one-hot encoded tensor (eg. [0.,1.,1.,0.,..]) with 1’s wherever the prediction matches the target, and zero everywhere else. The average is returned as the accuracy value.</p><p>The predictions are thresholded: any probabilities greater convert to 1, else 0. This is compared to the target (which is also 1-hot).</p><p>This also hides the fact that the model can get very high accuracies by learning to ignore rare classes (0==0) = 1. Nonetheless the leaderboard <a href="https://www.kaggle.com/c/planet-understanding-the-amazon-from-space#evaluation">F2 scores</a> are still stellar at +0.92.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*OtVAVVbyQ1ruPmPI-Xk3ng.png" /></figure><p>Unfortunately the model didn’t improve. I wonder if reloading a model, then training further — as I did here — has a different outcome than continuing to train a model you’re already working on. I don’t have the time to test that right now. Instead, it’s time for progressive resizing with the best working model. This’ll take at least an hour. Something I really like about AI work is how it pushes you towards being organized. If you schedule your jobs and plan for the wait-times, you get a lot of free time on your hands.</p><p>And I think that makes a good stopping-off point for this post. Next up will be the results of progressive resizing from size-64, comparing a 6-cycle model with a 7-cycle one and one with a double-length 6th cycle. After that, it’s “train the best one on the entire dataset and see what you get”. <em>After that: </em>do it again with ResNet50, and take care to note if the larger model handles the larger learning rates better.</p><p>With all that done, it’ll be a rush to implement the dehazer and see if adding L2 regression is worthwhile. My goal is to get started on xView on Monday, day after tomorrow, so we’ll see how that goes.</p><p>Before looking at longer or multiple cycles (which gave me some bad results), or referring back to the 2017 notebook, I’m going to see what happens if I train the size256 model at LR/2 and LR/5 (which is the max value of the ‘normal’ model).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b47995a8567" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/planet-revisted-2-b47995a8567">Planet, revisted 2</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Planet, revisited]]></title>
            <link>https://medium.com/data-science/planet-revisited-ca37faefab45?source=rss-febe20a208a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca37faefab45</guid>
            <category><![CDATA[satellite-imagery]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Wayne Polatkan]]></dc:creator>
            <pubDate>Sat, 10 Nov 2018 21:15:48 GMT</pubDate>
            <atom:updated>2018-11-10T21:15:48.569Z</atom:updated>
            <content:encoded><![CDATA[<p>satellite imagery analysis with fastai 1.0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*b19k-IYSkxqNuwOHVOjp2A.png" /></figure><p>I wanted to work on the <a href="http://xviewdataset.org/">xView</a> dataset, <a href="https://www.diux.mil/">DIUx’s</a> satellite imagery competition. I haven’t done computer vision work in a while, and with the 1.0 release and prerelease of <a href="https://www.fast.ai/2018/10/02/fastai-ai/">fastai</a> and <a href="https://pytorch.org/">PyTorch</a> I figured revisiting the <a href="https://www.kaggle.com/c/planet-understanding-the-amazon-from-space">Planet Amazon Kaggle competition</a> would be a good warm-up.</p><p>My aim is to beat the top-ranking score before moving on. That place is held by <a href="https://www.kaggle.com/bestfitting">bestfitting</a>, who’s currently the 2nd-ranking competitor on Kaggle, and previously 1st. So my first stop was to check out <a href="http://blog.kaggle.com/2017/10/17/planet-understanding-the-amazon-from-space-1st-place-winners-interview/">his interview</a> — since Kaggle interviews competition winners on its blog. I actually came back to this a few times: confused the 1st time, and with a feeling of “oh that was it?” the last time.</p><p>Here’s a thing. It’s really easy to get knocked off balance when you’re reading a new technical-<em>anything</em> by someone who knows what they’re doing. What you find over and over is that what felt like a big deal, wasn’t. Very often the underlying concept for a task in machine learning (or any field) is very straightforward. Being able to context-switch from low-level details to high-level overviews is very valuable.</p><p>So the first order, was to see how the winner did it. There’ll be room for innovation with xView; my goal is to get through this quickly, and the competition’s done. So let’s see what worked.</p><p>I think I read the interview 3 times, and wrote-&amp;-drew a diagram of what bestfitting was talking about twice, to hold my hand through the process. The gist of it is this:</p><ul><li>use a dehazing algorithm to preprocess the images (make foggy→clear)</li><li>use an ensemble of ~a dozen models</li><li>feed each model’s output to its own <em>ridge regression </em>model/layer<em> </em>to learn correlations in the data</li><li>feed the ensemble’s output to a final ridge regression model.</li><li>also use an F2 loss function</li></ul><p>What’s <a href="https://en.wikipedia.org/wiki/Tikhonov_regularization">ridge regression</a>? A few days to a week of <a href="https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/NCSS/Ridge_Regression.pdf">confused</a> <a href="https://onlinecourses.science.psu.edu/stat857/node/155/">reading</a> <a href="http://statweb.stanford.edu/~tibs/sta305files/Rudyregularization.pdf">later</a>, what I got is: ‘Ridge Regression’ is linear regression with a sum-of-squares term added to the loss function. <a href="https://towardsdatascience.com/l1-and-l2-regularization-methods-ce25e7fc831c">Anuja Nagpal’s post</a> was key in zeroing things in for me. So… ‘<a href="https://hackernoon.com/practical-machine-learning-ridge-regression-vs-lasso-a00326371ece#f0f7">ridge regression’ adds L2 regularization</a> to the loss function… (and has an L1 counterpart that adds a sum-of-magnitudes term, called ‘Lasso Regression’).</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*jgWOhDiGjVp-NCSPa5abmg.png" /><figcaption>from <a href="https://towardsdatascience.com/l1-and-l2-regularization-methods-ce25e7fc831c">Nagpal’s post</a></figcaption></figure><p>Here’s another thing. When I hear that some tool was used to “find correlations in the data” and “select the strongest models to predict each label” my mind goes to town, especially when the tool has its own name. Because at first pass, I have trouble imagining how regression with a summed-squares term is going to do something that sounds — dare I say — <em>intelligent. </em>There’s no way it could be something that you could just <a href="https://github.com/WNoxchi/Kaukasos/blob/master/misc/ridge-regression-tutorial_analytics-vidhya_20181020.ipynb">import from scikit-learn</a> or code into a neural-net as a layer, <em>right</em>?</p><p><em>But still</em>. <em>How does it do </em><strong><em>that</em></strong>? “Select a model” and all. I’ll tell you when I get there. The in-house names for things add friction to entering a field, though. Just call it what it is.</p><p>At this point, the only confusion I have about ‘ridge regression’ or L2 regression or etc., is stuff that just gets answered by doing it. When bestfitting says they use a <em>model</em>, do they mean they coded a mini neural-net in PyTorch, or imported from scikit-learn? Or is just a linear layer of a neural net (say, tacked on to the classifier head of a CNN model) with L2 regularization? That last one makes more sense…but how do you train it? See, the model-wise regressors make sense: make it a layer and train normally. But the ensemble-wise regressor… you’re not making a giant neural net of an ensemble and training that in one go. Even if you have the resources, the different models will have different training regimens. So that last regressor is either a PyTorch or scikit-learn model right? Sounds like it has to be. Then you fit it too, between the ‘raw’ predictions and actual labels, right?</p><p>…unfortunately you have to be ranked “Contributor tier” to be permitted to contact other people on the Kaggle, so I couldn’t easily ask. We’ll see when we get there.</p><p>This left one last detail before the work: dehazing. Dehazing is what it sounds like: it just removes the haze from hazy images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QWar30YGNCRLfxeg7qDjag.png" /><figcaption>from: <a href="https://github.com/anhenghuang/dehaze/tree/master/image">anhenghuang/dehaze</a></figcaption></figure><p>Bestfitting used an algorithm based on the paper: <a href="https://www.robots.ox.ac.uk/~vgg/rg/papers/hazeremoval.pdf">Single Image Haze Removal Using Dark Channel Prior</a>. It shows impressive results. I decided I wasn’t going to implement it — I’m playing with the idea that getting a project done quickly involves picking which hills to plant your sword in. I just looked for a good plug-&amp;-play version. I still spent a day on this. I found a <a href="https://github.com/anhenghuang/dehaze">Python version</a>, but that took a second to run so I found a <a href="https://github.com/cedarz/DeHaze">C++ version</a> that took even longer to run, after I finished fighting with Xcode and relearned how to build a project in it. So I thought, “let’s just use a neural-net to do this”. But I want to be disciplined in how I do this right? I don’t want to drown in setting up an environment <em>just right</em> to run a model that I’m only using once as a preprocessor. So I found a <a href="https://github.com/zlinker/DehazeNet">ready-to-go Caffe model</a>! Never used a compiled neural-net before, better learn some time. One catch. <a href="http://caffe.berkeleyvision.org/installation.html">How</a> <a href="https://gist.github.com/arundasan91/b432cb011d1c45b65222d0fac5f9232c">do you install</a> <a href="http://installing-caffe-the-right-way.wikidot.com/start">Caffe</a>? Preferably without altering your system for something you plan on using once. Ah there’s a way to <a href="https://caffe2.ai/docs/caffe-migration.html#caffe-to-caffe2">convert Caffe to Caffe2</a> (which comes with PyTorch’s conda install)… which involves caffe imports, thus requiring <em>Caffe </em>— you know what I’m going with the python version.</p><p>— I also found a couple other dehazers on github. <a href="https://github.com/hezhangsprinter/DCPDN">DCPDN</a> &amp; <a href="https://github.com/TheFairBear/PyTorch-Image-Dehazing">AOD-Net</a>. —</p><p>Now I’m ready to actually do some deep learning. Well not quite yet because somewhere in the playing with Xcode and HomeBrew and whatever else, I managed to break my Mac’s Python 2 install — which incidentally is what Google uses and thus the why <a href="https://cloud.google.com/sdk/gcloud/">gcloud</a> couldn’t connect to my <a href="https://cloud.google.com/compute/">GCP</a> instance; instead throwing a confusing ‘module zlib not found’ ImportError. I forgot <a href="https://github.com/Homebrew/homebrew-core/issues/29176#issuecomment-398656987">how I fixed that</a>. Something with downloading Xcode Commandline Tools from the <a href="https://developer.apple.com/downloads/more">Apple Developer Site</a> since it wouldn’t work from the <em>command line</em>. Then something with HomeBrew. That took a day. May’ve been the same day.</p><p>Nightmares like this are why I use checklists.</p><p><em>Now</em> I’m ready to get started with <a href="https://docs.fast.ai/">fastai</a>. And I’ll write about that in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca37faefab45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/planet-revisited-ca37faefab45">Planet, revisited</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comp.LinAlg L2: Topic Modeling with NMF & SVD]]></title>
            <link>https://medium.com/@nixalo/comp-linalg-l2-topic-modeling-with-nmf-svd-78c94330d45f?source=rss-febe20a208a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/78c94330d45f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <dc:creator><![CDATA[Wayne Polatkan]]></dc:creator>
            <pubDate>Mon, 25 Sep 2017 14:55:35 GMT</pubDate>
            <atom:updated>2017-09-25T14:55:35.961Z</atom:updated>
            <content:encoded><![CDATA[<p>This lecture deals with working on unlabeled data. The basic idea as with all unsupervised learning algorithms is that you can infer relationships and other items of interest by looking at how the data relates to one another. In this case, we’re trying to figure out what topic a piece of text is about. Hence: Topic Modeling. Two methods of doing this are <a href="https://en.wikipedia.org/wiki/Singular-value_decomposition">Singular Value Decomposition</a> and <a href="https://en.wikipedia.org/wiki/Non-negative_matrix_factorization">Non-negative Matrix Factorization</a>.</p><p>The Jupyter notebook for this lesson is <a href="http://nbviewer.jupyter.org/github/fastai/numerical-linear-algebra/blob/master/nbs/2.%20Topic%20Modeling%20with%20NMF%20and%20SVD.ipynb">located here</a>.</p><p>Put short: “the SVD algorithm factorizes a matrix into one matrix with <strong>orthogonal columns</strong> and one with <strong>orthogonal rows</strong> (along with a diagonal matrix, which contains the <strong>relative importance</strong> of each factor).”</p><p>The principle idea is that, for the purpose of telling two topics apart, words that occur frequently in one topic will occur rarely in an unrelated topic; otherwise a word that occurs often in two topics — like ‘is’ — would be useless on its own for telling the two apart. Therefore the vectors representing different topics should be orthogonal to one another, that is: their <a href="https://en.wikipedia.org/wiki/Dot_product">Dot Product</a> should be zero. <em>Note:</em> an orthogonal matrix has orthonormal columns and rows. <em>English</em>: each row or column vector of the matrix, dot-product’ed with itself equals One, with any other row/col equals Zero.</p><p><em>Aside: I feel like this a simple way to approach similarity/differences.. given that it’s a binary One/Zero. I expect to see more gray-area as the material progresses.</em></p><p>Okay, sounds simple enough. Facebook research actually has <a href="https://research.fb.com/fast-randomized-svd/">a good post on this</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*tsC2s0e-Ra0mcPQz8R7Chw.png" /><figcaption>source: <a href="https://research.fb.com/fast-randomized-svd/">https://research.fb.com/fast-randomized-svd/</a></figcaption></figure><p>A note on the above: SVD is an <strong>exact</strong> decomposition. The <strong>≈</strong> sign would be an <strong>=</strong> sign if <strong>r</strong> = <strong>n</strong> (same dimensions). This means the original matrix can be completely recovered from a decomposition. <strong>A</strong> is a matrix of words * hashtags detailing how often a word shows up in a post with a certain hashtag. <strong>U</strong> is composed of orthogonal columns of words * topics , <strong>V</strong>^T of orth. rows, topics * post and <strong>Σ </strong>is a diagonal square matrix which relates the relative importance between words &amp; hashtags.</p><p>The uses of SVD extend to semantic analysis (today’s topic), collaborative filtering &amp; recommendations, calculating the <a href="https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse">Moore-Penrose Pseudoinverse</a>, data compression, and principal component analysis.</p><p>In a lot of data sets, negative values don’t make sense and are hard to interpret — this is where NMF comes in. Whereas in SVD everything needs to be orthogonal to one another, in NMF everything has to be non-negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*dk8Wij9N8R2GLVddam2itw.png" /><figcaption><a href="http://nbviewer.jupyter.org/github/fastai/numerical-linear-algebra/blob/master/nbs/2.%20Topic%20Modeling%20with%20NMF%20and%20SVD.ipynb">Course Lesson 2 Notebook</a></figcaption></figure><p>NMF is also not exact, so you can’t get the original matrix back perfectly from the decomposition. Using NMF:</p><p>Say we’re analyzing Usenet posts from scikit-learn’s ’20 newsgroups’ dataset:</p><pre>categories = [&#39;alt.atheism&#39;, &#39;talk.religion.misc&#39;, &#39;comp.graphics&#39;, &#39;sci.space&#39;]<br>remove = (&#39;headers&#39;, &#39;footers&#39;, &#39;quotes&#39;)</pre><pre>newsgroups_train = fetch_20newsgroups(subset=&#39;train&#39; categories=categories, remove=remove)</pre><pre>vectorizer = CountVectorizer(stop_words=&#39;english&#39;)<br>vectors = vectorizer.fit_transform(newsgroups_train.data).todense()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joMTTBiFeXcRAlOLqpQiUA.png" /><figcaption>2,034 X 26,576 matrix</figcaption></figure><p>Then we set our dimensions:</p><pre>m, n = vectors.shape<br>d = 5 # num. topics</pre><p>And run the decomposition:</p><pre>clf = decomposition.NMF(n_components=d, random_state=1)</pre><pre>W1  = clf.fit_transform(vectors)<br>H1  = clf.components_</pre><p>fit_transform(X[, y, W, H]) is a method of sklearn.decomposition.NMF that learns an NMF model for the data X and returns the transformed data. components_: array, [n_components, n_features] is an attribute consisting of the factorization matrix. See: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.NMF.html">sklearn.decomposition.NMF</a>.</p><p>Taking a look at the results in the course notebook yields the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ms6Or6rhnD1y7tPp0xp8WA.png" /><figcaption>it’s clear each line fits a topic, even though these topics weren’t explicitly specified</figcaption></figure><p>NMF is easy to use and fast; although it took years of research and specific expertise to develop.</p><p>The lecture goes on to cover some important points, specifically the speedup from using PyTorch instead of NumPy if you have a GPU available. A final note: classical decomposition algorithms have a number of shortcomings, and randomized algorithms have some strong advantages. Straight from the course notebook:</p><p><strong>Shortcomings of classical algorithms for decomposition:</strong></p><ul><li>Matrices are “stupendously big”</li><li>Data are often <strong>missing or inaccurate</strong>. Why spend extra computational resources when input imprecision limits output precision?</li><li><strong>Data transfer</strong> now plays a major role in algorithm run time. Techniques requiring fewer passes over the data may be substantially faster, even if they require more <a href="https://en.wikipedia.org/wiki/FLOPS">FLOPS</a>. <em>(Important note for Big-O classically trained CS/Informatics students)</em></li><li>It’s important to take advantage of <strong>GPUs</strong>.</li></ul><p><strong>Advantages of randomized algorithms:</strong></p><ul><li>Inherently stable</li><li>Performance guarantees don’t depend on subtle spectral properties (matrix’s singular values)</li><li>Needed matrix-vector products can be done in parallel.</li></ul><p>— from <a href="https://arxiv.org/abs/0909.4061">Halko (arXiv)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78c94330d45f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starting Computational Linear Algebra]]></title>
            <link>https://medium.com/@nixalo/starting-computational-linear-algebra-5a07bec86889?source=rss-febe20a208a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a07bec86889</guid>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Wayne Polatkan]]></dc:creator>
            <pubDate>Fri, 15 Sep 2017 22:23:49 GMT</pubDate>
            <atom:updated>2017-09-15T22:31:12.016Z</atom:updated>
            <content:encoded><![CDATA[<p>Numerical…Computational…? yeah. LA. But the machine does the work.</p><p>Along with <a href="http://course.fast.ai/part2.html">Cutting Edge Deep Learning Part 2</a>, I’m just starting <a href="https://medium.com/u/ee56d0bac1b7">Rachel Thomas</a>’ <a href="https://github.com/fastai/numerical-linear-algebra/blob/master/README.md">Computational Linear Algebra</a>. And just as with the Deep Learning course, I’m thinking of writing a series of course notes here. First off: <em>why</em>?</p><p>I started my technical education with Professor <a href="https://www.edx.org/bio/robert-van-de-geijn">van de Geijn</a>’s <a href="https://www.edx.org/course/linear-algebra-foundations-frontiers-utaustinx-ut-5-05x-0">UT5.02x</a> Linear Algebra: Foundations to Frontiers on edX, and at the end of it, he mentioned his numerical LA class at UT Austin. At the time I was just excited that I could be ready to start a masters-level engineering course, but continued on to more immediate/practical work. Fast-forward to a week ago, that same excitement for diving deep into a subject came back when I saw the fast.ai announcement for the Comp-LA course. There’s a part of me that wants to go straight-up Heisenberg and disappear into research. At the same time, the rest of me wants to know: <em>where does this fit into the bigger picture?</em></p><p>So I started the first lecture as a test-drive to see if it could earn its keep in my triaged workload. Yes… yes it can.</p><p>The first motivation is that Computational (a.k.a. Numerical) Linear Algebra is what makes Deep Neural Nets work. Layers of matrix multiplies updated via Calculus’ chain-rule in the form of SGD. Alright, so in the future if I want better control over my ‘neural’ models, or if I want to implement some crazy ideas, it may pay to know how things work under the hood. But there’s more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ri91QGeRyfkXWGyTxzNEoQ.png" /><figcaption>From Lecture 01 of Computational Linear Algebra for Coders — orig. source: <a href="https://www.youtube.com/watch?v=0Il-y_WLTo4">Concepts of Markov Chains</a></figcaption></figure><p>Markov Chains. I vaguely remember a company’s coding challenge where you had to predict the end-state of a <a href="https://en.wikipedia.org/wiki/Absorbing_Markov_chain">terminating (‘Absorbing’) Markov Chain</a>. You could approximate its end state by multiplying the matrix by its transpose (I think?) repeatedly, but this wouldn’t give you the necessary accuracy before time ran out… the solution was to get the matrix into its canonical form, separate out some submatrices, create new matrices based on those, and finally multiply them together (<a href="https://math.dartmouth.edu/archive/m20x06/public_html/Lecture14.pdf">here is essentially it</a>). That problem would’ve been a lot easier if I knew anything of the subject before hand; especially how to code it… But there’s more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fx2zxYQMGL8IFkiqlkmk0g.png" /><figcaption>The single biggest moment for me in the first lecture. <a href="https://www.mff.cuni.cz/veda/konference/wds/proc/pdf06/WDS06_106_m8_Ulrychova.pdf">orig. source</a></figcaption></figure><p>I really can’t overstate how big the above example was for me. Not just because food is good. Because here is where it all clicked. <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a>’s lecture (L4) in <a href="http://course.fast.ai/lessons/lesson4.html">Practical Deep Learning</a> on embeddings, how LA is so integral to AI, and just…how <em>easy</em> this is. Then things went into overdrive, thinking about how all these things + other algorithms could be combined to create real powerful systems.</p><p>This is a hard problem to do by hand. Even with a computer and calculator: it’s tedious and easy to screw up — and what if you’re matching dozens to hundreds? Thousands?</p><p>Just Dot-Product them. You get your matrix of budgets and choose the smallest ones. Ah-ha.</p><p>Wait what about gigantic sparse matrices that will turn your RAM &amp; C/GPUs into Marxists? Oh there are algorithms that optimize for those… well this gets interesting.</p><p>But there’s more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXPt2psFUUgLz4VDlOidgw.png" /><figcaption>the Matrix has you</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIbynppEMamCrQSqQx6enQ.jpeg" /><figcaption>Red Pill, Please.</figcaption></figure><p><strong>And so we begin.</strong></p><p><strong>NOTE</strong>: there’s a lot more to the lecture than what’s covered above. Big things that come to mind are the <a href="https://www.youtube.com/watch?v=3uiEyEKji0M">Halide Talk</a>, writing code to optimize CPU/RAM locality &amp; parallelization more efficiently than doing so manually in C++ because simplicity lets you iterate more .. that was an eye opener. The part on floating-point numbers/arithmetic and how they’re stored, specifically: IEEE Double precision arithmetic (floats are more accurate closer to zero. Ariane 5, or <em>what happens when you try to fit a 64-bit number into 16-bit memory</em> (spoiler: Boom). And more.</p><p>[draft completed 01 Aug 2017]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a07bec86889" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning II L9: Generative Models]]></title>
            <link>https://medium.com/data-science/deep-learning-ii-l9-generative-models-dcd599ad6e0b?source=rss-febe20a208a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcd599ad6e0b</guid>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Wayne Polatkan]]></dc:creator>
            <pubDate>Thu, 14 Sep 2017 20:00:00 GMT</pubDate>
            <atom:updated>2017-09-18T21:01:00.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXKzaDsXKq4bj2hbQpwSWw.jpeg" /></figure><p>The <a href="http://course.fast.ai/lessons/lesson9.html">9th lesson</a> in <a href="http://www.fast.ai/">fast.ai</a>’s Deep Learning course continues the dive into Generative Adversarial Networks (GANs) from the perspective of making art. This mostly concerns the <a href="https://github.com/fastai/courses/blob/master/deeplearning2/neural-style.ipynb">neural-style</a> and <a href="https://github.com/fastai/courses/blob/master/deeplearning2/neural-sr.ipynb">neural-sr</a> Jupyter notebooks in the (as-of-writing) course repository. <em>Note</em>: this post is long. It starts simple, and keeps going deeper.</p><p>In <a href="http://course.fast.ai/lessons/lesson8.html">Lesson 8</a> we learned to take an image, stick it into a loss function consisting of style-loss and content-loss, outputting the loss and the gradients, and use those gradients to update the image and reduce the loss on the next iteration — and rinse and repeat. Like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OP7fNtVuU3xuIlmpyOOiPQ.png" /><figcaption>copyright: my notebook …</figcaption></figure><p>According to <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a> in the lecture, this is pretty much the best way to do style transfer for many different styles and images, like in a web app. However if you want to apply a single style to any image: this is where we can change things to do a lot better. The reason is you don’t need to do the above optimization loop to produce something. Instead you can just train a CNN to learn how to output images in a particular style (and a forward pass through a CNN is very fast — tradeoff being the CNN is trained on that particular style).</p><p>This time we start by feeding multiple images into the same loss function as before (Style + Content). Say in this example, for the Style-Loss we use Van Gogh’s Irises, and for the Content-Loss we use the current image being fed into the function. The big difference here is that we’ll put a CNN between the input images and the loss function. That CNN will learn to output an image such that when it gets thrown into the loss function it’ll output a small value for the loss. In English that means that the CNN has learnt to produce images that are both similar in content to the original input image, while also being stylistically similar to whatever was chosen for style.</p><p>A few notes here. With CNNs you can choose any loss function you’d like (your mileage may vary). <a href="http://course.fast.ai/">Deep Learning I</a> &amp; <a href="http://course.fast.ai/part2.html">II</a> has so far used fairly simple ones like <a href="https://en.wikipedia.org/wiki/Mean_squared_error#Loss_function">MSE</a> and <a href="http://neuralnetworksanddeeplearning.com/chap3.html#the_cross-entropy_cost_function">Cross-Entropy</a>. Here though, we’ll use Style + Content Loss, as in the first example above. <em>Note</em>: because that Style+Content Loss function was generated by a neural-net: it’s differentiable; And any differentiable loss function can be optimized.</p><p>Now if we take the output gradients with respect to the CNN’s weights, we can use them to update those weights so that the CNN will be better at turning an image into one that matches the style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhdZFwBp2Lt95Ja1dNOH2Q.png" /><figcaption>something like this</figcaption></figure><p>What’s powerful about this, again, is there’s no optimization step to slow down inference — or the ‘prediction’ operation of the model. The single forward pass through the CNN is more/less instantaneous.</p><p>There’s more you can do.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVxq9yj2pVWk%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVxq9yj2pVWk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVxq9yj2pVWk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/24766c803164494af0d19e953e264f4b/href">https://medium.com/media/24766c803164494af0d19e953e264f4b/href</a></iframe><p>Turns out, Deep-Learning Neural Networks can be used to enlarge images and infer the details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ghl-iJdCJvf8RrIlOCJtw.png" /><figcaption>we have the technology</figcaption></figure><p>We start by putting a CNN in between the LoRes and HiRes images. The CNN takes the LoRes image as input and sends its output into a loss function that only calculates Content Loss. The Content Loss is calculated by comparing its input from the CNN to the activations from the HiRes image. In other words, the loss function is checking if the CNN has created a larger image from the original LoRes, that has the same activations as the HiRes one.</p><p>This discussion prompted one of the best questions I’ve heard in the class:</p><blockquote>Can we just stick a CNN between any two things, and it’ll learn the relationship between them?</blockquote><p><a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a>:</p><blockquote>Yes, absolutely.</blockquote><p>And this gets into something we’re doing differently than before with CNNS. A <a href="https://arxiv.org/abs/1603.08155">2016 paper</a> details using a different loss function for CNNs to do Super-Resolution. Before this, <a href="https://en.wikipedia.org/wiki/Mean_squared_error#Loss_function">MSE</a> was typically used — between the upscaling-network pixel outputs and the HiRes image. Problem is: a blurry image will still perform well under <a href="https://en.wikipedia.org/wiki/Mean_squared_error#Loss_function">MSE</a>, but that’s sort of unacceptable for image tasks. On the other hand:</p><blockquote>…if you take the 2nd or 3rd conv-block of VGG, then it needs to know <em>this is an eyeball</em>, or it’s not going to look good.</blockquote><p>Lesson: use Content Loss instead of Pixel Loss.<em> (as an aside: it apparently took 1 year to go from using </em><a href="https://en.wikipedia.org/wiki/Mean_squared_error#Loss_function"><em>MSE</em></a><em> on the pixels to Content Loss. There’s something interesting about seeing the time it takes to uncover things that seem intuitive in retrospect.)</em></p><p>The <a href="https://arxiv.org/abs/1603.08155">paper</a> lists some useful applications of this method — framing them as <em>image transformation</em> tasks:</p><ul><li>Image Processing: Denoising, super-resolution, colorization</li><li>Computer Vision: Semantic segmentation, depth estimation</li></ul><p>(<em>another aside here is with Generative models you can produce as much labelled data as you want by just adding noise or making color images grayscale, etc.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ppIssdsBMyuvxwfJiJQQ0g.png" /><figcaption>high-level view of Content (Perceptual) Loss for Super Resolution or Style Transfer</figcaption></figure><p>2.Now to get into the code. See <a href="https://github.com/fastai/courses/blob/master/deeplearning2/neural-style.ipynb">neural-style.ipynb</a> if you want to follow along (Note: future updates to the course may change the code or notebooks altogether).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*QisWeJie5zqHebUyhYS-vQ.png" /><figcaption>the final network — “The Upsampling Network”</figcaption></figure><p>The code above starts by taking in a batch of low-res images as a tensor with dimensions of arr_lr.shape[1:] (which here is going to be: (72, 72, 3)). In the notebook, arr_lr and arr_hr are NumPy arrays.</p><p>inp = Input(arr_lr.shape[1:])</p><p>That input is then put into a convolutional block (defined earlier in the notebook) with 64 filters of size 9, and a unit stride (ie. no changes to input size).</p><p>x = conv_block(inp, 64, 9, (1,1))</p><p>This is a large filter size because we want a large initial receptive field. Apparently having 64 of them ensures no information is lost (coming from 3 color-channels), but I don’t know what that information loss curve of input — vs — filters looks like. But apparently this is also becoming common.</p><p>Next up is where most of the computation will be getting done. This is the part where the GAN has to figure out, for instance, <em>is that black dot an eyeball</em>, and then <em>what would a higher-res eyeball look like</em>.</p><p>for i in range(4): x = res_block(x) # res_block() is a <a href="https://arxiv.org/abs/1512.03385">ResNet</a> block defined elsewhere.</p><p>In Generative models we’ll want to do this main computation step at a low resolution. Low-res means there’s less work so the computation runs faster, but most importantly: we’ll have a larger receptive field. Why does this matter? You can easily image what an up-scaled version of a tiny photograph of someone’s face looks like because you know what faces look like. You know that that dark thing is an eye, and that dark region is a shadow cast by their jaw. You know all that to start with because you’re able to look at the entire photo in one pass and recognize it as a face and not a dinner plate or abstract-art piece. The GAN has to do the same thing.</p><p>There a few things that determine a receptive field: convolutional-layer depth, filter size, and down-sampling (non-unit stride, Max-Pooling, etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WFhZUpQth9SR-KLK_b0Jw.png" /><figcaption>hopefully this makes some amount of sense</figcaption></figure><p>Back to the code. The ResNet blocks are defined thusly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*I7H9GGWA3OmgmsbZgQPmyQ.png" /><figcaption>ip: input; nf: num. filters</figcaption></figure><p>This block takes an input, uses it to build up two Convolutional blocks (via <a href="https://keras.io/getting-started/functional-api-guide/">Keras’ functional API</a>), then adds the result of those Conv blocks back onto the original input: return merge([x, ip], mode=&#39;sum&#39;) The final Conv block has no activation (act=False) due to a recent paper (not sure which one) finding ResNet blocks generally perform better without.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlbNIotYehatxsG-a9MVug.png" /><figcaption>1st conv_block has ReLU activation; 2nd block no activ. ip is input. merge using sum operation.</figcaption></figure><p>From what I understand so far on <a href="https://youtu.be/UlnYEWXoxOY?t=600">Deep Residual Networks</a>, ResNet’s strength is it gives each layer of the network some context about the original input. In the lecture, <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a> says that a stack of ResNet blocks can hone in whatever it is they need to do to accomplish a task (here: upscaling an image).</p><p>y = f(x) + x; → f(x) = y — x; where y — x = the residual</p><p>So if the function is the difference between the output y and input x ,— the residual — and that gives some contextual information about how to minimize the loss function? I’ll have to learn more about that in time.</p><p>The conv_block is fairly standard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*ogsVWV1MWXNvmqQyG1-pQw.png" /><figcaption>a convolution, then batch-normalization, and optionally an activation</figcaption></figure><p>At this point we need to actually change the dimensions of the image. The original lecture used Deconvolution blocks which performed a <a href="https://youtu.be/I-P363wSv0Q?t=3154">de/transposed/fractionally — strided — convolution</a> to recreate what an image would have looked like if it’s present version (input) was the result of convolutions. Simply put: it’s a convolution on a (zero) — padded input. If you want to dive in further, <a href="http://deeplearning.net/software/theano_versions/dev/tutorial/conv_arithmetic.html">this is the link</a> referenced in the lecture. In the course’s github repository, the current version of the lesson’s notebook, <a href="https://github.com/fastai/courses/blob/master/deeplearning2/neural-style.ipynb">neural-style.ipynb</a> as well as <a href="https://github.com/fastai/courses/blob/master/deeplearning2/neural-sr.ipynb">neural-sr.ipynb</a> both use an up_block(..) defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*KIVtvq-zGbbk8fcfS4A7Sg.png" /></figure><p>So if I understand correctly this is a bit of a logical evolution of the course’s code. An issue with Transposed/Fract-Strided/Deconvolutions is checkerboarding: you get artifacts in a checkerboard pattern where the convolutional filters overlap, depending on stride-length. There’s a <a href="https://distill.pub/2016/deconv-checkerboard/">great paper on this</a> written by a few researchers at Google Brain and Université de Montréal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*kcGviYL1piLtunQlWVPnhA.png" /><figcaption>Figure from Odena, et al., “Deconvolution and Checkerboard Artifacts”, Distill, 2016. <a href="http://doi.org/10.23915/distill.00003">http://doi.org/10.23915/distill.00003</a></figcaption></figure><p>Simply put: a stride of 2 — stride=(2,2) — means the filter moves in steps of 2 pixels or cells as it scans across the input, and size=3 means the filter is a 3x3 square. Take a look at the figure above and the problem becomes obvious. One way to correct this is make sure your filter size is a multiple of your stride. The other method is to <em>not</em> use Deconvolutions at all.</p><p>The paper instead suggests first doing an Upsampling, which is essentially the opposite of a Max-Pooling operation: so for example every single pixel becomes a 2x2 grid of that same pixel. Doing an upsampling followed by a regular convolution results in no checkerboarding. And low-and-behold: that looks like exactly what <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a> has done in the newer version of the code. Cool.</p><p>So to drill into this a bit more: the original code used two Deconv blocks to enlarge the lo-res image from 72x72 → 144x144 → 288x288. The newer code accomplishes this with two Upsampling blocks which each do a single Upsampling2D() operation followed by a convolution and a batch-normalization. The <a href="https://keras.io/layers/convolutional/#upsampling2d">Keras documentation</a> for UpSampling2D() shows:</p><p>keras.layers.convolutional.UpSampling2D(size=(2,2), data_format=None)</p><p>The important part for us is the size parameter:</p><blockquote><strong>size</strong>: int, or tuple of 2 integers. The upsampling factors for rows and columns.</blockquote><p>So the default behavior is to just double the size of the image, which is why two empty calls to UpSampling2D() accomplishes the desired effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*uSE1Bie8xKnYBeU1ZQlI5g.png" /><figcaption>Just a reminder for what’s going on: the super-resolution network we’re building. inp is the original LoRes input tensor. outp is the HiRes output tensor. The Upsampling Network.</figcaption></figure><p>After the upscaling, we have a final 9x9 Convolutional layer in order to get back to 3 color channels. The explanation in lecture is that in going from 64 filters or channels down to 3 for the image output, we want a lot of context (hence the 9x9) to be able to do that. So putting the previous (288, 288, 64) tensor through the final Convolutional layer outputs a (288, 288, 3) tensor: an image. The final outp = Lambda(lambda x: (x+1) * 127.5)(x) line has to do with getting each pixel into its correct 0,255 color intensity rating from the previous tanh activation. Tanh is in the range 0±1 I think, so → ([-1:+1] + 1) * 127.5 = [0:255] . The Lambda(..) is a Keras wrapper that treats everything inside as a custom layer. <em>Note</em>: one of the <a href="https://arxiv.org/abs/1603.08155">Perceptual Loss paper’s</a> authors mentioned on reddit that they ran the network without a tanh activation and without the final Lambda processing layer and got as good or better results (no link).</p><p>The network can now be trained, but we still need to define our loss function. Ie: what’s the metric by which the network is gauging itself? We’ll first take our Upsampling Network and attach it to VGG. VGG will only be used as a loss function for Content Loss. Before outp the Upsamling Network’s output tensor can be put into VGG, it needs to be preprocessed (the normalization used in the VGG model). We do this by defining a custom Keras preprocessing layer, and defining a new output tensor outp_λ as the result of running outp through the preprocessing layer:</p><pre>vgg_λ = Lambda(preproc)<br>outp_λ = vgg_λ(outp)<br># I just discovered code blocks in Medium :D (```)</pre><p>Next we create a VGG16 network, and set all of its layers to untrainable. This is…kind of important. Because this network <em>is</em> our loss function — our measuring stick — it has to be static. Imagine if the kilogram or meter changed. If you want to see live chaos, just take a look at FOREX markets.</p><pre>shp = arr_hr.shape[1:]</pre><pre>vgg_inp = Input(shp)<br>vgg     = VGG16(include_top=False, input_tensor=vgg_λ(vgg_inp))<br>for λ in vgg.layers: λ.trainable=False</pre><p>The input tensor shape shp for the VGG network is the HiRes image dimensions. Hence: shp = arr_hr.shape[1:] and vgg_inp = Input(shp). arr_hr is a NumPy array created from a bcolz compressed array on disk, and its dimensions (shape) are: (num-elements, dim1, dim2, dim3, …). In our case it’s: (no. images, height, width, color-channels). So taking arr_hr.shape[1:] will return a tensor of shape: (288, 288 , 3). include_top=False for VGG16(..) will omit the Fully-Connected classification block at the end of the network. This is the fast.ai implentation of VGG16 w/ Average-Pooling &amp; Batch Normalization found at: <a href="https://github.com/fastai/courses/blob/master/deeplearning2/vgg16_avg.py">vgg16_avg.py</a> (links may break if course directory structure changes).</p><p>For getting the part/s of the VGG network we want for Content Loss, there’re a couple implementations. The original class lecture created a single model by choosing a single block at which to extract features (specifically conv layer 2 in block 2). In the course repository this has evolved into a function to retrieve features from multiple blocks.</p><p>The lecture’s implementation:</p><pre>vgg_content = Model(vgg_inp, vgg.get_layer(&#39;block2_conv2&#39;).output)<br>vgg1 = vgg_content(vgg_inp)<br>vgg2 = vgg_content(outp_λ)</pre><p>The updated course repo’s implementation in <a href="https://github.com/fastai/courses/blob/master/deeplearning2/neural-sr.ipynb">neural-sr.ipynb</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*Iy6aiK5day2LZOjgbo6ZyQ.png" /><figcaption>note how similar the 1 &amp; l look. Wait, in this font which is an I and which is an l? → Making my case for the λ. =) vgg_content here is a <a href="https://keras.io/getting-started/functional-api-guide/#multi-input-and-multi-output-models">Multi-Output model</a> (covered in Deep Learning I)</figcaption></figure><p>In either case, we use relatively early activations from the model. In L8 we found we could totally reconstruct an image using early layer activations. We then create two versions of VGG’s output using <a href="https://keras.io/getting-started/functional-api-guide/">Keras’ functional API</a>. A great thing about this Keras API is any layer (and models are treated as layers) can be treated as if it were a function. We can then pass into that ‘function’ any tensor we like, and Keras will create a new model where those two pieces are joined together. So vgg2 is outp, the UpSampling network on bottom, and vgg_content, the part of VGG16 we want to use as our loss function, on top.</p><p>Aside: you may be a bit confused here. Shouldn’t I’ve said outp_λ and not outp? Well, it is outp_λ in the lecture’s code: that’s the output tensor after going through a preprocessing Lambda layer. However that step is subsumed into the initialization call for the VGG16 model in the updated course code. The new call is:</p><pre>vgg = VGG16(include_top=False, input_tensor=Lambda(preproc)(vgg_inp))</pre><p>So now we have two versions of VGG layer output. vgg1 is based on the HiRes input, and vgg2 based on the output of the UpScaling Network (which took the LoRes input). We’re going to be comparing the HiRes target image and the HiRes upsamled result, so both tensors have the hi-res shape (288, 288, 3). Just to be clear: vgg1 is the HiRes content/perceptual activations, and vgg2 is the LoRes upsampled content/perceptual activations.</p><p><em>Note: There are significant differences between the original lecture and updated repository code for the definition of the loss function and final model. I’ll go through the lecture version first, then walk through what’s new.</em></p><p>Next we take the mean squared error between them. Any time you want to put something into a network in Keras, you need to turn it into a layer, and that’s done by throwing it into a Lambda(..):</p><pre>loss = Lambda(lambda x: K.sqrt(K.mean((x[0]-x[1])**2, (1,2))))([vgg1, vgg2])</pre><p>The final model will take the LoRes input and HiRes input as its two inputs, and return the loss function just defined as its output:</p><pre>m_final = Model([inp, vgg_inp], loss)</pre><p>Also, when you’re trying to fit things in Keras, it assumes you’re trying to take some output and make it close to a target. Here the loss is the actual loss function we want; there is no target, we just want it as small as possible. Since our loss function is using <a href="https://en.wikipedia.org/wiki/Mean_squared_error">MSE</a>, we can just say our target is zero. However, the targets in Keras are labels, so there has to be one for every row (every input), so we need an array of zeros:</p><pre>targ = np.zeros((arr_hr.shape[0], 128))</pre><p>Why 128 zeros for each image? [<a href="https://youtu.be/I-P363wSv0Q?t=4298">Answered in Lecture</a>]: the Lambda layer, loss, corresponding to the target array has 128 filters. 128 because that layer is taking in both vgg1 and vgg2, both of which have 64 filters.</p><p>Next we compile the model using the Adam optimizer and MSE loss, and fit it:</p><pre>m_final.compile(&#39;adam&#39;, &#39;mse&#39;)<br>m_final.fit([arr_lr, arr_hr], targ, 8, 2, **pars)</pre><p><em>Note:</em> pars contains a couple parameter arguments defined thusly: pars = {&#39;verbose&#39;: 0, &#39;callbacks&#39;: [TQDMNotebookCallback(leave_inner=True)]} — this turns off verbosity, and uses <a href="https://pypi.python.org/pypi/tqdm">TQDM</a> for status reporting.</p><p>After the first training round the learning rate is eased a bit (called ‘Learning Rate Annealing’):</p><pre>K.set_value(m_final.optimizer.lr, 1e-4)<br>m_final.fit([arr_lr, arr_hr], targ, 16, 2, **pars)</pre><p>After training, the part of our model we’re interested in is the Upsamling network. Once we’re done training &amp; trying to minimize the loss function, we no longer care about the loss: we care about the output images coming out of the Upsampling network. So now we define a model that takes in the LoRes input inp and returns a HiRes output outp:</p><pre>top_model = Model(inp, outp)</pre><p>This confused me a bit when I was first doing the assignment for it: outp has been trained during our training step above. In fact if you remember: inp and outp are just the input layer and output activations of our Upsampling network. We essentially built a machine to upsample images, used an existing module (VGG16) to train that machine by sticking it on top of it, then disconnectd that module when it was done, and now we have a trained machine that upscales images.</p><p><em>Now</em>, the way I did it, coming off of the way it’s done in the course repository is a little different. The section after defining vgg1 and vgg2 and before training looks like this:</p><pre>def mean_sqr_b(diff):<br>    dims = list(range(1, K.ndim(diff)))<br>    return K.expand_dims(K.sqrt(K.mean(diff**2, dims)), 0)</pre><pre>w = [0.1, 0.8, 0.1]</pre><pre>def content_fn(x):<br>    res = 0; n=len(w)<br>    for i in range(n): res += mean_sqr_b(x[i]-x[i+n]) * w[i]<br>    return res</pre><pre>m_sr = Model([inp, vgg_inp], Lambda(content_fn)(vgg1+vgg2)<br>m_sr.compile(&#39;adam&#39;, &#39;mae&#39;)</pre><p>Remember how the newer code used a multi-output model taking activations at different blocks in VGG16? Well we’re going to weight the relative influence of each block to our loss function: w = [0.1, 0.8, 0.1] means block1_conv2 is weighted at 10%, block_2_conv2 at 80%, &amp; etc.</p><p>Our loss function itself is a function within a function. content_fn(x) takes a tensor x, and outputs a scalar loss value res. For each weight in w, content_fn(.) calls mean_sqr_b(.) on the difference between the ith element of x and the ith + n element on x (where n = the number of weights in w), multiplies that result by the ith weight in w, and adds that value to res.</p><p>If you think of that x going into content_fn(.) as the concatenation of our HiRes tensor and our LoRes Upsampled tensor, and if both those tensors are the result of a multi-output model (the 3 different conv_block activations), then all content_fn(.) is doing is the <a href="https://en.wikipedia.org/wiki/Mean_squared_error">MSE</a> of the corresponding weighted block activations of the two tensors.</p><p>If that’s still a bit dense, try this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlQuDLjhkFQdraZFTbpEQw.png" /><figcaption>yes I see it too.</figcaption></figure><p>I’m going to pause a moment here and hope I didn’t make it worse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*swwHhvAesaCK87XcStr2Pg.png" /><figcaption>Terek</figcaption></figure><p>Right. So that’s the loss function.</p><p>The final model, this time called m_sr for super-resolution model, takes as input an array of tensors: LoRes and HiRes originals, and outputs the result of the loss function content_fn applied to vgg1 + vgg2.</p><pre>m_sr = Model([inp, vgg_inp], Lambda(content_fn)(vgg1+vgg2)</pre><p>Just visualizing this is a mild nightmare: imagining the multiple computation graphs that differ only in which block of VGG they take as output, how their outputs get woven together into the loss function; and that’s not even thinking about what’s going on inside each Upsampling network, or how backpropagation is actually updating the network. It’s cool that this can be abstracted away into just a few lines of code. I thought about drawing up one massive diagram … past a certain point it’s the Illuminati meets the Matrix and you’re in a race to figure out the plot.</p><p>Compilation is straightforward, although <a href="https://www.kaggle.com/wiki/MeanAbsoluteError">Mean Absolute Error</a> is used instead of <a href="https://en.wikipedia.org/wiki/Mean_squared_error">MSE</a>: m_sr.compile(&#39;adam&#39;, &#39;mae&#39;). The other difference is training. Loading ~40k images <em>just</em> barely fits into memory on my workstation, <em>sometimes</em>. What if you want more? That’s where the bcolz library comes in. You keep the data on disk and load it in batches. The code for that goes something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*HQALi9NKWvhXxn2mVrAE4A.png" /><figcaption>see: <a href="https://github.com/fastai/courses/blob/master/deeplearning2/bcolz_array_iterator.py">bcolz_array_iterator.py</a></figcaption></figure><p>bs is batch size. It must be a multiple of chunklen the chunk length of the bcolz carray, defined at compression time. I had an issue with the bcolz arrays having a chunk length of 64, whereas my workstation could only handle a batch size of 6; 8 if the planets aligned. I solved this by creating new arrays with the chunklen parameter explicitly set. This may or may not have been kosher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*D6EI5VI_3ZIOlYTLRDi0lg.png" /><figcaption><a href="https://github.com/WNoxchi/Kaukasos/blob/master/FAI02/Lesson9/neural_sr_attempt3.ipynb">neural_sr_attempt3.ipynb</a></figcaption></figure><p>niter is number of iterations. targ is the target vector just like before, but this time it’s an array of zeros, one for each element in the batch. bc is an iterator that returns the next batch of in this case arr_hr and arr_lr on each call to next(bc). I really like this because I had a system memory limit issue for one of the <a href="http://course.fast.ai/">Deep Learning I</a> assignments, and I hacked together similar-in-spirit bunch of functions to pull data from disk in batches and handle the final remainder batch correctly. <a href="https://github.com/fastai/courses/blob/master/deeplearning2/bcolz_array_iterator.py">The code</a> is quite a bit more advanced though and it’ll be interesting to pick it apart &amp; see how it works. It uses threading and with statements, which aren’t things I’ve had to use yet.</p><p>For niter iterations, train(..) loads the next batch of HiRes and LoRes images and then calls m_sr.train_on_batch([lr[:bs], hr[:bs]], targ). Why exactly is it lr[:bs] and not just lr when lr is length bs anyway, I’m not sure — maybe it isn’t? I’ve had issues with input and target arrays not matching up in length in the final batch. If you have 16,007 images and a batch size of 8, your target array size is set to the batch size → you get an off-by-one error. I solved this by specifying the target to be targ[:len(hr)] so the final input and target arrays are the same length. As for niter I set it to be: niter = len(arr_hr)//6 + 1 to account for the remainder, though in retrospect adding 1 only if a remainder existed would’ve been better.</p><p>After all that, the end is easy. Train for a couple epochs, ease the learning rate, then train a couple more. Then get your trained working model:</p><pre>top_model = Model(inp, outp)</pre><p>and start upsampling things. I got this (<em>Note</em>: the data here was all loaded into memory at once, and the model trained via model.fit(..)):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*ze1uXOwSvrFHIfcg3-M2-g.png" /><figcaption>it enhanced the mashed potatoes</figcaption></figure><p>Although as the course notebook hinted, this good performance may be in part to overfitting. Here are results with a photo of Jupiter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*AoUdv9HPTGtvzSdS1UtMMA.png" /><figcaption>LoRes — SuperRes — HiRes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*2nbN0uaThCR9_hPO0woG3w.png" /><figcaption>LoRes — SuperRes — HiRes (used batch-loading method)</figcaption></figure><p>This isn’t too surprising. First, I definitely forgot the learning rate annealing part in at least one implementation — was more interested in getting it to work: lots of resource exhaustion errors and troubleshooting the bcolz iterator — and the dataset I was working with only had 19,439 images. Maybe this should be more than enough, but if In: len(arr_hr)//16; Out: 62277 is anything to go by, the model in the course was training on at least 996,432 images, though that may be after the lecture was recorded. Whatever the case, you’d ideally train on all of ImageNet and not a small subset if you had any say in the matter anyway. And you’d ideally get the training regimen right as well. My two successful attempts took a combined compute time of around 12 hours, by the way. So 20k was just fine.</p><p>A note about Jupiter and overfitting: there does seem to be an issue with increased contrast and washing out color in all the pictures, but there also isn’t a planets category in ImageNet — as far as I could find. So there may be something going on there.</p><p>3. Fast Style Transfer. We can use the same basic idea from super-resolution for doing fast style transfer using perceptual (content) losses. This time we take a photo, put it through a CNN, then put that through a loss function doing style and content loss against a single fixed style image. There’s a <a href="https://arxiv.org/abs/1603.08155">paper</a> along with <a href="http://cs.stanford.edu/people/jcjohns/papers/eccv16/JohnsonECCV16Supplementary.pdf">supplementary material</a> on this topic.</p><p>The <a href="https://arxiv.org/abs/1603.08155">paper</a> uses reflection padding instead of zero padding on the input — that is: reflecting the image around borders instead of just having black pixels. <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a> implements this with a custom layer which in Keras is done as a Python class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*d5mTnbU3rN4ogI2836WVvw.png" /><figcaption><a href="https://github.com/fastai/courses/blob/master/deeplearning2/neural-style.ipynb">neural-style.ipnb</a></figcaption></figure><p>The first section is the constructor. After that are two things that need to be done whenever a custom Keras layer is being defined: you need to define get_output_shape_for(self, input) which takes in the input tensor’s shape, and returns the shape of the output tensor — in this case it’s the same batch size as s (s[0]), the same number of channels (s[3]), and twice the amount of padding for the rows and columns: (s[1] + 2 * self.padding[0], s[2] + 2 * self.padding[1],). Keras ‘magically’ knows how big the input/output of intermediary layers are when you put things together because every layer contains this kind of information. The second thing to define is call(self, x, mask=None). call(..) gets your layer data x, and returns whatever it is your layer does. <a href="https://keras.io/layers/writing-your-own-keras-layers/">Keras’ documentation states</a>:</p><blockquote>call(x): this is where the layer&#39;s logic lives.</blockquote><p>We want this layer to add reflection padding. TensorFlow has a built-in function for that called tf.pad(..).</p><p>That layer can now be used in a network definition:</p><pre>inp = Input((288, 288, 3))<br>ref_model = Model(inp, ReflectionPadding2D((40, 2))(inp)<br>ref_model.compile(&#39;adam&#39;, &#39;mse&#39;)</pre><pre>p = ref_model.predict(arr_hr[10:11]) # run model on 10th img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*xLGdGRKLNHhE0X3THplq1w.png" /><figcaption><a href="https://github.com/fastai/courses/blob/master/deeplearning2/neural-style.ipynb">neural-style.ipynb</a></figcaption></figure><p>The paper authors use 40x40 pixel reflection padding to the images. Since they use ‘valid’ convolutions in their ResNet blocks, the image is progressively cropped down through layers, so the reflection padding exists to preserve the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*3XM_aR3IwMbpCeo-5O27MA.png" /><figcaption>From: <a href="http://cs.stanford.edu/people/jcjohns/papers/eccv16/JohnsonECCV16Supplementary.pdf">Perceptual Loss Supplementary Material</a></figcaption></figure><p>In fact, the authors’ architecture is very similar to ours. The general pattern is: downsample the input via convolutions and increase the number of channels and receptive field thereby creating more complex representations of the data (lines 3–5), do computations on those representations (Residual layers), then upsample it (last 3 lines). The 1/2 stride is a Deconvolution: it’s the same as a Fractionally-Strided Convolution.</p><p>Without going into too much detail, implementing this (mainly following along from the updated course notebook) I took this style image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oK8NHIPD9HPmRzeRSNCpQ.png" /><figcaption>artist: <a href="https://www.artstation.com/aenamiart">Alena Aenami</a></figcaption></figure><p>And applied it to this picture of a Waynakh medieval tower:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*c4_-aJOOO71NgLvYlS3fww.png" /><figcaption>image: Ahmed Osmiev</figcaption></figure><p>Both images were resized to 500x500 . Looking back at the code I’m seeing some silly mistakes: The style image was cropped to 288x288 to fit the style tensor… so that threw away 33% of the style image. After resizing the content image of the tower to333x333 … that wasn’t going to fit, so I just cropped it to fit the input tensor. Still, after training the fast style transfer model for around 6 hours in 4 epochs with learning rate annealing (2 ep @ default → 2 ep @ 0.0001) the model did its style transfer in maybe a second or less and produced this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*EU4HcTIs5WxoI7wbLR2WOA.png" /><figcaption>resized in Apple Pages to (kind of) match original proportions</figcaption></figure><p>It kind of looks like a card for a role-playing game. A haunted castle or something. Obviously it’d be a lot better if I used the full resolution of the original content &amp; style images, but I haven’t looked into it yet. Since this model does its training first and not at run-time like the previous style-transfer model… it feels like it’ll be tricky getting it to work for large images w/ limited compute resources. You could try the simple extreme case of re-compressing the bcolz arrays to have a chunk length of 1 so you can use a batch size of 1, start with a much lower learning rate, just accept the longer training time and go from there…but that feels <em>too</em> simple of a solution. There ought to be a way to scale to any image size and only pay a cost in computing time, given fixed resources. <em>Hmm..</em></p><p>You could try breaking the image into a grid-mosaic, run on each piece, and stitch them back together. But now you pay a qualitative cost: If it’s a HiRes picture of a face, then there’s important information your network won’t be privy to because it’ll in effect be too zoomed in to see the forest for the trees.</p><p>Wait is there a way to use the 288x288x3 tensor as a field of view, and scan that over a larger image, loading what’s in view into memory and keeping the rest on disk maybe with bcolz? <em>Hmm..</em></p><p>4. <a href="https://research.google.com/pubs/pub41869.html">DeVISE</a>: Deep Visual-Semantic Embedding Model. The last part of lecture 9, and this odyssey of a blog post is DeVISE. Described <a href="https://research.google.com/pubs/pub41869.html">in a paper by Andrea Frome</a> (et al?), DeVISE seeks to take a step closer to what we do for image recognition by replacing one-hot encodings with word embeddings.</p><p>As a (very) rough overview: in your traditional one-hot encoded model, there’s little similarity between a shark and a fish, or any notion of the concept of ‘shark’ which is a superset of all types of sharks. Of course that’s not how we perceive things in real life. In a different domain, natural language processing, there’s a method for capturing the interrelatedness of categories called a word embedding. It’s basically a matrix where each row (column??) consists of a vector mapping a word’s relatedness to all other words. We used this in <a href="http://course.fast.ai/lessons/lesson4.html">Deep Learning I</a> to create a sort-of Nietzsche bot and also for movie recommendations (the embeddings can map movies to categories, not just words to words).</p><p>So for images, instead of having a 1000 element vector for a pug, with a 1 at the index for the pug category and zeros everywhere else, and replace it with a dense word vector for a pug (vector length depends on the embedding we’re using). We’d use a Softmax layer to do the one-hot encoding (answer is 1 all else are 0), but now we’ll use linear layer.</p><p>The tricky thing about this is going through ImageNet. 1.5 million-ish images is a lot. And that’s where bcolz and the array iterator (used earlier here) come in.</p><p>A tip here from <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a>: he defines two data paths — one for data living on fast SSDs/NVMes, and another for large HDDs. He used a RAID 1 SSD to quickly access resized images and feature arrays, and the HDD path for bulk data. Good idea.</p><p>The word embedding used is word2vec.</p><p>Another interesting thing mentioned <a href="https://youtu.be/I-P363wSv0Q?t=6172">in the lecture</a> is Python’s single-star (zip-star?) syntax. If you have a data structure that maps words to vectors and want to get a list of the words and a list of the vectors, if you can get that data structure as an iterator then:</p><pre>words, vectors = zip(*wordvec_iterator)</pre><p>will place all the words into words and all the corresponding vectors into vectors.</p><p>So in the lecture’s example, if wordvec_iterator contains &quot;fox:&quot;, array01, &quot;wolf&quot;, array02, ... then when you zip-star wordvec_iterator it’s the same as putting those contents into a zip(.) like so:</p><pre>zip(&quot;fox&quot;, array01, &quot;wolf&quot;, array02)</pre><p>So then testing this out:</p><pre>&gt;&gt;&gt; words = [&quot;fox:&quot;,&quot;wolf:&quot;]; vecs = [[1,2,3],[4,5,6]]; <br>&gt;&gt;&gt; zipped = zip(words, vecs)<br>&gt;&gt;&gt; list(zipped)</pre><pre>Out: [(&#39;fox:&#39;, [1,2,3]), (&#39;wolf&#39;, [4,5,6])]</pre><pre>&gt;&gt;&gt; w, v = zip(*zip(words, vecs)) # or: zip(*zipped) ## for fresh `zipped`<br>&gt;&gt;&gt; words == list(w) and vecs == list(v)</pre><pre>Out: True</pre><pre>&gt;&gt;&gt; w, v</pre><pre>Out: ((&#39;fox:&#39;, &#39;wolf:&#39;), ([1,2,3], [4,5,6]))</pre><p>Or to be pedantic:</p><pre>&gt;&gt;&gt; word, vecs</pre><pre>Out: ([&#39;fox:&#39;, &#39;wolf:&#39;], [[1, 2, 3], [4, 5, 6]])</pre><pre>&gt;&gt;&gt; list(w), list(v)</pre><pre>Out: ([&#39;fox:&#39;, &#39;wolf:&#39;], [[1, 2, 3], [4, 5, 6]])</pre><p>So I learned something new today. Basic lesson: if you want to turn a list of tuples into a tuple of lists, use zip-star (Python).</p><p><a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a> does more setting up the notebook for applying word embeddings to ImageNet pictures. I won’t go into detail here since this post has suffered it’s own form of mission-creep — and I also haven’t made the TB or so of free space for an full unzipped ImageNet yet. Howard does some processing on the word lists, reordering them so more common words are towards the front — and also putting all words into lower case since capitalization doesn’t matter here. He does a couple sanity checks by using np.corrcoef(..) to see the correlation coefficients between the upper and lower case versions of his name vs his name and unrelated objects.</p><p>He then creates two maps (Python dictionaries) of word vectors to the 1,000 ImageNet categories, and to the 82,000 nouns in WordNet — with the goal of creating a system that can go beyond Imagenet’s 1,000 categories.</p><p>Finally he created a list of the ImageNet categories not found in WordNet, and just moved those image folders out of the directory.</p><p>Another useful tip: Howard saves the output of everything that takes a non-trivial amount of time. Getting the filenames of a million images takes a while, especially if they’re on spinning disks.</p><p>He also takes advantage of a trio of techniques I’m seeing in the <a href="https://github.com/fastai/numerical-linear-algebra/blob/master/README.md">Computational/Numerical Linear Algebra</a> class as well: Memory Locality, SIMD/Vectorization, and Parallel Processing. [<a href="https://youtu.be/I-P363wSv0Q?t=6729">Lecture segment</a>]. I found the bit on SIMD very interesting.</p><p>So that wraps up what has by far been the longest lesson for me in the course. There’s a lot going on, but I love the idea of looking at the code in terms of its large-scale architecture. It’s extremely easy to get lost in a dark forest and forget where a slice of your model comes from. It’s also easy to dread making any changes for fear of never being able to understand it all again. But if you have the running theme of “I’m putting input image through a CNN, and that CNN’s output is being compared to what I want it to produce via a loss function” it becomes a lot easier to keep in mind what you’re actually doing. And that about wraps it up!</p><p>A couple notes on notation: I’ll often capitalize certain terms like Convolutional or Generative and etc. I’ve found it helps when reading new technical topics to have some of the key terms emphasized just enough to act like path markers, to avoid just reading through a wall of text like prose and getting lost.</p><p>Also, whenever there’s a stray l somewhere on its own in code, I’ll replace it with λ. Besides λ being pretty, in many fonts 1 I l look identical or near enough to be confusing; so it has an added use of sanity-preservation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcd599ad6e0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-learning-ii-l9-generative-models-dcd599ad6e0b">Deep Learning II L9: Generative Models</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FADL2 L8: ‘Neural’ Artistic Style Transfer]]></title>
            <link>https://medium.com/data-science/fadl2-l8-neural-artistic-style-transfer-a2e6780ab17b?source=rss-febe20a208a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e6780ab17b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <dc:creator><![CDATA[Wayne Polatkan]]></dc:creator>
            <pubDate>Fri, 28 Jul 2017 02:21:37 GMT</pubDate>
            <atom:updated>2017-07-28T04:23:12.622Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently finished Lesson 8 of <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a>’s <a href="http://course.fast.ai/">Practical Deep Learning</a>, (part 2 in beta). Here I’m going to go through a bit of the work and results from recreating the lesson’s Jupyter Notebook. &lt;<em>this is </em><strong><em>very</em></strong><em> rough</em>&gt;</p><p>[<em>NOTE: think part 2’s been renamed to ‘Cutting Edge Deep Learning’ — should be launched publicly soon. Also </em><strong><em>tl;dr: </em></strong><em>scroll to bottom for videos</em>]</p><p>My rendition of the notebook can be followed along here: <a href="https://github.com/WNoxchi/Kaukasos/blob/master/FAI02/L8_NeuralArtTrsfr_CodeAlong.ipynb">https://github.com/WNoxchi/Kaukasos/blob/master/FAI02/L8_NeuralArtTrsfr_CodeAlong.ipynb</a></p><p>After reviewing the library imports and the need to specify limit_mem() so TensorFlow doesn’t eat everything your GPU has to offer, I had to learn what ‘pickling’ was in Python. Turns out, courtesy of <a href="https://www.youtube.com/watch?v=2Tw39kZIbhs">sentdex</a> on YouTube, it’s just serialization in Python. What serialization? Obviously it’s sending a stream of one thing after another… apparently it’s useful when you’re doing a lot of disk accessing (like reading data for ML), although it provides no security, so beware for network streams.</p><p>I experimented by writing a mini dictionary of Latin:Mxedruli letters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*GxZS5EliEkCME3iOKNAyrw.png" /><figcaption>Learning to Pickle in Python (data serialization)</figcaption></figure><p>So that’s that. I haven’t looked at sentdex’s newer ‘<a href="https://www.youtube.com/watch?v=za5s7RB_VLw">Pickling and Scaling — Practical Machine Learning with Python p.6</a>’ video, but I may if I feel I need to.</p><p>1.CONTENT RECONSTRUCTION</p><p><strong>Neural Style Transfer</strong></p><p>NST is creating a new image that retains the ‘style’ of one image, and the form of another. So for example creating a picture of a cat painted in Vincent van Gogh’s style by using two input pictures: that of a cat, and another representing van Gogh’s painting style.</p><p>A few things are important here. The algorithm isn’t applying van Gogh’s style to the cat image itself: it’s starting with a fresh image (like a random bunch of pixels) and building it into the desired composite.</p><p>It’s going to need a model that’s already good/-enough at discerning features of both input images. So, “where are the eyes”, “this is a face”, “this brush-stroke is a thing”, etc.</p><p>First step is initializing the model (here a modified VGG16 CNN using Average Pooling and minus the top block of FC layers):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*QACFDXrfK6JFkZeGwk38_A.png" /><figcaption>instantiating a VGG16 model using Average-Pooling instead of Max, and excluding the end-block of Fully-Connected layers (we want convolutional features, not classification here)</figcaption></figure><p>Next we define a computation graph in Keras. A computation graph, as I understand it so far, is defining a series of operations on data stand-ins. No data’s been passed in yet, but when it is, the program will know what to do. We do this to define the target image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*Wx-7LXDKwBg7LHcP_fBL5Q.png" /><figcaption>`targ` isn’t any ‘thing’ yet, but more of an operational placeholder for when this bit of computation occurs.</figcaption></figure><p>As you can see, targ is the output (prediction) of the layer_model on the img_arr. layer_model is a Model ( keras.models.Model : <a href="https://keras.io/models/model/">Keras Functional API</a> ) made up of the layers of model from it’s input to layer, which we define to be the 1st Convolutional layer of the 5th Conv-Block of the VGG16 model. img_arr is the original image which has been preprocessed the same way the VGG authors preprocessed their ImageNet data in training their model.</p><p><strong>NOTE</strong>: layer is the output-activations from the end of our convolutional submodel. layer_model is the submodel defined from the beginning of the original model to layer. targ is the target-activations. The loss-function attempts to bring layer and targ as close together as possible.</p><p>That wording can be confusing, but it makes more sense when you go through it in code. We define several such graphs using Keras throughout this notebook.</p><p>In order for the algorithm to gauge how well it’s doing it needs to quantize it’s progress somehow: a Loss / Objective Function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45qOde7e4MQd17VI6Bb_RA.png" /></figure><p>To do this, we define the loss as being the <a href="https://en.wikipedia.org/wiki/Mean_squared_error">Mean-Squared Error</a> between the output layer and the target image.</p><p>evaluator is a custom-defined Evaluator class that allows the program to access the loss function and gradients separately, since Keras returns them together but the optimizer needs to see them separately.</p><p>This evaluator, along with the number of iteraions, and the random-image x, go into solve_image(•), which does the job of optimizing the loss.</p><p>All this is to recreate an image from an original by applying its conv-features to a randomly-generated image and updating the loss function.</p><p>The basic idea is: we run the original and a new random image through the submodel, and use our loss function to determine how close of a match they are. We use the <a href="https://en.wikipedia.org/wiki/Line_search">Line-Search</a> algorithm from scipy.optimize.fmin_l_bgfs_b as the optimizer to minimize the loss. When we next work on incorporating style from a style-image, we’ll be using weights to balance how much we want to focus on recreating the original image, vs applying the style of style image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*GgYFuqgUnPHHryFhR7bNtg.png" /><figcaption>`loss` is the sum of `style_loss`-es for all layers &amp; targets. `style_loss` is the mean-squared-error between the gramian matrix of the layer, and the gramian matrix of the target. The Gram Matrix is the dot-product of a matrix with its own transpose. ~ I think I remember in lecture, Howard saying no one really knows why it works … but it works.</figcaption></figure><p>So what we eventually get, using my cat Terek as the original image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlSgYwk26nsVLOweySGv9w.png" /><figcaption>Terek.</figcaption></figure><p>And generating an image of random pixels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*4JEqYETfldOxnhRg9qbchA.png" /></figure><p>And putting that through solve_image(•) for 10 iterations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*xwS1bX-0M8FQfv0lkff1Cg.png" /></figure><p>We get this unGodly monstrosity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPGxSdKqqZNK1P2abw5LTA.png" /><figcaption>How cats actually see</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fm9Y8VYUiavk%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dm9Y8VYUiavk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fm9Y8VYUiavk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f6866e83ebb97186ed04a737d84f06e/href">https://medium.com/media/4f6866e83ebb97186ed04a737d84f06e/href</a></iframe><p>As bad as this may look, it’s actually really interesting. Remember this algorithm is taking a mosaic or random pixels and recreating a picture of a cat by feeding them through the CNN we defined above, and optimizing the weights &amp; activations of that network based on the mean-squared error between the new (target) image and the original’s activations in the network. What this means is that the target image will be constructed according to what features are expressed in the convolutional network. So the model has to actually be able to tell eyes apart from the background and so on. Lower convolutional blocks will give us finer features, and later ones will give us the more macro features in the model. So we can get an output that looks more like the original image by using earlier convolutional layers.</p><p>2. STYLE RECONSTRUCITON</p><p>For recreating style, we’ll have to do something more. We’re changing the loss function by calculating it for multiple layers. Quoting the original notebook:</p><blockquote>Whereas before we were calculating MSE of the raw convolutional outputs, here we transform them into the ‘Gramian Matrix’ of their channels (that is, the product of a matrix and its transpose) before taking their MSE. It’s unclear why this helps us achieve our goal, but it works. One thought is that the Gramian shows how our features at that convolutional layer correlate, and completely removes all location information. So matching the Gram Matrix of channels can only match some type of texture information, not location information.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*KGbq0qo19DlVGCTvPcbOlA.png" /><figcaption>style_arr is the preprocessed style image. shp is the shape of style_arr. Note the major difference from before being that we’re building arrays from layers. Specifically 3 layers: for the 3 color-channels.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*GgYFuqgUnPHHryFhR7bNtg.png" /><figcaption>`loss` is the sum of `style_loss`-es for all layers &amp; targets. `style_loss` is the mean-squared-error between the gramian matrix of the layer, and the gramian matrix of the target. The Gram Matrix is the dot-product of a matrix with its own transpose. ~ I think I remember in lecture, Howard saying no one really knows why it works … but it works.</figcaption></figure><p>Doing that, we can the style of this van Gogh painting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*VqpezuGAxHZSSatZBhMiag.png" /></figure><p>And apply that style to this randomly generated target image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*BlL8Y0UiMvjkHBKZtRvemw.png" /></figure><p>To get an image of random pixels, in van Gogh’s style after 10 iterations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*OhpwBZ9BLqjK7MgO75WeLg.png" /></figure><p>3. STYLE TRANSFER</p><p>And finally for Style Transfer. We got 1. Input Recreation. 2. Style Recreation. Now to put it together:</p><p>This is done in the (eventually) intuitive way: combine the two approaches by weighting and adding the two loss functions. As before, we grab a sequence of layer outputs to compute style loss. Only one layer output is needed to compute content loss. The lower the layer: the more exact content reconstruction. When we merge content reconstruction with style: the earlier-layer / looser reconstruction will allow more room for style, and vice versa.</p><p>Here we have code to make the style_layers be the 2nd convolutional layer of blocks 1 through 5; and the content_layer the outputs (activations) of block 4 conv-layer 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*cLAZyD4hhZJVICjes8yDKQ.png" /><figcaption>The style and content models become submodels of the full model’s input to the respective style and content outputs. NOTE: the style target outputs/activations correspond to their multiple layers. The style targets ultimate take in the style array (preprocessed style image) and likewise content target takes in the preprocessed source image (src).</figcaption></figure><p>This creates three separate output types: for original image, style-image, and the random image who’s pixels we’re training.</p><p>Finally an array of weights to apply to the style output activations is created. This tunes the mix at those layers of image-reconstruction vs. style-transfer. NOTE: this works by being a factor on content-loss. The smaller the factor (greater denominator) the greater effect style has on the final image, until it completely obscures any original content.</p><p>Gotta find that sweet spot between <em>all-style</em> and <em>all-business.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*SBMcM5Hj0i2iVotDbE9bVQ.png" /><figcaption>This does the thing</figcaption></figure><p>And here are some results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*1vzg9Nf_8a36ofwY6PL7Tw.png" /></figure><p>I accidentally got an impressionist painting of a power plug:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FF-hAH1wPfBU%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DF-hAH1wPfBU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FF-hAH1wPfBU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/53d23cc4ab2eac08991b02d06574b2d7/href">https://medium.com/media/53d23cc4ab2eac08991b02d06574b2d7/href</a></iframe><p>Convolutional Neural Networks need a fixed input size, so the content, style, and output images have to be of the same dimensions. So while getting a compatible cropping of my cat’s picture, I forgot to adjust it, getting the top-left corner, of the same dimensions as a tiny bird-painting I was using for style.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHryck3K3jek%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHryck3K3jek&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHryck3K3jek%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2a660fcc02213140a527937402ad6b5/href">https://medium.com/media/f2a660fcc02213140a527937402ad6b5/href</a></iframe><p>And finally, just making sure I was doing things right: seeing if I could get the same results on the same input images as <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJhGur68gwKI%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJhGur68gwKI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJhGur68gwKI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec33d436f6395541116e16a1a640596a/href">https://medium.com/media/ec33d436f6395541116e16a1a640596a/href</a></iframe><p>Definitely some differences, for sure similarities, I like this for a first run. I’m definitely excited about doing <em>good</em> style transfer like what you’ll find here: <a href="https://github.com/titu1994/Neural-Style-Transfer">https://github.com/titu1994/Neural-Style-Transfer</a></p><p>Luckily enough, it looks like techniques such as ‘masking’ and others are going to be covered in Lesson 9, so I may not even need to learn that on the side.</p><p>So, final note: this wasn’t a post for learning from scratch. For that: you’ll have to go through the lesson and original notebook. But if you’re working on this and wanted some extra thoughts, then hopefully this was helpful.</p><p>Another thing I love about AI are all the opportunities for sketchy-but-accurate folder names:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*0m1y6eejSjepXVcAZzgVcA.png" /></figure><p>A big thanks to <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a> and <a href="https://medium.com/u/ee56d0bac1b7">Rachel Thomas</a> for putting together fast.ai.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e6780ab17b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/fadl2-l8-neural-artistic-style-transfer-a2e6780ab17b">FADL2 L8: ‘Neural’ Artistic Style Transfer</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro — Starting AI w/ fast.ai]]></title>
            <link>https://medium.com/@nixalo/intro-starting-ai-w-fast-ai-238ed53818dc?source=rss-febe20a208a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/238ed53818dc</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Wayne Polatkan]]></dc:creator>
            <pubDate>Tue, 25 Jul 2017 17:24:12 GMT</pubDate>
            <atom:updated>2017-07-30T16:00:39.862Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a rough recap of my first 3 months learning AI— and taking too long to get a blog running on my <a href="http://wnoxchi.github.io/">WNoxchi.github.io</a>.</p><p>I found <a href="http://www.fast.ai/">www.fast.ai</a> in April 2017 and was a bit blown away. An AI course focused on actually getting things done? I was just finishing Yaser Abu-Mostafa’s CS1156x ‘<a href="https://www.edx.org/course/learning-data-introductory-machine-caltechx-cs1156x-0">Learning from Data</a>’ on edX, and while a great theoretical course, it did cut down a lot of my enthusiasm for Machine Learning. I guess learning to code in Python while writing Linear Regression models by hand has that effect.</p><p>What really got me about <a href="https://medium.com/u/34ab754f8c5e">Jeremy Howard</a>’s ‘Practical Deep Learning I’ (which I’ll call FAI01/FADL1) was that, over and over again, he’d explain a thing, you’d go do it, and all of a sudden you’re catapulted to the forefront of applied ML. As an example, the course started off with CNNs, Convolutional Neural Networks. They basically work by sliding a filter across the previous layer, looking for a particular pattern. They can also be difficult to train: they take a lot of computation time, and it’s hard to compete w/ a CNN trained on 1.5 million ImageNet images. So why reinvent the wheel? Find a strong-performing model that can be applied with good results to our problem (in our case, the <a href="https://github.com/fchollet/keras/blob/master/keras/applications/vgg16.py">VGG16 model</a> ~ which is essentially several blocks of convolutional layers and some dense/fully-connected layers at the end), chop off its last/output layer, stick a fresh one on, lock the convolutional layers as they are, and retrain the modified network on the problem at hand. This is called finetuning and transfer learning — and the VGG model works particularly well at this. In the initial assignment, doing this for Kaggle’s Dogs vs Cats Redux, this’ll easily get to the top 50% in rankings, top 25% if done well.</p><p>Now this is ignoring details such as ensuring proper color-channel order (the Oxford VGG authors used BGR instead of RGB) and normalizing the data by subtracting/dividing the mean &amp; standard deviation of the ImageNet dataset VGG16 was originally trained on… but these are details you generally hear Howard mention, nod your head going “ah..okay..”, and then really learn by seeing it in the code, rewriting it, and rationalizing backwards.</p><p>This crazy part about this is, once you do it, you begin to look around and notice who else is basically doing the same thing as you. For example, later in the course you learn about t-SNE and embeddings. t-SNE is basically a way to flatten any high-dimensional matrix into 2D so it can be roughly visualized (to see how parts of data are correlated), and embeddings are vectors containing how one thing (like a single customer) is related to everything else (all the products in a store). Low and behold, while I was taking FADL1, the VP of Data Science at Instacart, <a href="https://medium.com/u/eac4abbe4148">Jeremy Stanley</a>, wrote a Medium post, <a href="https://tech.instacart.com/deep-learning-with-emojis-not-math-660ba1ad6cdc">Deep Learning with Emojis (not Math)</a>, where he used the same tools and techniques that were being taught in the course to generate shopping recommendations.</p><p>I’ve also noticed people using VGG16 in the same way as the course, but in everything from academic papers to tutorials, and other places. One more example are Matthew Zeiler’s visualizations of convolutional features. You see them in the first few lectures of FADL1, but I’ve also seen them in <a href="https://youtu.be/6QewMQT4iMM?t=250">lecture 5</a> of MIT’s 6.s191 (Intro to Deep Learning), and in a lot of other places.</p><p>A take-away from all this is that the frontier is quite close, and there are a lot of low-hanging fruit in AI. I think also that a lot of people exploring this field are limited by 19th-century research methodologies, and others are intimidated into self-selecting out by general lack of confidence (“but everyone else is a PhD” — “who are you to think you can just <em>start</em> learning this stuff” — etc). So my little hypothesis is that, due to the above, a person willing to put in the work, and approach it with a bit of a cowboy-esque engineering attitude, is going to see a lot of rapid success.</p><p>Maybe. Maybe not. <em>Gur du way.</em> We’ll see.</p><p>Right, so I may/not expand this, but I wanted some kind of intro before I started writing about the technical stuff I’m learning in J.Howard’s Practical Deep Learning II, and R.Thomas’ Computational (Numerical?) Linear Algebra. Also pictures. So on a totally-not ominous note, a mental image/association that always has me excited about AI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHlzykVh1_xkh2Yk5YSFgA.jpeg" /></figure><p>Corrections:</p><p>&lt; edited up above in the 2nd paragraph &gt;</p><blockquote>VGG isn’t the state of the art for object detection. But it’s great for transfer learning</blockquote><p>— @jeremyphoward</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=238ed53818dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>