<?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 Doruk Kilitcioglu on Medium]]></title>
        <description><![CDATA[Stories by Doruk Kilitcioglu on Medium]]></description>
        <link>https://medium.com/@dklt?source=rss-4022d0823b33------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gni5LH87FRsXiuXTeus-lw.jpeg</url>
            <title>Stories by Doruk Kilitcioglu on Medium</title>
            <link>https://medium.com/@dklt?source=rss-4022d0823b33------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:33:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dklt/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[Running Jupyter Notebook on NYU HPC in 3 Clicks]]></title>
            <link>https://medium.com/@dklt/running-jupyter-notebook-on-nyu-hpc-in-3-clicks-bc589372118a?source=rss-4022d0823b33------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc589372118a</guid>
            <category><![CDATA[nyu]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Doruk Kilitcioglu]]></dc:creator>
            <pubDate>Sun, 18 Nov 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-11-19T02:36:25.631Z</atom:updated>
            <content:encoded><![CDATA[<p>18 November 2018</p><p>I’ve been lately getting a lot of question about my setup for NYU’s High Performance Computing cluster and how it can be made more convenient to use. In this post, I’m going to be sharing my tips and tricks for increasing the productivity when working with remote clusters that use the <a href="https://slurm.schedmd.com/">Slurm Workload Manager</a>, such as NYU’s Prince cluster.</p><h3>Requirements</h3><ol><li><a href="https://wikis.nyu.edu/display/NYUHPC/Request+or+Renew">NYU Prince access</a>.</li><li>Some terminal that allows you to ssh. If you’re on Windows, I highly suggest using <a href="https://dorukkilitcioglu.github.io/2018/05/06/data-science-workflow-ubuntu-windows.html">Windows Subsystem for Linux</a>.</li><li>2 ports that are above 10000. One will be used for rmate, the other for Jupyter Notebook. We will call them port_rmate and port_jupyter.</li></ol><h3>Baby Steps</h3><p>The first order of business is to make sure we can access the Prince cluster easily. The <a href="https://wikis.nyu.edu/display/NYUHPC/Logging+in+to+the+NYU+HPC+Clusters">official method</a> requires you to first login to the bastion host (the gateway), and then login into the Prince cluster. In both cases, you’re required to enter your password, which is highly inefficient.</p><p>Normally, I’d recommend setting up ssh keys, because that is the most secure way of connecting to remote servers. However, you <strong>cannot</strong> modify the contents of the .ssh folder in the gateway server. Thankfully, we can use a little something called sshpass in order to automate the password bit.</p><p>In general, you can use sshpass -p &lt;your password&gt; &lt;valid ssh command&gt; for all actions that require a password. Even better, if you don’t want your password to be persisted in your history, you can use sshpass -f &lt;file containing your password&gt; &lt;valid ssh command&gt; to pass in a file that contains your history instead.</p><p>So install sshpass and save your Prince password to a file (lets call it prince.pwd). I generally do a chmod 400 prince.pwd in order to make sure only my user can read it. Then add the following to your .ssh/config file:</p><pre>Host prince<br>    HostName prince.hpc.nyu.edu<br>    ProxyCommand sshpass -f ~/prince.pwd ssh &lt;net_id&gt;@gw.hpc.nyu.edu -W %h:%p<br>    User &lt;net_id&gt;<br>    RemoteForward &lt;port_rmate&gt; localhost:&lt;port_rmate&gt; <br>    ServerAliveInterval 240<br>    ServerAliveCountMax 2</pre><p>and the following to your .bash_profile file:</p><pre>alias prince=&#39;sshpass -f ~/prince.pwd ssh prince&#39;</pre><p>Reload your .bash_profile file, and viola, you should be able to type prince and land straight into one of the login servers!</p><p>I personally use <a href="https://github.com/henrikpersson/rsub">rsub</a> in order to remotely edit my files in my local Sublime Text instance. Go ahead and install it, and make sure you go to Preferences &gt; Package Settings &gt; rsub &gt; Settings - Default and replace the contents with the following:</p><pre>{ &quot;port&quot;: &lt;port_rsub&gt;, &quot;host&quot;: &quot;localhost&quot; }</pre><p>This will make your local Sublime Text listen to the specific port you are forwarding. Now, advanced users will observe that this is just the <em>local</em> port, and it has nothing to do with the <em>remote</em> port we are forwarding, but I feel like keeping them the same is <strong>much</strong> easier.</p><p>On Prince, download one of the rmate implementations linked above inside above rsub link (hint: wget is your friend.), and place it on your PATH. I placed mine under ~/tools/bin, and placed that directory in my path (export PATH=$PATH:$HOME/tools/bin in your remote .bash_profile file).</p><p>You also have to make sure you set the relevant rmate variables in Prince, so add these to your .bash_profile:</p><pre>export RMATE_HOST=localhost<br>export RMATE_PORT=&lt;port_rmate&gt;</pre><p>Now you should be able to do rmate filename.txt and edit it in your local Sublime Text. Even with port forwarding it twice!</p><h3>Setting up a Python environment</h3><p>When using Python (which is the case for most Data Science projects), it is important to use <a href="https://docs.python-guide.org/dev/virtualenvs/">virtual environments</a> to handle different projects. This is especially important when dealing with Prince, because you don’t have control over the different Python modules available on Prince.</p><p>There are different virtual environment managers, including <a href="https://virtualenv.pypa.io/en/latest/">virtualenv</a>, <a href="https://pipenv.readthedocs.io/en/latest/">pipenv</a>, <a href="https://github.com/pyenv/pyenv">pyenv</a>, and <a href="https://www.anaconda.com/">Anaconda</a>. I personally use Anaconda, so the rest of this guide will assume the use of Anaconda.</p><p>While logged into Prince, type module load anaconda3/4.3.1 to load the Anaconda module. You will now have access to the conda command, and you can use <a href="https://conda.io/docs/user-guide/tasks/manage-environments.html">this guide</a> to create a new environment (let’s call it &lt;env_name&gt;).</p><p><strong>IMPORTANT</strong>: You can now activate the environment and install your dependencies. HOWEVER, if you are going to be using a GPU, make sure you install the GPU versions of your packages. For example, if you want to install Tensorflow, first load in CUDA using module load cuda/9.0.176, load in cuDNN using module load cudnn/9.0v7.0.5, and install the GPU version of Tensorflow using pip install tensorflow-gpu. Otherwise you’ll be requesting a GPU that will not be of any use :)</p><p>Also, make sure you install Jupyter <strong>inside</strong> your environment, otherwise you might end up running a different Jupyter, or the script might just crash. For bonus points, set up a <a href="https://jupyter-notebook.readthedocs.io/en/stable/public_server.html">password</a> for Jupyter.</p><h3>Sbatch &amp; Jupyter Notebook</h3><p>Here comes the fun part. The stuff we covered until now has been relatively tame. We will now up our game with triple port forwarding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/0*_vxEAOD7Iue1amc_.jpg" /><figcaption><a href="https://knowyourmeme.com/photos/565399-sweating-towel-guy">image credit</a></figcaption></figure><p>sbatch is Slurm’s batch script scheduler. Jobs submitted to Slurm using sbatch will be run on the background, so you can safely exit the shell without killing your application. If you need an introduction, you can read <a href="https://wikis.nyu.edu/display/NYUHPC/Submitting+jobs+with+sbatch">NYU’s docs on sbatch</a>.</p><p>What we will do is run a Jupyter Notebook using sbatch, which will place it on a GPU node. We can then forward the Jupyter port to the login servers, and forward that back to our local machine. Fun!</p><p>I use a <a href="https://github.com/dorukkilitcioglu/dorukkilitcioglu.github.io/blob/master/assets/misc/nyu-hpc-data-science/prince/tools/batch/run-jupyter.sbatch">slightly modified version</a> of the sbatch file given <a href="https://wikis.nyu.edu/display/NYUHPC/Running+Jupyter+on+Prince">here</a>. Download my version, modify the contents with your own &lt;env_name&gt; and &lt;port_jupyter&gt;, and put it under your ~/tools/batch/ directory.</p><p>While you’re there, you might as well do it for <a href="https://github.com/dorukkilitcioglu/dorukkilitcioglu.github.io/tree/master/assets/misc/nyu-hpc-data-science">all the files</a>, since we will be needing all of them.</p><p>This script loads in all the necessary CUDA modules, activates your environment, forwards the Jupyter port to the login servers, and then starts the Jupyter notebook. You can run it using sbatch $HOME/tools/batch/run-jupyter.sbatch. However, we can be cheeky, and add</p><pre>alias jp=&#39;sbatch $HOME/tools/batch/run-jupyter.sbatch&#39;</pre><p>to our .bash_profile file. This makes it so that you can run jp from any directory and it will run a notebook from that directory.</p><p>Once you submit the job and Jupyter is running, you can open another shell and start forwarding the right port to your local machine. Normally, you would have to do 2 port forwarding sshs, which is time consuming, so add this to your local .bash_profile file:</p><pre>alias jpprince=&#39;sshpass -f ~/prince.pwd ssh -N -L localhost:8888:localhost:&lt;port_jupyter&gt; &lt;net_id&gt;@prince&#39;</pre><p>and again, by simply doing jpprince, you can port forward the whole thing.</p><p>Now, go to http://localhost:8888 in your browser, and you should be able to use Jupyter notebook as if it was running on your computer!</p><h3>Conclusion</h3><p>Now that everything is in place, you can very quickly start a Jupyter notebook in 3 commands:</p><ol><li>Run prince on your local machine.</li><li>Run jp from Prince when the previous command finishes.</li><li>Run jpprince on your local machine from another shell.</li></ol><p>And viola! You now have a GPU enabled Jupyter notebook!</p><h3>Advanced topics</h3><p>You’ll notice that there are some additional files and commands <a href="https://github.com/dorukkilitcioglu/dorukkilitcioglu.github.io/tree/master/assets/misc/nyu-hpc-data-science">in the repo</a> for the Prince side. They are general utility functions that I’ve found to be useful for productivity.</p><ul><li>Running pygpu &lt;python_script&gt; from a Prince shell will immediately create a batch job that runs the script that you give it.</li><li>Running gpu &quot;&lt;shell command&gt;&quot; will execute the given shell command in a GPU node. This is more flexible than the previous one.</li><li>Running sq will give you the breakdown of your batch jobs.</li><li>Running sr will place you in an interactive shell inside a GPU node. From there, you can use any shell command while having access to a GPU. This is useful if you’re testing to see a script works.</li></ul><p>If you have any more shortcuts, please do let me know!</p><p><em>Originally published at </em><a href="https://dorukkilitcioglu.github.io/2018/11/18/nyu-hpc-data-science.html"><em>dorukkilitcioglu.github.io</em></a><em> on November 18, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc589372118a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hierarchical Clustering and its Applications]]></title>
            <link>https://medium.com/data-science/hierarchical-clustering-and-its-applications-41c1ad4441a6?source=rss-4022d0823b33------2</link>
            <guid isPermaLink="false">https://medium.com/p/41c1ad4441a6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Doruk Kilitcioglu]]></dc:creator>
            <pubDate>Fri, 26 Oct 2018 15:48:22 GMT</pubDate>
            <atom:updated>2018-10-26T15:48:22.029Z</atom:updated>
            <content:encoded><![CDATA[<p>Clustering is one of the most well known techniques in Data Science. From <a href="https://towardsdatascience.com/clustering-algorithms-for-customer-segmentation-af637c6830ac">customer segmentation</a> to <a href="https://www.datadoghq.com/blog/outlier-detection-algorithms-at-datadog/">outlier detection</a>, it has a broad range of uses, and different techniques that fit different use cases. In this blog post we will take a look at hierarchical clustering, which is the hierarchical application of clustering techniques.</p><h3>Clustering</h3><p>Clustering, in one sentence, is the extraction of natural groupings of similar data objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Uw1hHssz9RbqqMXo" /><figcaption>Republican and Democrat clusters of senators</figcaption></figure><p>There are a couple of general ideas that occur quite frequently with respect to clustering:</p><ul><li>The clusters should be naturally occurring in data.</li><li>The clustering should discover hidden patterns in the data.</li><li>Data points within the cluster should be similar.</li><li>Data points in two different clusters should not be similar.</li></ul><p>Common algorithms used for clustering include K-Means, DBSCAN, and Gaussian Mixture Models.</p><h3>Hierarchical Clustering</h3><p>As mentioned before, hierarchical clustering relies using these clustering techniques to find a hierarchy of clusters, where this hierarchy resembles a tree structure, called a dendrogram.</p><blockquote>Hierarchical clustering is the hierarchical decomposition of the data based on group similarities</blockquote><h4>Finding hierarchical clusters</h4><p>There are two top-level methods for finding these hierarchical clusters:</p><ul><li><strong>Agglomerative</strong> clustering uses a <em>bottom-up</em> approach, wherein each data point starts in its own cluster. These clusters are then joined greedily, by taking the two most similar clusters together and merging them.</li><li><strong>Divisive</strong> clustering uses a <em>top-down</em> approach, wherein all data points start in the same cluster. You can then use a parametric clustering algorithm like K-Means to divide the cluster into two clusters. For each cluster, you further divide it down to two clusters until you hit the desired number of clusters.</li></ul><p>Both of these approaches rely on constructing a similarity matrix between all of the data points, which is usually calculated by cosine or Jaccard distance.</p><h3>Applications of Hierarchical Clustering</h3><h4>1) US Senator Clustering through Twitter</h4><p><em>Can we find the party lines through Twitter?</em></p><p>Following the controversial <a href="https://www.sciencedirect.com/science/article/pii/S187775031100007X">“Twitter mood predicts the stock market” paper</a>, researchers have been looking at Twitter as a source of highly valuable data. In this example, we use Twitter to cluster US senators into their respective parties.</p><p>Our data is simple: we only look at which senators follow which senators. That defines a graph structure with senators as the nodes and follows as the edges.</p><p>On this graph, we use the Walktrap algorithm by <a href="https://www-complexnetworks.lip6.fr/~latapy/Publis/communities.pdf">Pons et al.</a>, which does a random walk through graph, and estimates the senator similarity by the number of times you end up at certain senator starting from a senator.</p><p>After getting these similarities, we can use agglomerative clustering to find the dendrogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GYn3kB4x6Cg3_oJONFALA.png" /><figcaption><em>Reds are Republicans, Blues are Democrats, Blacks are independent</em></figcaption></figure><p>In order to measure how well our clustering worked, we can color the results with the party colors. As you can see, Democrats and Republicans are very clearly split from the top, showing the success of this method.</p><p>You also might’ve noticed the two black lines, denoting the independent senators. These are a little trickier to evaluate, but both Sen. Bernie Sanders and Sen. Angus King caucus with the Democratic Party, meaning that it is natural that they are in the Democratic Party branch of the tree.</p><h4>2) Charting Evolution through Phylogenetic Trees</h4><p><em>How can we relate different species together?</em></p><p>In the decades before DNA sequencing was reliable, the scientists struggled to answer a seemingly simple question: Are giant pandas closer to bears or racoons?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*BTCHvLdepH-sPrIlGkL7sA.png" /></figure><p>Nowadays, we can use DNA sequencing and hierarchical clustering to find the <a href="https://en.wikipedia.org/wiki/Phylogenetic_tree">phylogenetic tree</a> of animal evolution:</p><ol><li>Generate the <a href="https://en.wikipedia.org/wiki/DNA_sequencing">DNA sequences</a></li><li>Calculate the <a href="https://en.wikipedia.org/wiki/Edit_distance">edit distance</a> between all sequences.</li><li>Calculate the DNA similarities based on the edit distances.</li><li>Construct the phylogenetic tree.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*qWTQGi9IwojqVtdw1mfGWw.png" /></figure><p>As a result of this experiment, the researchers were able to place the giant pandas closer to bears.</p><h4>3) Tracking Viruses through Phylogenetic Trees</h4><p><em>Can we find where a viral outbreak originated?</em></p><p>Tracking viral outbreaks and their sources is a major health challenge. Tracing these outbreaks to their source can give scientists additional data as to why and how the outbreak began, potentially saving lives.</p><p>Viruses such as HIV have high mutation rates, which means the similarity of the DNA sequence of the same virus depends on the time since it was transmitted. This can be used to trace paths of transmission.</p><p>This method was <a href="http://www.pnas.org/content/99/22/14292">used as evidence in a court case</a>, wherein the victim’s strand of HIV was found to be more similar to the accused patient’s strand, compared to a control group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*pyisOmqVssjW4KiOHthwBg.png" /><figcaption>V1–3 are victim’s strands, P1–3 are accused patient’s, and LA1–12 are the control group</figcaption></figure><p>A similar study was also done for finding the animal that gave the humans the SARS virus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*QJWNB8zfJjZx6LLRzeJy_g.png" /></figure><p>So humans got the SARS virus from palm civets… right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*V3xzBfowQpTluMmL" /><figcaption><a href="https://www.lifegate.com/people/news/kopi-luwak-coffee-asian-palm-civets">image source</a></figcaption></figure><blockquote>“With the data at hand, we see how the virus used different hosts, moving from <strong>bat to human to civet</strong>, in that order. So the civets actually got SARS <strong>from humans</strong>.” — <a href="https://www.sciencedaily.com/releases/2008/02/080219150146.htm">ScienceDaily</a></blockquote><h3>Conclusion</h3><p>Hierarchical clustering is a powerful technique that allows you to build tree structures from data similarities. You can now see how different sub-clusters relate to each other, and how far apart data points are. Just keep in mind that these similarities do not imply causality, as with the palm civet example, and you will have another tool at your disposal.</p><h4>References</h4><ol><li>Big Data Science (NYU) lecture slides by Dr. Anasse Bari</li><li>Bioinformatics (Bogazici University) lecture notes by Dr. Arzucan Ozgur</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41c1ad4441a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/hierarchical-clustering-and-its-applications-41c1ad4441a6">Hierarchical Clustering and its Applications</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[Recommender Systems: From Filter Bubble to Serendipity]]></title>
            <link>https://medium.com/data-science/recommender-systems-from-filter-bubble-to-serendipity-4131930a738e?source=rss-4022d0823b33------2</link>
            <guid isPermaLink="false">https://medium.com/p/4131930a738e</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Doruk Kilitcioglu]]></dc:creator>
            <pubDate>Tue, 09 Oct 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-10-09T20:55:14.956Z</atom:updated>
            <content:encoded><![CDATA[<p>Recommender systems power a lot of our day to day interactions with the content we see on the internet. With over 2.5 quintillion bytes of data created each day, the last two years alone make up 90% of the data in the world [1]. We produce content at a level that is simply impossible to consume in one lifetime, and that makes recommender systems inevitable. However, as Uncle Ben said, with great power comes great responsibility. Here I talk about some of the practical and ethical problems that recommender systems raise, and how we can go about solving them.</p><h3>What do recommender systems do?</h3><p>Recommender systems is at the forefront of the ways in which content-serving websites like Facebook, Amazon, Spotify, etc. interact with its users. It is said that 35% of Amazon.com’s revenue is generated by its recommendation engine[2]. Given this climate, it is paramount that websites aim to serve the best personalized content possible.</p><h3>What the user wants</h3><p>As a huge recommender systems geek, I am always pleasantly surprised whenever I see a good recommender system. I am interested in consuming a lot of content (and I do), but there are not enough hours in the day for me to personally go through everything available for me to consume. I want recommender systems that can understand what I really want to read/listen to/consume at that exact moment, perhaps even when I don’t know what I want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*P7SsGvys9otXCqId.png" /><figcaption>My beautiful Spotify generated playlists</figcaption></figure><p>It used to be that when the content available to you (either through the results of a search, or some other way of wading through the available content like a top 100 list), you had to narrow down your results using some sort of filtering. This filtering often took the form of longer, more explicit search terms, date restrictions, including and excluding certain tags, and many others.</p><p>Those days are now over.</p><p>As a user, I <strong>expect</strong> that I will have assistance in sorting through all the content produced on a website. I <strong>believe</strong> that when I search for std::list on Google, I find the <a href="https://www.reddit.com/r/ProgrammerHumor/comments/9llazt/thanks_google_thats_exactly_what_i_wanted/?st=JMWQC8HO&amp;sh=1946cc99">relevant links</a>. Contrary to a lot of people, I also <em>like</em> personalized ads. If these personalized ads actually make me realize that I am missing some crucial item in my life, I would gladly make the purchase. However, that also does not mean that I like seeing the same mahogany chair following me around 12 different websites just because I looked at a chair once back in 2003.</p><p>Does that sound spoiled? Maybe. But that is the landscape we live in right now. It is the only way we can remain efficient when the generated content is growing exponentially.</p><h3>What the company wants</h3><p>As mentioned above, recommender systems generate a lot of the revenue for many of the major brands in the world. For some, it is the front and center way that a user interacts with the product (ex: Facebook’s news feed). For others, it might supplement the core functionality of the product through personalization (ex: Google’s search engine) or might be a way to keep a user engaged as long as possible (ex: YouTube’s up next feature).</p><p>No matter how you frame it, businesses are businesses, and they are driven by different goals than the consumers. Improving customer experience is paramount for all businesses, and for web-based businesses, this often results in trying to make the experience more personalized for each individual user, creating the need for a recommender system.</p><p>So far so good, right?</p><p>Let’s take a closer look to how an average website can use recommendations to improve user experience:</p><ol><li>Company X realizes that they generate more content than a single person can interact with. Moreover, their competitors are using personalization so that their users can have easier access to relevant content.</li><li>Company X tries their hand on personalizing their search results. They choose a tried-and-true method like matrix factorization, and leverage their historical data to train the model.</li><li>The trial is a resounding success! The A/B tests show that the revenue has increased by 4%, and their monthly active users has increased by 13%!</li><li>Company X invests more resources into their personalizations. Multiple Data Scientists are working on implementing better Machine Learning models that perform better and better on their historical data, as they acquire more and more data.</li><li>They automate the validation such that they can set specific revenue/user/conversion rate/other KPI targets in any combination and try to optimize it using A/B/n testing, which automatically incorporates any new Machine Learning model, constantly improving the quality of recommendations while achieving better and better targets.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*iQOVMupOI_64euZY.png" /><figcaption><a href="https://www.oxfordcollegeofprocurementandsupply.com/procurement-performance-kpis">image credit</a></figcaption></figure><p>This is indeed the dream scenario. You have the historical data points that can provide some training targets (loss functions) and testing targets for your Machine Learning models, and even though you know they are not necessarily a good indicator for the real-world value of a recommender system, you have A/B tests to optimize for the real-world results. Everything here can be quantitatively analyzed.</p><p>Well, expect for the “quality” of recommendations. And speaking of which, how do you even <em>define</em> the quality of a recommendation?</p><h3>What should recommender systems do?</h3><p>As mentioned before, there are a couple of practical and ethical issues with this approach.</p><p>In the context of a behemoth like Google, a recommender system has the ability to affect the very fabric of our society, and unfortunately, we are yet to understand the full implications of <em>how</em> it affects the society. It is obvious that Google facilitates a lot of the information flow on the internet, and getting cut off from Google is therefore a huge deal. But when it comes to quantifying the effects of this flow of information, we are stumped.</p><p>That does not mean we cannot reason about how recommendations <em>should</em> look like, and talk about some important concepts for recommendations in general. Keep in mind though, all of these concepts are product dependent: you will have to choose whether that is relevant to you or your customers.</p><h3>Access to relevant content</h3><p>This comes as a no-brainer, but for completeness’ sake, this is an area that should not be ignored. If you have a recommender system, you want to make sure that it recommends content that is relevant for the user. If I read exclusively fantasy books, then the recommendations I am getting should be largely biased towards fantasy titles. That does not mean I won’t enjoy the occasional action or non-fiction recommendation, but I should not be seeing my recommendations dominated by such genres.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GOiFCBPLOZzJ9b61.png" /></figure><p>One culprit of such recommendations is the Collaborative Filtering approach to recommendations. Continuing with the book example, if there’s a predominant second genre among the rest of the fantasy readers, collaborative filtering will bubble up that genre to you, even if you do not want to consume it. Worse yet, if the recommender system is relying on explicit ratings (1–5), you usually <em>have to</em> consume and rate it bad in order to get rid of such recommendations.</p><p>One way to combat this is using a hybrid model that also leverages content-based recommendations, which is the solution we went with for <a href="https://dorukkilitcioglu.github.io/2018/05/14/introducing-books2rec.html">Books2Rec</a>. That way, you can balance the collaborative filtering with content similarity.</p><h3>Balance the Diminishing Returns</h3><p>Diminishing returns are a well-understood concept in econometrics and psychology. The concept is pretty simple: the more you have of something, the less you want it.</p><p>To give a personal example, I really like listening to a single song until I’m sick of them, or binging Friends until I simply can’t handle another fight between Ross and Rachel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*T19B-Wu4iJKqxflX.gif" /><figcaption><a href="https://media3.giphy.com/media/ubpB6XcvpYMF2/giphy.gif">image credit</a></figcaption></figure><p>Of course, this seemingly runs contrary to the previous notion of getting relevant recommendations; that will hit a point of diminishing returns. The key aspect here is timing: you are likely to get sick of seeing the same type of recommendations (based on your historical data) during a single visit to a website, but when you come back a week later, you don’t want to start from somewhere far away from your historical data.</p><p>Recommender systems typically make the distinction between historical and contextual (session-based) recommendations. Historical recommenders make use of the full extent of your historical data to find the next thing you would want to watch, while contextual recommenders take a look at your current session (think of it like the last hour of your Spotify/YouTube session) and predict what would best fit to you <em>right now</em>.</p><p>Of course, these two systems are not cut and dried, there is most certainly an overlap, and the right recommender system is somewhere in between. Contextual models work best when the opportunity cost is low, and where rapid consumption is viable. Diminishing returns is also more of an issue with the contextual models.</p><h3>Long Term Returns</h3><p>Another problem with recommenders in general is the best-recommendation-first policy. Think of a recommender system that can fully capture what you value in a video, and recommend you the 5 videos that will be the best 5 videos you will ever watch.</p><p>What happens when you finish consuming the best possible content?</p><p>The recommender system will keep recommending you the same <em>type</em> of content, but because you’ve already consumed the best, each and every one of them will be <strong>worse</strong> than the previous.</p><blockquote><em>By doing its job too well, a recommender system can reduce your future enjoyment.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/0*U6DszFmk-GJ8VupN.png" /><figcaption>what happens when no new content is added to a website, <a href="https://arxiv.org/abs/1710.11214">image credit</a></figcaption></figure><p>Now, of course, a lot of content is produced every day, and there’s a very good chance that the best possible content for you is not produced yet. But the fact remains that the top N content for you (or the top N content for the general public) is a hard list to get into, and you might get a better overall enjoyment by spacing the best content.</p><p>Another way of thinking about is that we should aim to maximize the long term reward of our recommendations. Put that way, it is easy to draw an analogy to Reinforcement Learning, and to algorithms like MDP (Markov Decision Process) and Bandits, especially in terms of exploration vs exploitation. And sure enough, we can see a lot of interest in Reinforcement Learning for recommender systems in the recent years.</p><h3>Filter Bubble</h3><p>Another result of the previous scenario is a phenomenon that is called the filter bubble. Coined by Eli Pariser and made famous by his book of the same name, filter bubble is the idea that you become trapped inside a bubble wherein only the information that a personalization algorithm (a filter) thinks you would like gets passed in. As you give the system more and more data, your bubble becomes smaller and smaller, a niche within a niche. You get trapped in a positive feedback loop with no escape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ztWN6g_n9OiKg_zp.jpg" /><figcaption><a href="https://www.smithsonianmag.com/innovation/have-scientists-found-a-way-to-pop-the-filter-bubble-180948265/">image credit</a></figcaption></figure><p>Not only does this limit your options by not displaying content you might’ve liked, over time it homogenizes your interests, which results in you losing interest in different types of content, which again decreases your options. Worse yet, because of diminishing returns, you start to enjoy the content recommended to you less and less.</p><p>All is not lost, though. As designers of recommender systems, even if we cannot reliably solve this problem, we can give the users a way out. It doesn’t have to be fancy — even an <strong>unbiased</strong> and <strong>de-personalized</strong> search system might give the users enough tools to reach content that is outside of their filter bubble. Even if you rely on implicit ratings, a user can over time shift the recommendations to somewhere more diverse.</p><p>Note: A related term that is more associated with politics is <a href="https://en.wikipedia.org/wiki/Echo_chamber_(media)">echo chamber</a>, which has more to do with the interactions of people with like-minded people and getting more and more confident that their thoughts are the right ones. I will not be covering that.</p><h3>Diversification</h3><p>Diversification is a way in which we can fight the effects of the filter bubble and diminishing returns. Unfortunately, it is not a natural byproduct of recommender systems; instead, we have to work for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SMHbrGzgXg8sPPn3.png" /><figcaption>My YouTube recommendations</figcaption></figure><p>I have observed that users can be broadly categorized into two categories in terms of their taste diversity:</p><p>Social users are your typical users with some loosely-defined genre preferences, but are satiated with consuming the items in the top N lists. If a piece of content is popular and/or it has been shared by their friends, they also want to consume it. If you modeled their distribution of tastes as a Gaussian Mixture Model, they would have shallow peaks and a lot of overlap.</p><p>Power users care more about consuming content that they care most about. There are less of them when compared to the social users, but they still make up a sizable portion. Some of these users start off with a pretty diverse set of interests. In terms of a Gaussian Mixture Model, they would have high peaks and a lot of dead zones in the middle.</p><p>It is in our best interest to keep and nurture these diverse set of interests. Some researchers model these tastes explicitly[3], while others try to learn them more organically. As will be explained later on, it might still be in your best interest to force some diversity in even for users with highly specific interests.</p><blockquote><em>By optimizing for the average, you end up sacrificing the higher fidelity recommendations that your power users rely on.</em></blockquote><p>The problem with diversity is that it is hard to measure exactly how diverse a set of recommendations is. In a recent episode of <a href="https://twimlai.com/twiml-talk-187-diversification-in-recommender-systems-with-ahsan-ashraf/">TWiML&amp;AI</a>, Pinterest Data Scientist Ahsan Ashraf talks about a set of guidelines you can use as a sanity check for any recommender system — diversity measure pair:</p><ol><li>Stability: As we give a recommender system items of the same topic/genre, does it converge to that topic, resulting in the recommender system “overfitting” to that topic? How fast does it converge? How diverse are those recommendations?</li><li>Sensitivity: Suppose you have two topics <em>A</em> and <em>B</em>, and start with a 100 items of <em>A</em>. Do the recommendations cover the whole spectrum (from only a little bit of <em>B</em> to all <em>B</em>s) as you add more and more items from <em>B</em>? Is your diversity maximized at 50:50 ratio and minimized at 100:0 and 0:100?</li><li>Sanity: Are completely random recommendations more diverse than the average recommendations for a user? Are topic-specific lists less diverse than the average recommendations for a user?</li></ol><h3>Serendipity</h3><p>Taking one more step forward from diversity, we come to the concept of serendipity, which is finding something valuable or beneficial while not looking for it, a happy coincidence. It is finding something that simply blows you away.</p><p>I like dividing serendipity into two categories: immediate and eventual. Immediate serendipity happens, well, immediately. You’re walking along the streets, and you look up — without any specific reason — and see the Empire State building.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GGYHNrdydM74M3rE.jpg" /></figure><p>Eventual serendipity (which perhaps is a misnomer, but I have yet to find a better name for it) is when you look back at your life, and realize one random event led you on a journey that shaped part of who you are.</p><p>In order to realize the importance of serendipity, think of that random incident that led you to discover your favorite artist, or your best friend, or that moment when you realized <em>this</em> was all you had been looking for.</p><p>Wouldn’t it be great if we as the designers of a recommender system could facilitate this event?</p><p>Looking at it analytically, we can use a proxy for the actual serendipity (which is very hard to quantify) with looking at items that the probability of the user having heard of that item is low and the probability of user liking that item is high. The problem then becomes calculating these two probabilities, which we can approximate using any number of methods.</p><p>Of course, this proxy is not ideal, and there is ongoing research on trying to figure out a better way to formulate this problem. One thing that we know is that we need some sort of diversity or randomness in order to facilitate that.</p><p>Obviously, this lends itself to some problems easier than the others. It is much easier to be more experimental in song recommendations than book recommendations. This is due to what the economists call the “opportunity cost”. Each time you interact with something, you choose not to interact with the others. In music, if you fully listen to the song, you might lose 4 minutes of your time, and you even have the option to skip it. Thanks to music streaming services, you probably won’t pay anything extra to engage with that content.</p><p>However, a book is a longer term investment. It might take you a 100 pages to realize that book is not a good fit for you, and by that time you might’ve spend a couple of hours and $10 for the book. Therefore, it is important to be (on average) more conservative doing book recommendations than music recommendations.</p><h3>A case study in algorithmic confounding</h3><p>A recent paper[4]from the researchers at Princeton University discusses the further effects of the feedback loop generated by a recommender system. More specifically, they look at the confounding that occurs when models attempt to capture user preferences without accounting for the fact that the choices the user was presented with was also generated by the model, weakening the causal impact of recommendations on user behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*9SWfCWvZBnBpbunQ.png" /><figcaption><a href="https://arxiv.org/abs/1710.11214">image credit</a></figcaption></figure><p>The major claims made in the paper are as follows:</p><ol><li>Not all algorithms benefit from retraining using confounded data (that is, data that has been generated as a result of the recommender system).</li><li>Evaluating a model using confounded data are biased to move the data in a direction that fits the algorithm, creating a feedback loop that should not exist in the underlying data.</li><li>The previous feedback loop works to homogenize both individual users and the whole set of users.</li></ol><p>Without going into details, researchers model a realistic interaction sequence between users being recommended items, recommender system getting the results of those interactions, and updating its recommendations with that data and with new items that are introduced over time.</p><p>Researchers show that in terms of total utility, using confounded data works best with content-based models and social (trust-based) models, but do not have a significant advantage when using with Matrix Factorization models. Moreover, they show that evaluating the model using the confounded data generated by the same model leads to a greater improvement in scores compared to using the confounded data generated by a different model.</p><p>Evaluating your model with confounded data may therefore overstate the performance of your model.</p><p>This is also a worrying case for publicly available datasets used for research, that may themselves be confounded due to the recommender system that was used to create the data, and may therefore have hidden biases for certain types of models.</p><p>Researchers also measure the effect of homogenization on total utility, claiming that homogenization is good because it means the model is learning the underlying patterns, but can also block new items from being discovered that might’ve been beneficial for a user.</p><p>They find that homogenization (captured as the y-axis of the following plot) correlates negatively with total utility (x-axis), for all 4 methods barring the random model, which by definition does not rely on any model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SigRJFrbAAMeQB3T.png" /><figcaption><a href="https://arxiv.org/abs/1710.11214">image credit</a></figcaption></figure><p>It is therefore important that we try to keep our recommendations as diverse as possible, but at the same time, balance them with recommendations that make sense for the users. Again, we can draw an analogy to the explore/exploit problem with Reinforcement Learning methods. If we really want to achieve the best possible outcome, we need to find the right balance and work hard to keep it there.</p><h3>Conclusion</h3><p>Thanks to a growing interest from both the academia and the industry, we have today a lot of tools to make recommendations, and a better understanding of our tools. However, we are not yet at a point where we fully understand the consequences of our choices when building a recommender system. There is no free lunch, and there are always consequences to our choices, even if we cannot immediately see them.</p><p>I hope this post leaves you with some general ideas on what sort of stuff you have to keep an eye out for if you want to give the users the best experience possible. As the designers of recommender systems, we have the power to influence what reaches a user, and what doesn’t. It is up to us to use that power wisely.</p><h3>References</h3><p>1. <a href="https://www.domo.com/learn/data-never-sleeps-5?aid=ogsm072517_1&amp;sf100871281=1">Domo — Data never sleeps</a><br>2. <a href="http://www.mckinsey.com/industries/retail/our-insights/how-retailers-can-keep-up-with-consumers">McKinsey</a><br>3. <a href="https://arxiv.org/abs/1711.08379">Mixture-of-tastes Models for Representing Users with Diverse Interests</a><br>4. <a href="https://arxiv.org/abs/1710.11214">How Algorithmic Confounding in Recommendation Systems Increases Homogeneity and Decreases Utility</a></p><p><em>Originally published at </em><a href="https://dorukkilitcioglu.github.io/2018/10/09/recommender-filter-serendipity.html"><em>dorukkilitcioglu.github.io</em></a><em> on October 9, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4131930a738e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/recommender-systems-from-filter-bubble-to-serendipity-4131930a738e">Recommender Systems: From Filter Bubble to Serendipity</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[Representation Learning through Matrix Factorization]]></title>
            <link>https://becominghuman.ai/representation-learning-through-matrix-factorization-a24a5df235ad?source=rss-4022d0823b33------2</link>
            <guid isPermaLink="false">https://medium.com/p/a24a5df235ad</guid>
            <category><![CDATA[machine]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[artificial]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Doruk Kilitcioglu]]></dc:creator>
            <pubDate>Mon, 10 Sep 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-10-15T13:26:00.211Z</atom:updated>
            <content:encoded><![CDATA[<p>Principal Component Analysis (PCA) and Singular Value Decomposition (SVD) has been around for a while, and have been successfully utilized for learning intermediary representations of data for quite some time. This post will be recap on what they actually do, and how they work.</p><p>Note: this post is part 2 of my Representation Learning series. See <a href="https://dorukkilitcioglu.github.io/2018/02/24/representation-learning-introduction.html">part 1</a> and <a href="https://dorukkilitcioglu.github.io/2018/08/11/pca-decision-tree.html">part 1.5</a>. I also highly suggest checking this post on <a href="https://dorukkilitcioglu.github.io/2018/09/10/representation-learning-matrix-factorization.html">my personal website</a> since Medium cannot render the Latex equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LPDf5-6j4JPlIVAn.png" /></figure><h3>Trending AI Articles:</h3><blockquote><a href="https://becominghuman.ai/cheat-sheets-for-ai-neural-networks-machine-learning-deep-learning-big-data-678c51b4b463">1. Cheat Sheets for AI, Neural Networks, Machine Learning, Deep Learning &amp; Big Data</a></blockquote><blockquote><a href="https://becominghuman.ai/data-science-simplified-principles-and-process-b06304d63308">2. Data Science Simplified Part 1: Principles and Process</a></blockquote><blockquote><a href="https://becominghuman.ai/getting-started-with-building-realtime-api-infrastructure-a19601fc794e">3. Getting Started with Building Realtime API Infrastructure</a></blockquote><blockquote><a href="https://becominghuman.ai/ai-nlp-workshop-7bc121986d61">4. AI &amp; NLP Workshop</a></blockquote><h3>Matrix Factorization</h3><p>Matrix factorization is a way of decomposing any matrix <strong><em>M</em></strong> into multiple matrices. Often this is done for two reasons: in order to reduce the matrix to a lower <em>rank</em> while keeping as much information as possible (dimensionality reduction), or to expose some underlying <em>factors</em> that appear naturally in the data. As this is a series about representation learning, we will be mostly concerned about exposing the underlying factors.</p><p>In the context of Machine Learning, it’s a good idea to think of the matrix <strong><em>M </em></strong>as your data matrix, with <strong><em>n</em></strong> data points and <strong><em>m</em></strong> features. This can be the values you get from a database table or a csv file, or a tf-idf representation of documents, or anything that you have previously translated into a matrix of numbers.</p><p>It’s easy to ignore this, but I find it useful to acknowledge that if you had to translate your data into a matrix of numbers, you’ve already done some sort of Representation Learning already. So congrats! You’re now doing <em>Hierarchical</em> Representation Learning, which is a powerful tool that’s going to be covered more in-depth in the future posts.</p><p>This post will deal with Linear Algebra concepts such as eigenvectors and eigenvalues. If you need a refresher, I highly suggest checking the <a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab">Essence of linear algebra</a> series up in Youtube, which gives a very intuitive and graphical explanation of the concepts.</p><h3>PCA</h3><p>PCA is an algorithms that aims to linearly transform the data such that the resulting dimensions are orthogonal (and therefore can represent the same space), and the dimensions greedily try to explain as much of the total variance as possible (which means the 1st dimension explains the max possible variance any single dimension can, the 2nd explains the most of the remaining variance, and so on). It is a straightforward application of eigenvectors on the matrix <strong><em>M^TM</em></strong>.</p><h3>Calculating the PCA</h3><p>Why <strong><em>M^TM</em></strong>? The mathematical explanation is pretty hefty, but intuitively each value <strong><em>M^TM</em></strong> is the dot product of column <strong><em>i</em></strong> with column <strong><em>j</em></strong>, which defines a covariance matrix over the columns of <strong><em>M</em></strong>. The total variance of this matrix is given by the sum of the diagonal terms in the matrix (commonly called the <em>trace</em> of the matrix).</p><p>Orthogonal linear transformations (such as the one performed by the matrix of eigenvectors) cannot increase the total variance. Going back to our aim of maximizing variance as greedily as possible, we want to distribute this sum to lean heavily to the beginning.</p><p>A more mathematical formulation of this goal is that PCA aims to solve a series of optimization problems, each one trying to optimize the amount of variance for a single dimension — while still being a linear transformation of the data.</p><p>I will not go into the exact math behind it (readers can look to Bishop[1] section 12.1.1 for the proof), but this is equivalent to finding the eigenvalues and the eigenvectors of <strong><em>M^TM</em></strong> and ordering the eigenvectors matrix by their eigenvalues from high to low.</p><p>Once this matrix of eigenvectors (let’s call it <strong><em>T</em></strong>) is learned, all that’s left is to transform the original matrix <strong><em>M</em></strong>, using <strong><em>P = MT</em></strong>. As discussed above, this matrix will have the property that its first dimension explains as much of the total variance as possible, the second dimension explains as much of the remaining variance, and so on.</p><h3>Dimensionality Reduction</h3><p>The dimensionality reduction comes in the form of dropping some of the eigenvectors from <strong><em>T</em></strong>. Notice that <strong><em>M </em></strong>is a matrix of size <strong><em>n</em></strong> <em>x</em> <strong><em>m</em></strong>, <strong><em>M^TM</em></strong> is a matrix of size <strong><em>m</em></strong> <em>x</em> <strong><em>m</em></strong>, and <strong><em>T</em></strong> is a matrix of size <strong><em>m</em></strong> <em>x</em> <strong><em>r</em></strong>, where <strong><em>r</em></strong> is the <em>rank</em> of the matrix <strong><em>M^TM</em></strong>. If all rows of <strong><em>M^TM</em></strong> are linearly independent, <strong><em>r = m</em></strong>.</p><p>If we drop the last few columns of <strong><em>T</em></strong>, we will not lose too much variance, as most of the total variance is in the first few columns. Since variance is closely tied to the <a href="https://dorukkilitcioglu.github.io/2018/08/11/pca-decision-tree.html">amount of information in the matrix</a>, dropping the columns with the least variance keeps most of the information. When you take the first <strong><em>k</em></strong> columns of <strong><em>T</em></strong>, you get a size <strong><em>n</em></strong> <em>x</em> <strong><em>k</em></strong> matrix when you apply the transformation, decreasing the dimensionality.</p><h3>Learned Representation</h3><p>In terms of Representation Learning, the result of using PCA can be viewed as learning a representation that maximally exposes the underlying variance of the data. This makes separating data into logical pieces (such as classification) easier, as explained <a href="https://dorukkilitcioglu.github.io/2018/08/11/pca-decision-tree.html">in a previous post</a>.</p><h3>SVD</h3><p>Singular Value Decomposition is similar to PCA both in terms of its applications and its formulation. It is, however, much more intuitive in terms of Representation Learning, as it explicitly tries to learn the underlying factors (called singular values) in the data, and how the data points and the features relate to those underlying factors.</p><p>More formally, SVD tries to decompose <strong><em>M</em></strong> into <strong><em>M</em></strong> = <strong><em>UΣV^T</em></strong>, where <strong><em>r </em></strong>is the <em>rank</em> of the matrix <strong><em>M</em></strong>, <strong><em>U</em></strong> is a matrix of size <strong><em>n</em></strong> <em>x</em> <strong><em>r</em></strong>, <strong><em>Σ</em></strong> is a diagonal matrix of size <strong><em>r </em></strong><em>x</em><strong><em> r</em></strong>, and <strong><em>V</em></strong> is a matrix of size <strong><em>m</em></strong> <em>x</em> <strong><em>r</em></strong>. Furthermore, <strong><em>U</em></strong> and <strong><em>V</em></strong> are column-orthonormal matrices, such that each of its columns is a unit vector and the dot product of any two columns is 0.</p><h3>Calculating the SVD</h3><p>Calculating the SVD requires you to calculate the eigenvectors of <strong><em>M^TM</em></strong> and <strong><em>MM^T</em></strong> again. This is the same as the process explained above, but we can see why that is with a little bit of math. The math is available in my personal website, as there is no way to display those equations on medium.</p><p>The equations lead to the fact that <strong><em>V</em></strong> is the matrix of eigenvectors for the matrix <strong><em>M^TM</em></strong>. A similar derivation can also be made to obtain <strong><em>U </em></strong>from <strong><em>MM^T</em></strong>. Also seen from the same equation, the matrix of eigenvalues for <strong><em>M^TM</em></strong> is the square of the singular value matrix <strong><em>Σ</em></strong>. We again rearrange the eigenvectors matrix such that <strong><em>Σ </em></strong>is sorted in the decreasing order.</p><h3>Dimensionality Reduction</h3><p>We can again drop the smallest <strong><em>k</em></strong> eigenvalues, which is equivalent to dropping the last <strong><em>k</em></strong> rows and columns from the <strong><em>Σ</em></strong> matrix, and dropping the last <strong><em>k</em></strong> columns from both <strong><em>U</em></strong> and <strong><em>V</em></strong> (note that this drops rows from <strong><em>V^T</em></strong>). If all you want is to then use this smaller data, you can use <strong><em>UΣ</em></strong> as an input to the rest of your Machine Learning algorithm.</p><p>You can also calculate the amount of total variance you’re losing by dropping the last <strong><em>k</em></strong> columns looking at the squares of the singular values. The total variance is the sum of squares of all singular values, and you can calculate which percentage of variance you retain after you drop the last <strong><em>k</em></strong> by summing up the squares of all the remaining singular values and dividing by the original sum.</p><h3>Learned Representation</h3><p>As mentioned before, <strong><em>U</em></strong> and <strong><em>V</em></strong> learn to represent the data points and the features in terms of latent factors. If you want to transform a new datapoint <strong><em>q </em></strong>and you want to transform it into a distribution of these latent factors, you only need to compute <strong><em>qV</em></strong>, which will give you a vector of size <strong><em>r</em></strong>. You can then re-map this vector into the original feature-space using <strong><em>qVV^T</em></strong>. This is useful if <strong><em>q </em></strong>has a lot of missing data, which can be estimated through this procedure. This is also the basis of <a href="https://dorukkilitcioglu.github.io/2018/05/14/introducing-books2rec.html">doing recommendations using SVD</a>.</p><h3>Conclusion</h3><p>Using SVD in order to expose some of the latent factors is the first step of uncovering the secrets behind your data. Due to the linearity of these operations, SVD cannot learn non-linear representations of data. In the following posts, we will see how we can get rid of this pesky linearity using neural networks.</p><p>References:</p><p>1: <a href="http://users.isr.ist.utl.pt/~wurmd/Livros/school/Bishop%20-%20Pattern%20Recognition%20And%20Machine%20Learning%20-%20Springer%20%202006.pdf">Pattern Recognition and Machine Learning, Chris Bishop</a></p><p><em>Originally published at </em><a href="https://dorukkilitcioglu.github.io/2018/09/10/representation-learning-matrix-factorization.html"><em>dorukkilitcioglu.github.io</em></a><em> on September 10, 2018.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F8f5f8b%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F8f5f8b&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href">https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href</a></iframe><figure><a href="https://becominghuman.ai/artificial-intelligence-communities-c305f28e674c"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*2f7OqE2AJK1KSrhkmD9ZMw.png" /></a></figure><figure><a href="https://upscri.be/8f5f8b"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*v-PpfkSWHbvlWWamSVHHWg.png" /></a></figure><figure><a href="https://becominghuman.ai/write-for-us-48270209de63"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*Wt2auqISiEAOZxJ-I7brDQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a24a5df235ad" width="1" height="1" alt=""><hr><p><a href="https://becominghuman.ai/representation-learning-through-matrix-factorization-a24a5df235ad">Representation Learning through Matrix Factorization</a> was originally published in <a href="https://becominghuman.ai/">Becoming Human: Artificial Intelligence Magazine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A case for better Python docstrings]]></title>
            <link>https://medium.com/@dklt/a-case-for-better-python-docstrings-7ed125aaa108?source=rss-4022d0823b33------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ed125aaa108</guid>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Doruk Kilitcioglu]]></dc:creator>
            <pubDate>Sat, 18 Aug 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-08-25T01:28:41.160Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been using Python daily for 3 years, and working professionally with it for about a year now. It is a great language, and I’m grateful that I get to work with it every day. However, my biggest gripe with Python was the rather uninspiring docstrings found online and in style guides. Here, I propose a <strong>clean</strong>, <strong>explicit</strong>, and <strong>visually appealing</strong> alternative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*CN4gIgJydCubNWle.png" /></figure><p>This is a style I’ve been using in my <a href="https://github.com/dorukkilitcioglu/persist-desktop">latest project</a>, and I’m quite happy with how it’s working out.</p><h3>The Standard</h3><p>The official guidelines for Python’s docstring conventions is given by <a href="https://www.python.org/dev/peps/pep-0257/">PEP 257</a>. The following is <em>the</em> example given by it:</p><pre>def complex(real=0.0, imag=0.0):<br>    &quot;&quot;&quot;Form a complex number.<br>    Keyword arguments:<br>    real -- the real part (default 0.0)<br>    imag -- the imaginary part (default 0.0)<br>    &quot;&quot;&quot;<br>    if imag == 0.0 and real == 0.0:<br>        return complex_zero</pre><p>Now, PEP 257 <em>technically</em> does not define the need to use the varname -- explanation (default defaultval) syntax. However, as the authoritative source on the matter, this piece of code is what most people see when they search for python docstring on Google.</p><p>I have a few problems with this. One is that it is not clear in the first glance that where the keyword argument name ends and where the explanation begins. The specific example looks okay, but only because the lengths of the keyword arguments match, and the explanations are short. Case in point:</p><pre>def complex(real=0.0, imaginary=0.0, print_result=False):<br>    &quot;&quot;&quot;Form a complex number.<br>    <br>    Keyword arguments:<br>    real -- the real part (default 0.0)<br>    imaginary -- the imaginary part (default 0.0)<br>    print_result -- whether to print the result to the console.<br>                    this is required for some legacy code<br>                    (default False)<br>    &quot;&quot;&quot;<br>    if imaginary == 0.0 and real == 0.0:<br>        return complex_zero</pre><p>There are different ways of handling multi-line explanations here, like aligning it with the start of the above comment, or going with an indent, but there are problems with both of them. It’s also difficult to explain a tuple input without having statements like “a 3-tuple which…”</p><p>Another problem is the <strong>lack of types</strong>. Although Python is dynamically typed, it is always good to indicate the expected type in the docstring, so that whoever is looking at your code doesn’t have to guesstimate what exactly is being passed into the function. The default argument can sometimes indicate the type, but when the default is None, it’s going to be tough.</p><h3>The Google Way</h3><p>The <a href="https://github.com/google/styleguide/blob/gh-pages/pyguide.md#383-functions-and-methods">Google style guide for Python</a> defines a syntax that makes way more sense. Below is an example directly taken from their style guide:</p><pre>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):<br>    &quot;&quot;&quot;Fetches rows from a Bigtable.</pre><pre>    Retrieves rows pertaining to the given keys from the Table<br>    instance represented by big_table. Silly things may happen if<br>    other_silly_variable is not None.</pre><pre>    Args:<br>        big_table: An open Bigtable Table instance.<br>        keys: A sequence of strings representing the key of each <br>            table row to fetch.<br>        other_silly_variable: Another optional variable, that has<br>            a much longer name than the other args, and which does <br>            nothing.</pre><pre>    Returns:<br>        A dict mapping keys to the corresponding table row data<br>        fetched. Each row is represented as a tuple of strings.<br>        For example:</pre><pre>        {&#39;Serak&#39;: (&#39;Rigel VII&#39;, &#39;Preparer&#39;),<br>         &#39;Zim&#39;: (&#39;Irk&#39;, &#39;Invader&#39;),<br>         &#39;Lrrr&#39;: (&#39;Omicron Persei 8&#39;, &#39;Emperor&#39;)}</pre><pre>        If a key from the keys argument is missing from the <br>        dictionary, then that row was not found in the table. </pre><pre>    Raises:<br>        IOError: An error occurred accessing the bigtable.Table<br>            object.<br>&quot;&quot;&quot;</pre><p>This does a few things well:</p><ul><li>Args and Returns are clearly separated from the rest of the docstring</li><li>The : separator is much more natural than --</li></ul><p>However, the problems I had above are not entirely gone. It is hard to separate the variable names from their explanations, its hard to explain a tuple, and there are no types.</p><h3>An alternative</h3><p>What I’m proposing is a <strong>clean</strong>, <strong>explicit</strong>, and <strong>visually appealing</strong> solution:</p><pre>def run_on_command_line(command, input=None, open_async=False):<br>    &quot;&quot;&quot; Runs a command on command line</pre><pre>    Args:<br>        command::[str]<br>            The command to run. The first element in list is the <br>            executable, the rest are the arguments<br>        input::bytes<br>            The input to be fed in as STDIN<br>        open_async::bool(=False)<br>            Whether to open the process as asynchronous. If set, <br>            there will not be any communication through stdin and <br>            stdout, and the return code may not be set.</pre><pre>    Returns:<br>        return_code::int<br>            The return code of the executed command<br>        stdout::str<br>            The output of the command as a string, or an error <br>            object if the command was not executed successfully <br>        pid::int<br>            The process id of the created process<br>&quot;&quot;&quot;</pre><p>The first thing to notice is that each keyword argument and returned object has a base syntax of varname::type. This makes it easy to, at a glance, understand the type of argument the function is expecting, and is very explicit. If there is a optional argument, you can optionally use varname::type(=defaultval). I personally do not use them if I’m not expecting to generate a docstring using pydoc.</p><p>For lists and dicts, I use shorthands like [str] and {int: float}. If you have non-uniform lists or dicts, you can always fall back to list and dict keywords.</p><p>All the explanations are on a new line and indented, which makes their starting points clearly align between different lines and different arguments, making the docstring look clean and visually appealing.</p><p>For the high level tuples which are the only input or the output for a function, like the return value above, you can use a spread out notation similar to arguments. Since by default you can only have a single return value (even if it is a tuple), spreading it out does not create any confusion.</p><p>For inner tuples, it gets a little trickier:</p><pre>&quot;&quot;&quot;<br>Returns:<br>    return_code::int<br>        The return code of the executed command<br>    stdout::str<br>        The output of the command as a string, or an error object if<br>        the command was not executed successfully<br>    process::tuple(2)<br>        All information related to a process</pre><pre>        pid::int<br>            The process id of the created process<br>        proc::Process<br>            The process object<br>&quot;&quot;&quot;</pre><p>The description for the tuple string is optional, as explaining everything inside that tuple should be sufficient in order to understand the tuple, but it is sometimes worth it to explain the tuple at a high level.</p><p>This is not a perfect solution for inner tuples, and I welcome improvements.</p><h3>Conclusion</h3><p>This docstring style has been adopted by a few of my coworkers and friends already. Since it is very verbose, I do not use it for every single function, but for longer functions that need clarity, this style works very well. If you have any suggestions, or if you decide to adopt this style, make sure you send me a message or an email!</p><p><em>Originally published at </em><a href="https://dorukkilitcioglu.github.io/programming/2018/08/18/python-better-docstring.html"><em>dorukkilitcioglu.github.io</em></a><em> on August 18, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ed125aaa108" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adventures with RapidMiner]]></title>
            <link>https://medium.com/@dklt/adventures-with-rapidminer-859a744d0796?source=rss-4022d0823b33------2</link>
            <guid isPermaLink="false">https://medium.com/p/859a744d0796</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[rapidminer-software]]></category>
            <dc:creator><![CDATA[Doruk Kilitcioglu]]></dc:creator>
            <pubDate>Thu, 01 Mar 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-09-02T19:10:49.983Z</atom:updated>
            <content:encoded><![CDATA[<p>For our <a href="https://cs.nyu.edu/~abari/TeachingBDS.html">Big Data Science course @ NYU</a>, me, <a href="https://nickgreenquist.github.io/">Nick</a>, and <a href="https://panghalamit.github.io/">Amit</a> are building a <a href="https://github.com/dorukkilitcioglu/book-recommender-system">Book Recommender System</a>, specifically for using with <a href="https://www.goodreads.com/">GoodReads</a>. Although the exact details of what we’re doing is yet to be ironed out, we though it was a good idea to get a quick and dirty baseline with <a href="https://rapidminer.com/">RapidMiner</a>. More than a couple of hours later, I can safely say that while we did get a baseline, it ended up more work than intended.</p><h3>RapidMiner</h3><p>RapidMiner is a tool that allows for rapid prototyping using Machine Learning algorithms without ever touching a programming language. It offers most of the commonly used Machine Learning algorithms by default, and there are even extensions that you can download if your specific algorithm is not supported out of the box. It has a 10000 row limit without a license, which can be restrictive considering Big Data can contain billions of rows of data, but you acquire educational licenses very easily.</p><h3>The good</h3><p>The good part of using RapidMiner was really the ease of use for common tasks. If the input data is properly formatted, it is really easy to get it as input, fill in the missing values, set up some classification algorithm, and get the all the relevant metrics using cross validation. It also uses drag-and-drop components, which becomes a lot faster than writing code that ties everything together. Last, but not the least, it provides a visual workflow, which makes any complicated project much more easy to digest.</p><h3>The bad</h3><p>As with all of the systems that hide the implementation details, you will hit the limits on what it allows you to do sooner or later. Unfortunately, in our case, this was sooner rather than later. Converting our csv file to something that would work well with the RapidMiner ecosystem ended up being impossible to do through RapidMiner, and we had to result to extensions that also did not work well with rest of the RapidMiner ecosystem.</p><h3>Recommender System</h3><p>Our data was the ratings from <a href="https://github.com/zygmuntz/goodbooks-10k">goodbooks-10k</a> database. The ratings are given as a csv file with three columns: user_id, book_id, and rating. This is the most common way of storing user ratings. For example, the first 5 rows are:</p><p>user_id book_id rating 1 258 5 2 4081 4 2 260 5 2 9296 5 2 2318 3</p><p>For the record, there are 10000 books and 56000 users, with 6 total million ratings. If you actually do the multiplication, you can see that the number of possible ratings between 10000 books and 56000 users are way more than 6 million (93 times more, in fact). The reason is that the data is very sparse. Nobody can expect every person to read and rate anything close to 10000 books, because most people only really average a couple of books per year.</p><h3>Building the matrix</h3><p>These csv files are used for building the user-item matrix. Essentially, a user item matrix is another way of representing user ratings, and it is probably the most used one. The reason is that there are Matrix Factorization techniques that work on these matrices, which are able to deconstruct and reconstruct the matrix to guess the missing ratings.</p><p>The data does not come in this format due to the aforementioned sparsity. Notice how the first user only has a single book rating: by keeping our data in a user-item matrix, we would be storing 9999 extra ratings that serve no purpose. Even if you use 4 bytes per rating (which is a typical int), this data would’ve been 2GB instead of ~100MB. And this is just based on the 10000 most commonly read books — think of how more obscure books would fare.</p><h3>Where RapidMiner fails</h3><p>Unfortunately, reading in this sparse data and transforming into a user-item matrix has been impossible for us with RapidMiner. There is a ReadSparse component, which supposedly reads sparse files, but we could not find any good documentation into how it works. We also could not find a way where we load the data as it is, and transform it into a user-item matrix. We tried some combinations of pivoting and de-pivoting, and essentially gave up after a few hours. It was also discouraging that we did not find a blog post that could walk us through it. And even if we did, unless it could handle sparse matrices, it would have been of little use to us.</p><p>Conversely, the following Python code took me 10 minutes to write (with the help of StackOverflow), and can read the ratings file in a sparse matrix:</p><pre>ratings = pd.read_csv(&#39;data/goodbooks-10k/ratings.csv&#39;)<br>ratings = ratings.to_sparse()<br>users = list(ratings.user_id.unique())<br>books = list(ratings.book_id.unique())<br>data = ratings[&#39;rating&#39;].tolist()<br>row = ratings.user_id.astype(&#39;category&#39;, categories=users).cat.codes<br>col = ratings.book_id.astype(&#39;category&#39;, categories=books).cat.codes<br>sparse_matrix = csr_matrix((data, (row, col)), shape=(len(users), len(books)), dtype = np.dtype(&#39;u1&#39;))</pre><h3>Extensions to the rescue</h3><p>Fortunately, we did find an extension (simply titled Recommendations) for RapidMiner. Once we figured it out, it wasn’t that hard to get some baseline results. The extension handles recommendations in both the information retrieval and in rating prediction aspects. Unfortunately, it probably does construct an explicit user-item matrix, as memory quickly became an issue. With only 12000 users, it was using over 12GB of memory. As such, it is not really suited to even moderately-sized databases - we could not even fit our 6 million ratings.</p><p>What it did was to give us a very barebones baseline. Again, since the number of users are so low, we do not want to draw any conclusions, but it still is an indication to what is possible. I’m not going to go in-depth in these metrics, as this blog post is mainly for exploring RapidMiner and not the Recommender Systems themselves.</p><h3>Information Retrieval</h3><p>This is the process that we used for making recommendations and evaluating it as an information retrieval problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*k0W-v1v6mYRzPXzL.png" /></figure><h4>Results:</h4><p>AUC: 0.753<br>prec@5: 0.043<br>prec@10: 0.039<br>prec@15: 0.038<br>NDCG: 0.288<br>MAP: 0.025</p><h3>Rating Prediction</h3><p>This is the process that we used for making recommendations and evaluating it as an rating prediction problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*2pXXAq_3KGnMnW5A2-QvDw.png" /></figure><h4>Results:</h4><p>RMSE: 0.864 <br>MAE: 0.685 <br>NMAE: 0.171</p><h3>Going forward</h3><p>Our next stop will be <a href="https://mahout.apache.org/">Apache Mahout</a>, which has extensive support for recommender systems, and is therefore a great starting point. You can see our whole journey (including the rmp files for the above processes) in our <a href="https://github.com/dorukkilitcioglu/books2rec">GitHub Repo</a>.</p><p><em>Originally published at </em><a href="https://dorukkilitcioglu.github.io/data-science/2018/03/01/adventures-rapidminer.html"><em>dorukkilitcioglu.github.io</em></a><em> on March 1, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=859a744d0796" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Representation Learning]]></title>
            <link>https://medium.com/@dklt/representation-learning-1f1d3ceee797?source=rss-4022d0823b33------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f1d3ceee797</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Doruk Kilitcioglu]]></dc:creator>
            <pubDate>Sat, 24 Feb 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-08-18T00:22:44.700Z</atom:updated>
            <content:encoded><![CDATA[<p>Representation Learning is a relatively new term that encompasses many different methods of extracting some form of <strong>useful representation</strong> of the data, based on the data itself. Does that sound too abstract? That’s because it is, and it is purposefully so. Feature learning, Dimensionality reduction, Data reduction, and even Matrix Factorization are all parts of Representation Learning.</p><p>Any Machine Learning model requires some features, numerical representations of data, in order to work. The traditional method is to painstakingly measure some features of the data, and then employ feature engineering in order to extract some new features, either based on your intuition or based on the previous research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*-xJOaONHBQJwfNxI.png" /><figcaption><a href="https://www.memsource.com/blog/2017/09/19/neural-machine-translation-the-rising-star/">Image Source</a></figcaption></figure><p>In this blog post series, I will heavily rely on the <a href="https://arxiv.org/abs/1206.5538">“Representation Learning: A Review and New Perspectives”</a> paper by Bengio et al., which has been immensely useful for me to learn how to think about representations, although I will be including stuff that is older and was not covered in the paper (such as t-SNE, PCA, etc.), and also stuff that is not in the paper simply because they were published after the paper was written (such as Generative Adversarial Networks). Let’s begin.</p><h3>Feature Engineering</h3><p>Feature engineering is a very useful (and often necessary) step when trying to train a model. For example, it is pretty intuitive that when trying to predict traffic, categorizing time of day into discrete intervals (such as morning, noon, afternoon, etc.) can be more helpful than the actual hours or seconds that has elapsed in the day. You know this, because you see the rush hour every day, and know that there are certain time bands that are bound to have more traffic.</p><p>What happens if you don’t do this? Linear models will outright fail to incorporate this information. A linear model will try to match the high input (hours later in the day) with either high or low traffic, and try to match the low input (with the lowest being either midnight or 1am, depending on how you represent it) with its inverse. This doesn’t work. A good model might ignore this variable due to its low correlation with traffic (even though time of day is one of the most important factors in determining traffic), or you might throw it out based on a chi-squared test, or any other test that measures statistical significance. A worse model might fit a bias towards one way or other, meaning that it thinks either hour 23 or 0 has the maximum amount of traffic (it doesn’t).</p><h3>Feature Learning</h3><p>Of course, better models <em>learn</em> to use transformations of this variable in order to extract meaningful information. Neural networks in particular are used by many partly because of their power to learn features. They do not <em>necessarily</em> learn transformations that are useful in other tasks, but often these transformations (and their resulting representations) are useful in different applications. This will be covered later in Multi-Task and Transfer Learning.</p><p>Representation Learning can be thought of as the inverse of this approach. Can we learn a <em>representation</em> of the data, such that it is (by some metric) close to the input and is, at the same time, a useful input to a predictor?</p><h3>Learning good representations</h3><p>According to Bengio et al., a good representation “is often one that captures the posterior distribution of the underlying explanatory factors for the observed input”. That is, assuming there are some underlying explanatory factors in the data, which should always be the case (otherwise you’re working just with noise), a good representation learns (per data point) the impact of each explanatory factor in generating the data. Since we model these factors by variables, the impact is the value of any variable.</p><p>Also according to Bengio et al., a good representation is “one that is useful as input to a supervised predictor”. That is, there needs to be some value to this representation, else there is no reason to use it. It is often impossible to evaluate how good a representation is, and as with most things in Machine Learning, goodness and usefulness are synonymous in this case. It should be noted that my definition for it does not include supervised predictor, as I find using methods such as t-SNE for visualizations can prove to be extremely useful.</p><h3>General purpose priors in representations</h3><p>Below are some priors (assumptions about the underlying factors) that are useful when learning about methods for learning representations. Most learners of representations base their methods in the assumption that some combination of these factors hold for data. As such, these factors — and how different learners utilize these factors — should be in the back of your head when trying to select a model for your dataset.</p><p>This list was compiled, again, by Bengio et al. All credit go to them.</p><h4>Smoothness</h4><p>Assumes that the function used for representation is sufficiently smooth, such that small perturbations to the input only cause small differences in representations. This is useful as it means that the representation is less susceptible to noise.</p><h4>Multiple explanatory factors</h4><p>Assumes that the data (and its underlying distribution) is generated by multiple underlying factors, and that these factors are largely independent of each other (or as the paper puts it, each factor generalizes over the different configurations of the other factors). Viewed this way, representation learning becomes the act of separating the strengths of the factors per data point.</p><h4>A hierarchical organization of explanatory factors</h4><p>This builds upon the previous point by assuming that these factors are found in an hierarchical manner. The higher you go in the hierarchy, the more abstract factors you learn, as you are essentially learning the factors of the factors. The most famous example of this is Yann LeCun’s digit recognition model, which shows the clear hierarchical structure from edges to lines to small shapes to digits themselves. Deep models are naturally well suited for these.</p><h4>Semi-supervised learning</h4><p>Assumes that at least a part of the learned representation is useful for supervised models. This allows the learned representations of data (usually done unsupervised) to be provided as an (but not necessarily the only) input to supervised predictors. Since unsupervised data is much more abundant than supervised, this assumption (if true) can allow you to leverage a much bigger data than would’ve been possible. This can be seen in word embeddings, as they have been known to improve most NLP tasks compared to a one-hot encoding schema. Moreover, it is often better to download the pre-trained embeddings and fine tune them for your task (see below).</p><p>Similar to the above, this assumes that representations of the data learned during one supervised task is also useful in other tasks. This is the base assumption under Multi-Task and Transfer Learning. Learners of image representations employ this heavily, as for most tasks, first downloading a well-tested pre-trained model (such as the VGG models) greatly improve your end result.</p><h4>Manifolds</h4><p>I have a soft spot for manifolds. They represent the hope that there is some order to the chaos that is known as data. Manifolds are lower-dimensional regions in the data that collectively contain most data points. One of the most common ways of learning manifolds is using Principle Component Analysis (PCA). Although the exact workings of PCA will be explained in another post, it is sufficient now to say that PCA learns linear manifolds (hyperplanes) by picking the hyperplanes with the most variance (and as such, explains the data the most). For non-linear manifold learning, autoencoders are the latest trend.</p><h4>Natural clustering</h4><p>Natural clustering builds up on the idea of manifolds by positing that the data points that are close on the learned manifolds belong to the same group (cluster). We like seeing that the data that are projected to be close on the manifold also belong to the same cluster, as this is exactly how we perceive the world. Moreover, this also assumes that there are low density regions in between the manifolds, and as such, there is also a natural separation between the data points.</p><p>An intuitive way of forcing this is using adversarial attacks. In Generative Adversarial Networks, the representation of the data is constantly polished by adversarial attacks, so that the representation becomes robust in the face of noise. This exactly means that there are low density regions between the representations of different categories, as mid density regions would have been exploited by the adversarial attacks.</p><h4>Temporal and spatial coherence</h4><p>This idea is the marriage of smoothness, manifolds, and categories. It assumes that the manifolds are smooth with respect to data, which means that small changes in the data will cause small changes in its representations on the manifold. If we are attempting to put data into categories, this means that categories should not change due to noise. Temporal changes refer to consecutive values in a time series, which again must hold these properties.</p><h4>Sparsity</h4><p>Sparsity is the assumption that given multiple explanatory factors, only a small percentage are active per data point. It is often represented by biasing the learned factors to zero, which can be done by using L1 regularization on the learned representations if a loss function is used. The most common example is probably the sparse coding. Note that while in representation learning, you generally want to keep the dimensionality of the representation smaller than the dimensionality of the input, creating a bottleneck (especially if the model producing the representations can copy the input directly), sparse representations can be <em>overcomplete</em>, in other words, have a larger dimensionality. This greatly increases the number of explanatory factors you can model.</p><h4>Simplicity of Factor Dependencies</h4><p>In many aspects of the real world, hierarchical factors are often simple (depending only on a couple of factors) linear (only requiring linear transformations) combinations of different factors. By forcing a representation to adhere to these simplicities, you can greatly reduce the overfit of your representation to your data. This, however, does not mean that complex hierarchies do not exist, or that you will have enough data and computing power to model all the different simple dependencies.</p><h3>Conclusion</h3><p>As this will be a multi-part series, there cannot be a real conclusion. However, the information here (and especially the priors) should always be at the back of your mind when you have to choose a Representation Learning algorithm. If you have an intuition about the underlying priors that give birth to your data, you can then choose the models that go well with it.</p><p>As cited many times above, this blog post would not have been possible without the paper by <a href="https://arxiv.org/abs/1206.5538">Bengio et al.</a>. You can take a look at the plethora of examples in that paper to see great examples of representation learning being used in the academia and the industry. And although this blog post was on the longer side, the following ones should be easier to digest.</p><p>I’ll see you then.</p><p><em>Originally published at </em><a href="https://dorukkilitcioglu.github.io/machine-learning/2018/02/24/representation-learning-introduction.html"><em>dorukkilitcioglu.github.io</em></a><em> on February 24, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f1d3ceee797" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello World]]></title>
            <link>https://medium.com/@dklt/hello-world-60766f69c47b?source=rss-4022d0823b33------2</link>
            <guid isPermaLink="false">https://medium.com/p/60766f69c47b</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Doruk Kilitcioglu]]></dc:creator>
            <pubDate>Sat, 17 Feb 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-08-11T18:41:19.255Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the blog. This blog will house my adventures through grad school and beyond. The contents of this blog will therefore (presumably) be about Data Science and Machine Learning, though it is very much possible that I might add in some other random stuff.</p><p>Given how busy grad school is, there is a good chance that this blog will not be periodically updated, but rather, will be sporadically updated. Hence the title. Even so, these sporadic updates should be good™.</p><p>All of my blog posts will be available <a href="http://dorukkilitcioglu.github.io/">on my personal website</a> two weeks before they are published here, so do check it out.</p><p><em>Originally published at </em><a href="https://dorukkilitcioglu.github.io/misc/2018/02/17/hello-world.html"><em>dorukkilitcioglu.github.io</em></a><em> on February 17, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60766f69c47b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>