{"@attributes":{"version":"2.0"},"channel":{"title":"Posts on mlpowered","link":"https:\/\/www.mlpowered.com\/posts\/","description":"Recent content in Posts on mlpowered","generator":"Hugo -- gohugo.io","language":"en-us","webMaster":"mlpoweredapplications@gmail.com (Emmanuel Ameisen)","lastBuildDate":"Mon, 20 Mar 2023 00:00:01 -0800","item":[{"title":"ML models don't need that much data to be better than you","link":"https:\/\/www.mlpowered.com\/posts\/ml-models-dont-need-that-much-data\/","pubDate":"Mon, 20 Mar 2023 00:00:01 -0800","author":"mlpoweredapplications@gmail.com (Emmanuel Ameisen)","guid":"https:\/\/www.mlpowered.com\/posts\/ml-models-dont-need-that-much-data\/","description":"<figure><img src=\"https:\/\/www.mlpowered.com\/images\/2023-ml-models-dont-need.jpeg\"\n         alt=\"A robot studying (generated on Lexica.art)\"\/><figcaption>\n            <p>A robot studying (generated on Lexica.art)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>A common trope when discussing AI is to call out the vast quantities of data that models are trained on. This has led some to believe that the performance of AI models comes solely from processing more information than any human.<\/p>\n<p>As I\u2019ve been working more with large models in a variety of domains, and become increasingly impressed with their capabilities, I decided to spend some time verifying these claims. How many more books did ChatGPT actually consume compared to a human? How many images did Stable Diffusion see? Before running the numbers, I would have estimated that the average large model sees five to six orders of magnitude more data than a human, mostly due to how articles have described the size of these datasets. It turns out that the gap between how much data a human and a model needs is much smaller than I had anticipated.<\/p>\n<p>I\u2019ll tackle 4 areas of interest: images, text, speech, and energy. In each, I\u2019ll attempt a ballpark estimate of human and model data consumption, and compare both. Wonder where humans still have the edge and for how long? Let\u2019s find out.<\/p>\n<h1 id=\"images\">Images<\/h1>\n<h2 id=\"humans\">Humans<\/h2>\n<p>Let&rsquo;s estimate how many interesting images a human sees throughout their lifetime. On average, people are awake for 16 hours per day and see around 60 images per second. However, most of these images are nearly identical, so let\u2019s instead use an average quantity of distinct images perceived of 6 per second. 6 images per second for 16 hours a day translates to about 1.4 million images per day, or roughly 2 billion images per year. So, by the age of 10, the average person has seen 19 billion images, and 38 billion by the age of 20.<\/p>\n<h2 id=\"machines\">Machines<\/h2>\n<p>What about computers?<\/p>\n<p>The dataset used to train Stable Diffusion, called LAION, includes approximately 413 million pairs of images and their corresponding captions. This is equivalent to the number of images that a human sees during their first 3 months of life. And yet, compared to most toddlers, stable diffusion is a pretty amazing painter.<\/p>\n<p>The above is a bit of an unfair comparison because each LAION image comes with a caption. While humans aren\u2019t provided live captions, they have other unfair advantages such as their mastery of language which allows them to generate those captions themselves, or 3D vision and depth perception, which makes making sense of the world (and drawing hands) significantly easier. For the purpose of our analysis, we\u2019ll ignore these issues.<\/p>\n<p>Verdict: ML wins. ML models require fewer images than humans<\/p>\n<h1 id=\"speech\">Speech<\/h1>\n<h2 id=\"humans-1\">Humans<\/h2>\n<p>Assuming that babies hear four hours of language a day until they reach pre-K (age 3), and eight hours of conversations or lectures during kindergarten, and approximately twelve hours (including classes and personal time) in elementary school, an average human being will hear approximately 1,460 hours of speech by their first anniversary, 4,000 hours by the time they reach pre-K, 10,000 by kindergarten, 25,000 after completing elementary school, and 60,000 by the end of high school.<\/p>\n<h2 id=\"machines-1\">Machines<\/h2>\n<p>The machine learning model, Whisper, was trained on an impressive <a href=\"https:\/\/huggingface.co\/openai\/whisper-large\">600,000 hours of audio<\/a>, which is ten times more than an average human has heard by the end of high school. At the same time, Whisper performs human level speech transcription in 10 different languages. Assuming equal difficulty for all languages, Whisper is 10 times better than the average human.<\/p>\n<p>Verdict: Tie. ML models require 10 times more data to perform 10 times better.<\/p>\n<h1 id=\"text\">Text<\/h1>\n<h2 id=\"humans-2\">Humans<\/h2>\n<p>On average, Americans read four books per year. Over an active reading range of 10 to 80 years old, that comes out to 280 books. We can generously double this estimate to account for education and round up to 600 books in a lifetime.<\/p>\n<p>Nowadays people don\u2019t just read books. They read blogs (thanks by the way!), social media posts, online articles, as well as texts and email.<\/p>\n<p>People spend an average of 150 minutes daily on social media, a quarter of which is spent reading content. At a reading speed of 250 words per minute, that\u2019s an additional 3.4 million words a year, the equivalent of reading an extra 43 books per year (an average book is <a href=\"https:\/\/www.publishingtalk.org\/writing\/how-many-words-in-a-novel-average-word-count-for-books-by-genre\/\">80,000 words<\/a>). Assuming regular social media use from age 10 to 70, we get an incremental additional 2,623 books per person. What about text and email?<\/p>\n<p>The average email is <a href=\"https:\/\/emailanalytics.com\/ideal-email-length\/\">100 words<\/a>. An average person sends and receives <a href=\"https:\/\/financesonline.com\/email-statistics\">60 non-spam business emails a day<\/a>. All in all that gives us an additional 2.2 million words (or 28 books) a year, totaling 1,708 extra books from 10 to 70.<\/p>\n<p>10 years ago, Americans sent and received an average of <a href=\"https:\/\/www.pewresearch.org\/internet\/2011\/09\/19\/how-americans-use-text-messaging\/\">40 texts a day<\/a>. Based on my experience, I\u2019m going to double this estimate to get to current numbers. 80 texts a day, at a short average length of <a href=\"https:\/\/www.crushhapp.com\/texting-tidbits\/the-average-text-message-length-is-around-7-words\">7 words<\/a>, gives us an incremental two hundred thousand words a year, or 2.5 books. Assuming we text from age 10 to 80 gives us an additional 175 books. That\u2019s a lot of texts.<\/p>\n<p>Summing all those up, we have 600 + 2,623 + 1,708 + 175 = 5,106 books.<\/p>\n<h2 id=\"machines-2\">Machines<\/h2>\n<p>In this analysis, I will use GPT-3 to estimate ChatGPT&rsquo;s data consumption, as more public data exists about it.<\/p>\n<p>GPT-3 was trained on <a href=\"https:\/\/en.wikipedia.org\/wiki\/GPT-3#Training_and_capabilities\">hundreds of billions of words<\/a>, corresponding to about 500 billion BPE tokens. Each BPE token encodes between 3 and 4 characters, meaning that GPT-3 was exposed to a staggering 1,750 billion characters. In English, the average word length is <a href=\"https:\/\/norvig.com\/mayzner.html\">4.8 characters<\/a>, so ignoring other languages and code, GPT-3 has read 365 billion words or approximately 4.6 million books, which is as much text as 1,000 Americans read in their lifetime.<\/p>\n<p>Does GPT-3 exhibit reasoning capabilities that are 1,000 times better than the average american? I wouldn\u2019t say so. What I will say is that it has a breadth of knowledge that is likely 1,000 times superior to the average human, being able to summon facts from essentially any domain of science or the humanities. At the same time, it also fails on riddles that a <a href=\"https:\/\/www.reddit.com\/r\/OpenAI\/comments\/zgghcc\/chatgpt_not_really_that_good_with_riddles_yet\/\">5 year old can solve<\/a>, so we can\u2019t really consider it as superior to humans for now.<\/p>\n<p>Verdict: Humans win. ML models require much more text than humans.<\/p>\n<p>I will note that while these large models do use orders of magnitude more data, I would have expected the difference to be even larger (on the order of a million times larger). The relatively smaller gap surprised me and motivated me to write this blog post.<\/p>\n<h1 id=\"energy\">Energy<\/h1>\n<p>One last comparison for fun.<\/p>\n<p>Americans consume an average of 3,782 kilocalories per day, which translates to approximately 1,600 kWh per year or 128,000 kWh over their lifetime.<\/p>\n<p>Training GPT-3 required <a href=\"https:\/\/www.theregister.com\/2020\/11\/04\/gpt3_carbon_footprint_estimate\">190,000 kWh<\/a>. So GPT-3 consumes as much energy to train as a human would if they were to live 118 years. And this doesn&rsquo;t even take into account the inference costs of running the model while it&rsquo;s being trained.<\/p>\n<p>Verdict: Humans win. In terms of energy, we still have an edge for now.<\/p>\n<h1 id=\"conclusion-converging-curves\">Conclusion: converging curves<\/h1>\n<p>To sum up, machine learning models like Stable Diffusion, Whisper, and GPT-3 have been trained on vast amounts of data, but the difference between the amount of data they have seen and that of humans is not as significant as you may have believed. In fact, Stable Diffusion has been trained on less data than any artist has seen! Although scaling to larger datasets has been beneficial so far, the development of better training techniques (such as recent fine-tuning approaches) will continue to improve our efficiency at learning from data. I expect the gap between the amount of data machine learning models and humans need for training to shrink as progress in model training continues. It wouldn&rsquo;t surprise me if language models start performing as well as humans while training on less data soon.<\/p>\n"},{"title":"Posts","link":"https:\/\/www.mlpowered.com\/posts\/","pubDate":"Mon, 20 Mar 2023 00:00:01 -0800","author":"mlpoweredapplications@gmail.com (Emmanuel Ameisen)","guid":"https:\/\/www.mlpowered.com\/posts\/","description":{}},{"title":"What Noam Chomsky gets wrong about AI","link":"https:\/\/www.mlpowered.com\/posts\/chomsky-gets-wrong\/","pubDate":"Fri, 10 Mar 2023 00:00:01 -0800","author":"mlpoweredapplications@gmail.com (Emmanuel Ameisen)","guid":"https:\/\/www.mlpowered.com\/posts\/chomsky-gets-wrong\/","description":"<figure><img src=\"https:\/\/www.mlpowered.com\/images\/2023-noam-chomsky-gets-wrong.jpeg\"\n         alt=\"Einstein and &amp;lsquo;ML Einstein&amp;rsquo; facing off (AI generated on lexica.art)\"\/><figcaption>\n            <p>Einstein and &lsquo;ML Einstein&rsquo; facing off (AI generated on lexica.art)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>In a recent <a href=\"https:\/\/www.nytimes.com\/2023\/03\/08\/opinion\/noam-chomsky-chatgpt-ai.html\">article<\/a> published in The New York Times by Noam Chomsky, Ian Roberts, and Jeffrey Watumull, the authors made crucial errors regarding Large Language Models (LLMs) and failed to focus on the right questions about them.<\/p>\n<p>In general, I think the misconceptions in the article are pretty common, and limit useful discourse around language models. The sooner we can dispel some of them, the better the field will be, so I thought I\u2019d take an attempt at briefly addressing some errors.<\/p>\n<p>I found three specific claims in the article particularly striking and will explain why they are incorrect below.<\/p>\n<p>The claims in question are:<\/p>\n<ul>\n<li>The human brain is and will remain fundamentally much more sample efficient than ML models like ChatGPT<\/li>\n<li>The measure of human intelligence is the ability to apply the scientific method<\/li>\n<li>The authors claim to have found specific examples of ML model failure. I demonstrate how models actually succeed in both<\/li>\n<\/ul>\n<h1 id=\"claim-1-the-human-brain-is-and-will-remain-fundamentally-much-more-sample-efficient-than-ml-models-like-chatgpt\">Claim 1: The human brain is and will remain fundamentally much more sample efficient than ML models like ChatGPT<\/h1>\n<p>The authors claim that machine learning models like ChatGPT are fundamentally less sample efficient than the human brain, but they fail to provide a set of figures to contextualize this claim. While humans consume less data than some of these large machine learning models, the models usually offer significantly more breadth of capabilities than humans.<\/p>\n<p>In fact, the difference is much smaller than implied in the text. Stable diffusion was trained on a dataset which contains as many images as a human sees in 3 months through the course of normal life, and composes images significantly better than most of us. ChatGPT was trained on two orders of magnitude more texts than an average American reads during their lifetime. It\u2019s also much more proficient in a variety of domains than humans.<\/p>\n<p>Finally, as LLM training techniques have improved, they\u2019ve started leveraging high-quality instructions for fine-tuning which are minuscule datasets in comparison to the original training data, showing that sample efficiency can improve tremendously with better methods.<\/p>\n<p>Given all of this, it isn\u2019t clear at all that human learning is quantitatively more efficient than current ML methods, and while human learning has been optimized over hundreds of thousands of years, we are still discovering algorithmic improvements to machine learning every month. So much for the human mind&rsquo;s efficiency.<\/p>\n<h1 id=\"claim-2-the-measure-of-human-intelligence-is-the-ability-to-apply-the-scientific-method\">Claim 2: The measure of human intelligence is the ability to apply the scientific method<\/h1>\n<p>The article sets an unrealistic benchmark for measuring the intelligence of current machine learning models by comparing their outputs to the body of work produced by Albert Einstein. The authors essentially argue that the ability to apply the scientific method is &ldquo;the most critical capacity of any intelligence,&rdquo; using the theory of gravity as an example.<\/p>\n<p>This benchmark is unrealistic to say the least. The concept of the scientific method itself was first codified in the 20th century, long after billions of humans had already lived. While having an AI contribute to science is an important milestone, it should not be used as the sole benchmark for defining &ldquo;human intelligence.&rdquo;<\/p>\n<p>Today\u2019s models are able to translate between languages better than most humans, retrieve scientific knowledge (mostly) accurately, and understand, summarize and answer questions about complex texts. Sure, they aren\u2019t Karl Popper, but that doesn\u2019t mean they don\u2019t exhibit intelligence.<\/p>\n<p>More generally, a lot gets lost when specifically trying to dissect which aspects of \u201cintelligence\u201d models exhibit, and which they lack. A better measure of progress is to design empirical tasks and to continuously measure progress against them. When doing so, we can see that the field has made tremendous progress in some areas like language understanding, and comparatively less in others such as manipulation of physical objects.<\/p>\n<h1 id=\"claim-3-models-fail-on-specific-examples-due-to-their-lack-of-language-understanding\">Claim 3: Models fail on specific examples due to their lack of language understanding<\/h1>\n<p>Towards the end of the article, the authors finally provide some falsifiable claims for their arguments, which they could have immediately falsified if they carried on a bit more due diligence.<\/p>\n<p>The article claims that machine learning models like ChatGPT fail to properly parse and understand certain phrases, such as &ldquo;John is too stubborn to talk to.&rdquo; However, empirical testing of modern language models shows that they are capable of understanding and parsing this phrase with ease.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/gpt-chomsky-example.jpeg\"\n         alt=\"ChatGPT isn\u2019t fooled by the question in the article. Neither were other models I tried\"\/><figcaption>\n            <p>ChatGPT isn\u2019t fooled by the question in the article. Neither were other models I tried<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>ChatGPT isn\u2019t fooled by the question in the article. Neither were other models I tried\nThe authors also prompt ChatGPT to take a moral stance, which it refuses to do. However, this is not an inherent limitation of the model, but rather a result of its final phase of training, Reinforcement Learning from Human Feedback phase. Models can be trained to espouse arbitrary moral stances, as has been shown over the course of ChatGPT&rsquo;s deployment as its answers to political questions changed as further fine-tuning was performed. Instead of demonstrating the inability to &ldquo;balance creativity with constraint,&rdquo; this experiment shows the opposite: a model can be trained to generate creative answers to a myriad of questions, while being constrained in its answers in some domains (morality in this example).<\/p>\n<h1 id=\"conclusion\">Conclusion<\/h1>\n<p>There are a lot of other issues in the piece, and overall it felt very reminiscent of speeches that some teachers gave when Wikipedia gained in popularity, describing it as categorically inferior to alternatives.<\/p>\n<p>Criticizing a novel tool like ChatGPT won&rsquo;t stunt its growth if people find it useful, and large language models are being used more and more every day. These models are fantastically useful and have significant potential to contribute to society, and we must address the concerns surrounding their use in a responsible way.<\/p>\n<p>But in my opinion, this criticism should be based on empirical results and on concrete attributes of the technology at hand, rather than on hypotheses about the true nature of intelligence. As language models continue to evolve and improve, I hope that the discourse around their capabilities and limitations continues to improve.<\/p>\n"},{"title":"Most impactful AI trends of 2018: the rise of ML Engineering","link":"https:\/\/www.mlpowered.com\/posts\/2019-ml-trends\/","pubDate":"Wed, 02 Jan 2019 22:02:51 -0800","author":"mlpoweredapplications@gmail.com (Emmanuel Ameisen)","guid":"https:\/\/www.mlpowered.com\/posts\/2019-ml-trends\/","description":"<figure><img src=\"https:\/\/www.mlpowered.com\/images\/2019-ml-trends-cover.jpeg\"\n         alt=\"2019, the year for tool builders\"\/><figcaption>\n            <p>2019, the year for tool builders<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>The field of Machine Learning (ML) has been consistently evolving since Data Science started gaining traction in 2012. However, I believe 2018 was a critical <em>inflection point<\/em> in the ML industry. After helping <a href=\"http:\/\/insightdatascience.com\/\">Insight<\/a> Fellows build dozens of ML products to get roles on applied ML teams and reading through both corporate and academic published research, I\u2019ve seen more need for engineering skills than ever before.<\/p>\n<p>As a field that has consistently toed the line between its origins in academic research and the need to serve customer needs, it has often been hard to reconcile engineering standards with ML models. As both research and applied teams are doubling down on their engineering and infrastructure needs, the nascent field of <em>ML Engineering<\/em> will build upon 2018\u2019s foundation and truly blossom in 2019.<\/p>\n<p>To illustrate this, I wanted to both:<\/p>\n<ul>\n<li>Share back three of the key trends I observed in 2018<\/li>\n<li>Draw a parallel to how I think they\u2019ll affect 2019 in three key ways<\/li>\n<\/ul>\n<h1 id=\"three-takeaways-from-2018\">Three takeaways from 2018<\/h1>\n<p>Both in research and industry, ML is growing at a pace that is thrilling and exciting for the future, but can make it hard to get a sense for the direction of the field. Here are three trends I\u2019ve identified from 2018 that I think will have an impact on ML in industry in 2019 and beyond.<\/p>\n<h2 id=\"1-redefining-representation-learning\">1. Redefining representation learning<\/h2>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/2019-ml-trends-gan.gif\"\n         alt=\"An Insight AI project presenting a novel photorealistic image generation method\"\/><figcaption>\n            <p>An Insight AI <a href=\"https:\/\/blog.insightdatascience.com\/generating-custom-photo-realistic-faces-using-ai-d170b1b59255\">project<\/a> presenting a novel photorealistic image generation method<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>One of the most impressive trends in 2018 has been various models\u2019 growing ability to capture increasingly useful information in <em>dense learned representations<\/em>. Here are a few examples below:<\/p>\n<ul>\n<li><strong>Generative Adversarial Networks (GAN)<\/strong> have existed since <a href=\"https:\/\/arxiv.org\/abs\/1406.2661\">2014<\/a> and have grown from an exciting research proposition to a cutting edge technique. The ability of these models to learn a condensed <em>representation<\/em> allows them to be applied as photo-realistic editors (linked above) and <a href=\"https:\/\/arxiv.org\/abs\/1808.07371\">style transfer for dance<\/a>. <a href=\"https:\/\/arxiv.org\/abs\/1812.04948\">Recent research<\/a> is further improving on the quality of these representations.<\/li>\n<li><strong>Reinforcement Learning<\/strong> has had a few success stories in 2018 as well. OpenAI\u2019s Dota 2 bot showed great promise, beating semi professional teams. A core part of the work involved reducing a complex game to a smaller learned <em>representation<\/em> (effectively a list of 1024 numbers, see <a href=\"https:\/\/neuro.cs.ut.ee\/the-use-of-embeddings-in-openai-five\/\">here<\/a> for more).<\/li>\n<li><strong>Natural Language Processing (NLP)<\/strong> finally got its ImageNet moment in 2018. This past year has been called the year of transfer learning for NLP because of successful approaches in large scale language model pre-training, such as <a href=\"https:\/\/arxiv.org\/abs\/1801.06146\">ULMFiT<\/a> and <a href=\"https:\/\/arxiv.org\/abs\/1810.04805\">BERT<\/a>. Again, the key to these is to consume a large corpus of text such as the entirety of Wikipedia to learn a more useful <em>representation<\/em> of text.<\/li>\n<\/ul>\n<p>Other than the quality of the representations they generate these exciting results have something else in common: they leverage an increasing amount of data and compute, which leads us to our second trend!<\/p>\n<h2 id=\"2-scaling-up\">2. Scaling up<\/h2>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/2019-ml-trends-scale.png\"\n         alt=\"The scale of compute (credit to OpenAI)\"\/><figcaption>\n            <p>The scale of compute (credit to <a href=\"https:\/\/blog.openai.com\/ai-and-compute\/\">OpenAI<\/a>)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>In recent years, we have learned that when it comes to performing on <em>well-defined tasks<\/em>, such as standard datasets or game environments, larger datasets and additional compute will help us push performance further.<\/p>\n<p>In fact, if we look back to the examples in the representation learning section, they all leveraged a larger dataset or more compute:<\/p>\n<ul>\n<li>Many GAN improvements such as <a href=\"http:\/\/large%20scale%20gan%20training%20for%20high%20fidelity%20natural%20image%20synthesis\/\">BigGAN<\/a> have relied on massively larger datasets, and training models for longer.<\/li>\n<li>OpenAI\u2019s Dota 2 bot plays 180 years worth of games against itself every day during training.<\/li>\n<li>NLP models learn better representations by leveraging the entirety of Wikipedia before even starting to train on their actual task!<\/li>\n<\/ul>\n<p>While the strategy of scaling up has shown promise on academic tasks, this post focuses on practical ML in industry where there is often <strong>no standard definition of a task or dataset<\/strong>, and the data distributions we are trying to understand are <em>constantly shifting<\/em> in nature. This requires an entirely different set of tools.<\/p>\n<p>In fact, the disparity between research results we see today (see <a href=\"https:\/\/www.youtube.com\/watch?v=PCBTZh41Ris\">video<\/a> of the dance paper above) and what has been deployed in most products except by a few leading companies points to a <strong>wide gap between researchers and well funded teams, and other practitioners and startups<\/strong>.<\/p>\n<h2 id=\"3-building-internal-platforms\">3. Building internal platforms<\/h2>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/2019-ml-trends-michelangelo.png\"\n         alt=\"An architecture diagram of Uber\u2019s Michelangelo\"\/><figcaption>\n            <p>An architecture diagram of Uber\u2019s <a href=\"https:\/\/eng.uber.com\/michelangelo\/\">Michelangelo<\/a><\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>This past year, more companies have started to publicize the <strong>scale of the tooling they have built internally<\/strong> to help support their ML efforts. Here are a few personal favorites:<\/p>\n<ul>\n<li>Uber released two more articles in their series explaining Michelangelo (<a href=\"https:\/\/eng.uber.com\/michelangelo\/\">one<\/a>, <a href=\"https:\/\/eng.uber.com\/michelangelo-pyml\/\">two<\/a> and <a href=\"https:\/\/eng.uber.com\/scaling-michelangelo\/\">three<\/a>) which I highly recommend reading.<\/li>\n<li>Airbnb shared a very candid and fascinating <a href=\"https:\/\/arxiv.org\/abs\/1810.09591\">account<\/a> of the trials and tribulations of applying Deep Learning to search rankings.<\/li>\n<li>Netflix explained the infrastructure they have put in place to use notebooks in production in these <a href=\"https:\/\/medium.com\/netflix-techblog\/notebook-innovation-591ee3221233\">two<\/a> <a href=\"https:\/\/medium.com\/netflix-techblog\/scheduling-notebooks-348e6c14cfd6\">posts<\/a>.<\/li>\n<\/ul>\n<p>Seeing how some of the best engineering teams in industry have tackled the challenge of delivering ML to their users is inspiring. At the same time, because building such platforms represents such a herculean effort, many practitioners advise smaller teams to avoid building their own ML platform.<\/p>\n<p>This leaves most small to medium sized teams in a no man\u2019s land between cobbling together offerings from service providers that do not exactly fit their needs, and taking on significant engineering costs. There is a <strong>growing gap<\/strong> pointing to a need for a set of frameworks like Tensorflow and Spark, and of widely shared best practices for <strong>all the parts of ML that are not purely model training<\/strong>.<\/p>\n<p>More and more people realize that <strong>nobody needs yet another library or tutorial to build a 3-layer neural network on MNIST<\/strong>. Consequently, many startups have entered the space of data and model infrastructure, management and deployment, and educational resources have started to focus on these aspects more. This is why, I fundamentally believe that 2019 will be <strong>the year of ML Engineering<\/strong>. I\u2019ll explain how I see this unfolding below!<\/p>\n<h1 id=\"three-ways-ml-engineering-will-grow-in-2019\">Three ways ML Engineering will grow in 2019<\/h1>\n<p>A common warning shared with aspiring Data Scientists is that 90% of the work is about <strong>gathering and cleaning data<\/strong>, or <strong>validating, deploying, and monitoring models<\/strong>. If that is the case, why are 90% of the frameworks and Github repositories (see this <a href=\"https:\/\/github.com\/josephmisiti\/awesome-machine-learning\">list<\/a> for example)focused on model building?<\/p>\n<p>A part of the job that demands so much of a practitioner\u2019s time should have proper tooling support.<\/p>\n<p>Now that many large companies have laid the ground work for best practices when it comes to building ML products, and that many teams are being forced to reinvent the wheel when it comes to building the majority of their modeling pipeline, we are finally at the right moment for <strong>open-source ML Engineering frameworks<\/strong>.<\/p>\n<h2 id=\"1creating-tooling-for-all-data-scientists\">1.Creating tooling for all Data Scientists<\/h2>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/2019-ml-trends-keras.png\"\n         alt=\"What will be the Keras of data exploration?\"\/><figcaption>\n            <p>What will be the Keras of data exploration?<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Amazing libraries such as Keras, Tensorflow, PyTorch, and fast.ai have made it easier than ever to define and train custom models. At the same time, many companies have launched hosted services that complement such libraries by helping with data visualization, cleaning, model serving, and experiment tracking.<\/p>\n<p>The problem with many of these services, is that ML Engineering needs are very use case specific, and often require the flexibility of an extensible open source framework. This is quite similar to Google Cloud offering APIs to call standard computer vision models: it is <strong>valuable for a subset of users, but would never be considered a replacement for Keras<\/strong>. The question now is, what will be the Keras of data exploration and cleaning?<\/p>\n<p>There are many parts to ML Engineering work, and we could see frameworks being extended to cover multiple aspects, or separate solutions winning out in each of these categories. Here are a few domains to watch for:<\/p>\n<ul>\n<li>Data exploration, labeling, and versioning.<\/li>\n<li>Model automated testing, validation, serving, and lifecycle management.<\/li>\n<li>Experiment tracking, hyperparameter optimization, and experimentation tooling in general<\/li>\n<\/ul>\n<p>Startups have started to propose solutions for many of these problems, but none have really helped define standards as widely adapted as Tensorflow and Pytorch are for model building. This is part of a larger trend, the <strong>lack of best practices for ML Engineering<\/strong>.<\/p>\n<h2 id=\"2-defining-a-clear-path-to-production\">2. Defining a clear path to production<\/h2>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/2019-ml-trends-agile.jpeg\"\n         alt=\"What will be the agile of ML? (credit InfoQ)\"\/><figcaption>\n            <p>What will be the agile of ML? (credit <a href=\"https:\/\/www.infoq.com\/articles\/modern-agile-intro\">InfoQ<\/a>)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>More and more developers can train a model to a given level of performance. However, when building a product you usually simply have a goal, with no attached dataset. This requires being able to:<\/p>\n<ol>\n<li>Go from a product goal to formulating a learning problem that will both be feasible, and generate a useful model.<\/li>\n<li>Efficiently gather a dataset, build a simple model, and consistently improve both the model and the dataset (many can improve a model given a standard dataset, but few know how to iterate on a dataset, see <a href=\"https:\/\/blog.insightdatascience.com\/how-to-deliver-on-machine-learning-projects-c8d82ce642b0\">here<\/a> for more)<\/li>\n<li>Decide what it means for a model to actually be ready to be put in front of users.<\/li>\n<li>Monitor deployed models to know when and how to update them.<\/li>\n<\/ol>\n<p>These are crucial skills, that usually make or break a data product, and there is a shortage of resources and best practices to help guide practitioners. When surveyed, this is the type of content that most experienced ML professionals in my network want more of, since it related to the problems they face <strong>every day<\/strong>, which leads me to my last point.<\/p>\n<h2 id=\"3-promoting-resources-that-best-prepare-aspiring-professionals\">3. Promoting resources that best prepare aspiring professionals<\/h2>\n<p>When it comes to recruiting, Hiring Managers of teams all over the valley most often complain that while there is no shortage of people able to train models on a dataset, they need <strong>engineers that can build data driven products<\/strong>.<\/p>\n<p>At the same time, most aspiring Data Scientists and ML Engineers are most excited about training models on provided datasets. This excitement is usually inspired by blogs and courses that have focused on that part of the work, instead of data gathering\/labeling\/cleaning and model deployment.<\/p>\n<p>This leads to a frustrating <strong>disconnect<\/strong> between companies looking to hire and newcomers. While professional Fellowships like <a href=\"http:\/\/insightdatascience.com\/\">Insight Data Science<\/a> have worked on bridging this gap since Data Science started, I am looking forward to more resources that promise to teach ML focusing on the 90% of the field that is <em>not model building<\/em>!<\/p>\n<h1 id=\"looking-forward-2019-resolutions\">Looking forward: 2019 resolutions<\/h1>\n<p>The march towards ML Engineering has already sped up in 2018, and at Insight, we\u2019ve been hard at work to help more people transition to the field successfully (learn more <a href=\"https:\/\/apply.insightdatascience.com\/start\">here<\/a>!). In addition, throughout this year, I will focus more of my writing on the 90% of ML work that have been ignored so far, but that is so crucial to success in industry.<\/p>\n<p>If you\u2019d like to hear more advice, recommendations, and tutorials, feel free to join the mailing list below!<\/p>\n<p>Emmanuel<\/p>\n"},{"title":"How to deliver on Machine Learning projects","link":"https:\/\/www.mlpowered.com\/posts\/how-to-deliver-on-machine-learning-projects\/","pubDate":"Thu, 04 Oct 2018 16:06:59 +0000","author":"mlpoweredapplications@gmail.com (Emmanuel Ameisen)","guid":"https:\/\/www.mlpowered.com\/posts\/how-to-deliver-on-machine-learning-projects\/","description":"<figure><img src=\"https:\/\/www.mlpowered.com\/images\/ml_loop_cover.jpeg\"\n         alt=\"Follow the loop all the way\u00a0up!\"\/><figcaption>\n            <p>Follow the loop all the way\u00a0up!<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p><em>This post was co-authored by<\/em> <a href=\"https:\/\/twitter.com\/EmmanuelAmeisen\"><em>Emmanuel Ameisen<\/em><\/a><em>, Head of AI at<\/em> <a href=\"https:\/\/www.insightdata.ai\/\"><em>Insight Data Science<\/em><\/a> <em>and<\/em> <a href=\"https:\/\/twitter.com\/adampaulcoates\"><em>Adam Coates<\/em><\/a><em>, Operating Partner at<\/em> <a href=\"https:\/\/www.khoslaventures.com\/\"><em>Khosla Ventures<\/em><\/a><em>.<\/em><\/p>\n<p>As Machine Learning (ML) is becoming an important part of every industry, the demand for Machine Learning Engineers (MLE) has grown dramatically. MLEs combine machine learning skills with software engineering knowhow to find high-performing models for a given application and handle the implementation challenges that come up\u200a\u2014\u200afrom building out training infrastructure to preparing models for deployment. New online resources have sprouted in parallel to train engineers to build ML models and solve the various software challenges encountered. However, one of the most common hurdles with new ML teams is maintaining the same level of forward progress that engineers are accustomed to with traditional software engineering.<\/p>\n<p>The most pressing reason for this challenge is that the process of developing new ML models is highly uncertain at the outset. After all, it is difficult to know how well a model will perform by the end of a given training run, let alone what performance could be achieved with extensive tuning or different modeling assumptions.<\/p>\n<p>Many types of professionals face similar situations: software and business developers, startups looking for product-market fit, or pilots maneuvering with limited information. Each of these professions has adapted a common framework to help their teams work productively through the uncertainty: agile\/scrum for software development, \u201clean\u201d startups, and the US Air Force\u2019s <a href=\"https:\/\/en.wikipedia.org\/wiki\/OODA_loop\">OODA loop<\/a>. MLEs can follow a similar framework to cope with uncertainty and deliver great products quickly.<\/p>\n<h3 id=\"the-ml-engineering-loop\">The ML Engineering Loop<\/h3>\n<p>In this article, we\u2019ll describe our conception of the \u201cOODA Loop\u201d of ML: the <strong>ML Engineering Loop<\/strong>, where ML Engineers iteratively<\/p>\n<ol>\n<li>Analyze<\/li>\n<li>Select an approach<\/li>\n<li>Implement<\/li>\n<li>Measure<\/li>\n<\/ol>\n<p>to rapidly and efficiently discover the best models and adapt to the unknown. In addition, we will give <strong>concrete tips<\/strong> for each of these phases, as well as to optimize the process as a whole.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/le_loop.png\"\n         alt=\"The MLE\u00a0Loop\"\/><figcaption>\n            <p>The MLE\u00a0Loop<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Success for an ML team often means delivering a highly performing model within given constraints\u200a\u2014\u200afor example, one that achieves high prediction accuracy, while subject to constraints on memory usage, inference time, and fairness. Performance is defined by <strong>whichever metric is most relevant to the success of your end product<\/strong>, whether that be accuracy, speed, diversity of outputs, etc. For simplicity, we\u2019ve elected to minimize \u201cerror rate\u201d as our performance metric below.<\/p>\n<p>When you are just starting to scope out a new project, you should accurately define success criteria, which you will then translate to model metrics. <strong>In product terms<\/strong>, what level of performance would a service need to be useful? For example, if we are recommending 5 articles to individual users on a news platform, how many of them do we need to be relevant, and how will we define relevance? Given this performance criterion and the data you have, what would be the simplest model you could build?<\/p>\n<blockquote>\n<p>In product terms, what level of performance would a service need to be\u00a0useful?<\/p>\n<\/blockquote>\n<p>The purpose of the ML Engineering Loop is to put a rote mental framework around the development process, simplifying the decision making process to focus exclusively on the most important next steps. As practitioners progress in experience, the process becomes second nature and growing expertise enables rapid shifts between analysis and implementation without hesitation. That said, this framework is still immensely valuable for even the most experienced engineers when uncertainty increases\u200a\u2014\u200afor example, when a model unexpectedly fails to meet requirements, when the teams\u2019 goals are suddenly altered (e.g., the test set is changed to reflect changes in product needs), or as team progress stalls just short of the goal.<\/p>\n<h3 id=\"getting-started\">Getting started<\/h3>\n<p>To bootstrap the loop described below, you should <strong>start with a minimal implementation<\/strong> that has very little uncertainty involved. Usually we want to \u201cget a number\u201d as quickly as possible\u200a\u2014\u200a\u2014 to build up enough of the system so that we can evaluate its performance and begin iterating. This typically means:<\/p>\n<ol>\n<li>Setting up training, development and testing datasets, and<\/li>\n<li>Getting a <a href=\"https:\/\/blog.insightdatascience.com\/always-start-with-a-stupid-model-no-exceptions-3a22314b9aaa\">simple model<\/a> working.<\/li>\n<\/ol>\n<p>For instance, if we\u2019re building a tree detector to survey tree populations in an area, we might use an off-the-shelf training set from a similar Kaggle <a href=\"https:\/\/www.kaggle.com\/c\/inaturalist-challenge-at-fgvc-2017\/data\">competition<\/a>, and a hand-collected set of photos from the target area for development and test sets. We could then run logistic regression on the raw pixels, or run a pre-trained network (like <a href=\"https:\/\/pytorch.org\/tutorials\/beginner\/transfer_learning_tutorial.html\">ResNet<\/a>) on the training images. <strong>The goal here is not to solve the project in one go<\/strong>, but to start our iteration cycle. Below are a few tips to help you do that.<\/p>\n<h4 id=\"tips\">Tips<\/h4>\n<p>On a good test set:<\/p>\n<ul>\n<li>Since the team is aiming to perform well on the test set, the test set is effectively a description of the team\u2019s goal. Therefore, <strong>the test set should reflect the needs of the product or business<\/strong>. For example if you are building an app to detect skin conditions from selfies, feel free to train on any set of images, but make sure that your test set contains images that are as poorly lit and of poor quality as some selfies can be.<\/li>\n<li>Changing the test set alters the team\u2019s goal, so it is helpful to fix the test set early and modify it only to reflect changes in project, product or business goals.<\/li>\n<li>Aim to make the test and development sets large enough that your performance metric will be accurate enough to make good distinctions between models. If the sets are too small, you will end up making decisions based on noisy results.<\/li>\n<li>Similarly, you should try to curate any labels or annotations as much as practical for the development and test sets. A mislabeled test set is about the same as an incorrectly specified product requirement.<\/li>\n<li>It\u2019s helpful to know how well humans perform on the test set, or how well existing \/ competing systems perform. These give you a bound on the <em>optimal error rate<\/em>, the best possible performance you could achieve.<\/li>\n<li>Reaching parity with human test performance is often a good long-term goal for many tasks. In any event, the ultimate goal is to bring test performance as close to our guess for optimal performance as possible.<\/li>\n<\/ul>\n<p>Regarding the development and training set:<\/p>\n<ul>\n<li>The development set is the team\u2019s proxy for test performance that they can use to tune hyper-parameters. As a result, it should be from the same distribution as the test set, but ideally from a disjoint group of users\/inputs to avoid data leakage. A good way to ensure this is to first curate a large pool of samples, then shuffle and split them into development and test sets afterward.<\/li>\n<li>If you imagine that production data will be noisy, however, make sure that you account for that noise in your training set, by using data augmentation or degradation. You cannot expect a model trained exclusively on sharp images to generalize to blurry ones.<\/li>\n<\/ul>\n<p>Once you have an initial prototype, you should check its performance on the training, development and test sets. This marks the end of your first (degenerate) trip around the loop. Take stock of the gap between the test performance and the performance required for a useful product. <strong>Now it\u2019s time to start iterating!<\/strong><\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/loop_analyze.png\"\/>\n<\/figure>\n\n<h3 id=\"analyze\">Analyze<\/h3>\n<h4 id=\"identify-the-performance-bottleneck\">Identify the performance bottleneck<\/h4>\n<p>The analysis phase is like medical diagnosis: you\u2019re equipped with a set of <em>diagnostics<\/em> that you can perform and your goal is to come up with the most likely <em>diagnosis<\/em> for what limits the performance of your model. In practice, there might be many different overlapping issues responsible for the current results, but your objective is to <strong>find the most glaring issues first<\/strong> so that you can resolve them quickly. Don\u2019t get bogged down trying to develop a complete understanding of every shortcoming\u200a\u2014\u200a\u2014 aim instead to understand the biggest factors since many of the smaller issues will change or even disappear as you make improvements to your model.<\/p>\n<p>Below, we list a common set of diagnostics that you will use frequently along with some of the diagnoses. There is at least some art to selecting which diagnostics to run, but as you work your way around the ML Engineering Loop, you will gradually gain intuition for what to try.<\/p>\n<p>A good starting point for every analysis is to look at your training, development, and test performance. We suggest putting code to do this at the end of every experiment to habituate yourself to looking at these numbers every time. <strong>On average, we will have: training error &lt;= development set error &lt;= test set error<\/strong> (if the data in each set follows the same distribution)<strong>.<\/strong> Using the training, development and test error rates from your last experiment, you can quickly see which of these factors is currently a binding constraint. For example, when there is a small gap between training error and development set error then your training error represents the bottleneck to improved performance.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/weight_histograms.jpg\"\n         alt=\"Weight histograms from stackoverflow\"\/><figcaption>\n            <p>Weight histograms from <a href=\"https:\/\/stackoverflow.com\/questions\/42315202\/understanding-tensorboard-weight-histograms\">stackoverflow<\/a><\/p>\n        <\/figcaption>\n<\/figure>\n\n<h4 id=\"diagnostics--diagnoses\">Diagnostics &amp; diagnoses<\/h4>\n<p>If <strong>training set error<\/strong> is the current limiting factor, the following issues might be contributing:<\/p>\n<ol>\n<li>The optimization algorithm (e.g., gradient descent for a deep neural network) is not precisely tuned. Look at the <a href=\"https:\/\/www.dataquest.io\/blog\/learning-curves-machine-learning\/\">learning curve<\/a> to see whether the loss is decreasing. Check whether you are able to overfit a much smaller dataset (e.g., by checking whether the loss decreases when training on a single minibatch or a single example). You can visualize histograms of neuron responses to check whether they are saturating (which might lead to <a href=\"https:\/\/en.wikipedia.org\/wiki\/Vanishing_gradient_problem\">gradient vanishing<\/a>).<\/li>\n<li>The training set may have mislabeled or corrupt data. Manually inspect some training examples at the stage of your code just before they are consumed by the training algorithm.<\/li>\n<li>The model may be too small or inexpressive. For example, if you are using linear regression for a problem that is highly nonlinear, your model is simply incapable of fitting the data well. We say that the model is <em>high bias<\/em> or <em>underfitting<\/em>.<\/li>\n<\/ol>\n<p>If <strong>development set<\/strong> error is the current limiting factor, this may be caused by an analogous set of issues as above:<\/p>\n<ol>\n<li>The model may be too large or expressive, or insufficiently regularized. We say that the model has <em>high variance<\/em> or is <em>overfitting<\/em>.<\/li>\n<li>There is insufficient training data to learn a good model of the underlying pattern.<\/li>\n<li>The distribution of the training data doesn\u2019t match the development or test data distribution.<\/li>\n<li>The hyper-parameters for the model are set poorly. If you\u2019re searching over hyper-parameters (such as feature sets, regularization terms, etc.) it could be that the search method isn\u2019t finding good choices.<\/li>\n<li>The \u201cinductive prior\u201d encoded in your model is a poor match to the data. For example, if you are using a nearest-neighbors method when the data is naturally represented by a linear function, you might generalize poorly unless you have a lot more training data.<\/li>\n<\/ol>\n<p>If <strong>test set<\/strong> error is the current limiting factor, this is often due to the development set being too small or the team overfitting to the development set over the course of many experiments.<\/p>\n<p>For any of the above situations, you can understand the failures of your models by manually <strong>inspecting a random set of examples<\/strong> your model gets wrong (You should generally <em>not do this for the test set<\/em> to avoid \u201ctraining\u201d your system on those examples.).<\/p>\n<ol>\n<li>Try to identify common types of errors <strong>by visualizing the data<\/strong>. Then go through the examples and keep a tally for how often each type of error occurs. For classification, look at a confusion matrix and identify the classes you perform the worst on. You can then focus on resolving the types of errors that account for the most mistakes.<\/li>\n<li>Some examples may be mislabeled or have multiple reasonable labels.<\/li>\n<li>Some examples may be more difficult than others, or may be missing context needed for a good decision. Tagging some examples as \u201cvery hard\u201d might help you direct your efforts to lower hanging fruit if several groups of errors are equally common. Similarly, tagging some as \u201cvery easy\u201d might tip you off to a trivial mistake in your system that\u2019s causing it to miss out on easy cases. This is a bit like estimating the \u201coptimal error rate\u201d on different subsets of the data, then diving deeper on the subset with the most room for progress.<\/li>\n<\/ol>\n<p>Note that many of the diagnoses above have a direct and obvious response. For example, if there\u2019s too little training data, then just get more training data! We still find it useful to mentally separate the analysis stage and selection stage (below) since it is easy to slip into trying random approaches without really digging into the underlying issues. Further, diligently returning to error analysis with an open mind often reveals useful insights that will improve your decisions about what to do.<\/p>\n<p><strong>Examples<\/strong><\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/satellite_picture.png\"\n         alt=\"Satellite data is notoriously noisy, and often requires inspection\"\/><figcaption>\n            <p>Satellite data is notoriously noisy, and often requires inspection<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>At Insight for example, when AI Fellow Jack Kwok was building a segmentation system to help with <a href=\"https:\/\/blog.insightdatascience.com\/deep-learning-for-disaster-recovery-45c8cd174d7a\">disaster recovery<\/a>, he noticed that while his segmentation model performed well on his training set of satellite imagery, it performed poorly on the development set, which contained cities that were flooded by hurricanes. The reason was that the hurricane images were of lower quality and blurrier than the training data. Adding an extra augmentation step to the training pipeline, that applied blurring to images helped reduce the gap between training and development performance.<\/p>\n<p>For speech recognition systems, an in-depth error analysis on the development set may reveal that speakers with strong accents that are very different from the majority of users represents a disproportionate number of errors. One could then check the training set to see whether similar accents are well-represented, correctly labeled, and successfully fit by the training algorithm. Underrepresentation or mis-labeling of some user groups is one example of <a href=\"https:\/\/blog.algorithmia.com\/racial-bias-in-facial-recognition-software\/\"><em>bias in machine learning<\/em><\/a><em>.<\/em> For Google\u2019s speech systems, one solution was to actively <a href=\"https:\/\/www.theverge.com\/2016\/8\/17\/12402176\/google-voice-recognition-accents-reddit\">solicit<\/a> additional training data from users with strong accents.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/loop_select.png\"\/>\n<\/figure>\n\n<h3 id=\"select-approach\">Select Approach<\/h3>\n<h4 id=\"find-the-simplest-way-to-address-the-bottleneck\">Find the simplest way to address the bottleneck<\/h4>\n<p>After your analysis, you will have a good sense of what kind of errors your model is making and what factors are holding back performance. For a given diagnosis, there might be several potential solutions and the next step is to enumerate and <strong>prioritize them<\/strong>.<\/p>\n<p>Some of the diagnoses above lead directly to potential solutions. For example, if your optimizer appears to be mis-tuned, you could try different step sizes, or consider switching optimization algorithms altogether. If the training dataset is too small, gathering more training data might be a reasonably quick and easy solution.<\/p>\n<p>We suggest that ML engineers and their teams enumerate as many ideas that might work, and then bias toward <strong>simple, fast solutions<\/strong>. If an existing solution might work (e.g., using another optimization algorithm already implemented in your toolkit), start with that. While more sophisticated approaches might look like they will get more done in one swing, we often find that improvements from many quick iterations swamps the gains from tinkering with state-of-art or bespoke solutions that take longer to get right. If you have the choice between labeling 1000 data points or researching a cutting edge unsupervised learning method, we think you should collect and label the data. If you could get started with some simple heuristic features, go for it.<\/p>\n<blockquote>\n<p>Improvements from many quick iterations swamps the gains from tinkering with state-of-art or bespoke solutions that take longer to get\u00a0right<\/p>\n<\/blockquote>\n<h4 id=\"tips-1\">Tips<\/h4>\n<p>Depending on your diagnosis, here are a number of common sets of solutions.<\/p>\n<p>If you need to tune the optimizer to better fit the data:<\/p>\n<ul>\n<li>For numerical optimizers, try adjusting the learning rate or momentum settings. Starting with a small momentum (0.5) is usually easiest to get working.<\/li>\n<li>Try different initialization strategies, or start from a pre-trained model.<\/li>\n<li>Try a type of model that is easier to tune. In deep learning, <a href=\"https:\/\/arxiv.org\/abs\/1512.03385\">residual networks<\/a> or networks with <a href=\"https:\/\/arxiv.org\/abs\/1502.03167\">batch normalization<\/a> may be simpler to train.<\/li>\n<\/ul>\n<p>If the model is unable to fit the training data well:<\/p>\n<ul>\n<li>Use a larger or more expressive model class. For example, when using decision trees you could make the trees deeper.<\/li>\n<li>Check the examples the model gets wrong on the training set for labeling errors, missing fields, etc. Investing time in training data cleanup can improve results significantly.<\/li>\n<\/ul>\n<p>If the model isn\u2019t generalizing to the development set:<\/p>\n<ul>\n<li>Add more training data. Note that it may be important to focus on <strong>adding training examples similar to classes of errors seen in the development set<\/strong>.<\/li>\n<li>Augment your data with novel samples generated from real training examples. For example, if you notice your tree detector consistently performs poorly on foggy images, play with OpenCV to add an augmentation step that makes your images look a bit foggy.<\/li>\n<li>Search over a wider or finer-grained range of hyper-parameters to ensure you find the model that performs best on the development set.<\/li>\n<li>Try a different form of regularization (such as weight decay, dropout for neural networks, or pruning for decision trees).<\/li>\n<li>Try a different model class. A different type of model can alter how well you fit your data and how well it generalizes, so it is difficult to know when this will work. One advantage of deep learning is that there is a wide range of \u201cbuilding block\u201d neural network components you can easily try out. If you\u2019re using a traditional model (such as a decision tree or gaussian mixture model), switching model classes is much more involved. If the assumptions embodied by the new model are more correct, the change might help\u200a\u2014\u200abut it may be better to try easier things first.<\/li>\n<\/ul>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/loop_implement.png\"\/>\n<\/figure>\n\n<h3 id=\"implement\">Implement<\/h3>\n<h4 id=\"build-only-what-you-need-to-build-and-do-itfast\">Build only what you need to build, and do it\u00a0fast<\/h4>\n<p>You know what to try, and you\u2019ve made it simple for yourself, now it\u2019s just a matter of implementing\u2026 \u201cjust\u201d. The goal of this phase is to <strong>prototype<\/strong> rapidly so that you can <strong>measure<\/strong> the results, <strong>learn<\/strong> from them, and go back around the cycle quickly. For that reason, we recommend focusing on building just what\u2019s needed for your current experiment. Note that while your goal is to learn quickly rather than polish everything, your work still needs to be <strong>correct<\/strong> and so you should check that the code works as expected frequently.<\/p>\n<h4 id=\"tips-2\">Tips<\/h4>\n<blockquote>\n<p>Most people overestimate the cost associated with gathering and labeling data, and underestimate the hardship of solving problems in a data starved environment.<\/p>\n<\/blockquote>\n<p>When gathering and labeling data:<\/p>\n<ul>\n<li><strong>Regularly look at your data<\/strong>. Look at the raw data, look at it after it is pre-processed, look at the labels. We can\u2019t stress this enough! You can catch many errors just by keeping an eye on your data at each step of your pipeline. Every session, Insight AI Fellows catch bugs related to data cleaning, bounding box coordinates, and segmentation masks when solving computer vision problems.<\/li>\n<li>Labeling and cleaning data is a common task. Most people overestimate the cost associated with gathering and labeling data, and underestimate the hardship of solving problems in a data starved environment. Once you get in a rhythm, you can easily label <a href=\"https:\/\/petewarden.com\/2017\/04\/26\/how-to-label-images-quickly\/\">20 images per minute<\/a> for classification. Would you rather spend an hour labeling images, and an hour to solve an easy classification problem with a dataset of 1200 images, or spend 3 weeks trying to get a model to learn from 5 examples?<\/li>\n<\/ul>\n<p>When you code up a new model, start from a similar existing implementation. Many research papers now have freely available code\u200a\u2014\u200aso try to get code before reimplementing an idea from a paper as there are often undocumented details. This will save you hours\/days of work. If possible, for any problem, we recommend going through these successive steps:<\/p>\n<ol>\n<li>Find an implementation of a model solving a similar problem.<\/li>\n<li>Reproduce the implementation locally in the conditions of the existing model (same dataset and hyperparameters).<\/li>\n<li>Slowly tweak the implementation of the model and the data pipeline to match your needs.<\/li>\n<li>Rewrite any parts needed.<\/li>\n<\/ol>\n<p>Write <a href=\"https:\/\/medium.com\/@keeper6928\/how-to-unit-test-machine-learning-code-57cf6fd81765\">tests<\/a> to check whether your gradients, tensor values, and input data and labels are properly formatted. Do this as you are setting up your model initially, that way if you catch an error once, you will never have to deal with it again.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/loop_measure.png\"\/>\n<\/figure>\n\n<h3 id=\"measure\">Measure<\/h3>\n<p>Print out your test results and any other metrics (e.g., production constraints) you need to decide whether you\u2019re ready to ship.<\/p>\n<p>If your performance improved somewhat, you might be on the right track. In this case, now might be a good time to clean up any components you know are working well and make sure that the experiment can be reproduced by others in your team.<\/p>\n<p>On the other hand, if performance became worse or didn\u2019t improve enough, you\u2019ll need to decide whether to try again (going back to the analysis phase) or to abandon your current idea. These decisions are easier to make <strong>if each cycle of the ML Loop is relatively cheap<\/strong>: you haven\u2019t put too much energy into making your code perfect, and another attempt won\u2019t take too long\u200a\u2014\u200a\u2014 so you can decide what to do based on the risk and value of the idea instead of sunk cost.<\/p>\n<h4 id=\"tips-3\">Tips<\/h4>\n<ul>\n<li>Useful performance metrics include accuracy and loss for the ML side, and business value metrics (how often do we recommend the right article amongst our top 5?) Remember that the latter metrics are what matters in the end, since they are the ones determining the usefulness of what you are building. If your test metric (as optimized by your ML code) is diverging from your business metric, the end of this measurement cycle is a good time to stop and consider changing your optimization criterion or test set.<\/li>\n<li>Since you\u2019ll print out your metrics at the end of each development loop regardless, it\u2019s often a convenient place to compute other metrics as well that will help you during the analysis phase or help decide whether to continue with the current idea at all.<\/li>\n<li>You\u2019ll often end up building a \u201cdashboard\u201d with your test metric and business metrics as well as other useful data that you can see at the end of every experiment. This is especially useful when working in teams.<\/li>\n<\/ul>\n<h3 id=\"optimizing-theloop\">Optimizing the\u00a0Loop<\/h3>\n<p>The ML Engineering Loop above will help you make methodical progress toward a better model despite the inherent uncertainty of the task. It is not at all magical, unfortunately\u200a\u2014\u200ayou will need to develop your ability to make good choices in each stage, like identifying the performance bottleneck, deciding which solutions to try, how to implement them correctly, and how to measure performance for your application. You will also need to become adept at iterating quickly. Thus, you should also take time to think about improving the <em>quality<\/em> and <em>speed<\/em> of iteration so that you can make maximum progress during each cycle and you can finish many iterations quickly.<\/p>\n<p><strong>Tips<\/strong><\/p>\n<ul>\n<li>If your analysis stage is slowing you down, create a script that summarizes the results of an experiment, collects errors from the training and dev sets, and formats them nicely. This \u201cdashboard\u201d of often-used diagnostic outputs can help you overcome that moment of thinking \u201cUgh! I have to run that analysis by hand again\u2026 I\u2019ll just try this random solution instead.\u201d<\/li>\n<li>If you feel like you\u2019re hand-wringing about what to try, just pick <em>one.<\/em> Trying to do too many things at once slows you down. You can sometimes come back to try another idea while your experiment is running!<\/li>\n<li>Collecting data is a common way to get better performance. If getting a lot more data sounds painful, but would really make a difference, it might make sense to invest in tools to make data easier to collect, clean and label.<\/li>\n<li>If you\u2019re feeling stuck on diagnosing the bottleneck or selecting a good model to try next, consider reaching out to experts. Domain experts can often provide useful insights during error analysis (e.g., pointing out subtle distinctions that make some cases hard or easy), while research papers or experienced ML practitioners might have creative solutions to add to your list of things to try (and will be better able to help you if you can share your detailed analysis so far).<\/li>\n<li>Good implementation skills are important, and coding hygiene can prevent bugs. That said, since a large fraction of ideas will fail, feel free to hack your experiment code with abandon and throw away failed code while you\u2019re in the process of iterating. Once you feel comfortable that you\u2019ve made useful progress, you can impose some discipline and clean up before the next loop.<\/li>\n<li>If your experiments are taking too long, consider spending some time looking for optimizations to your code. Or talk to a systems expert about ways to make your training faster. When in doubt, buying an upgraded GPU or running more experiments in parallel is a time-honored solution to the \u201churry up and wait\u201d problem of ML experimentation.<\/li>\n<\/ul>\n<p>As with other decisions, only work on these items if they\u2019ll address a current pain point. Some teams spend too much time building the \u201cperfect\u201d framework only to discover that the real headaches are somewhere else.<\/p>\n<h3 id=\"conclusion\">Conclusion<\/h3>\n<p>ML projects are inherently uncertain and the approach we recommend above is designed to provide you a handrail as a guide. While it\u2019s hard to hold yourself accountable to hitting a specific accuracy goal when the fate of your experiment is uncertain, you can at least hold yourself accountable to finish that error analysis, draw up a list of ideas, code them, and see how it works. In both Emmanuel\u2019s and Adam\u2019s experience, resisting the call of the shiny things, and relentlessly focusing on incremental progress can lead to extraordinary results in both research and application. This has transformed teams, and allowed countless Fellows to deliver on cutting-edge projects.<\/p>\n<p>If you\u2019d like to know more, please feel free to reach out to <a href=\"http:\/\/twitter.com\/mlpowered\">Emmanuel<\/a> or <a href=\"https:\/\/twitter.com\/adampaulcoates\">Adam<\/a>.<\/p>\n"},{"title":"Building an image search service from scratch","link":"https:\/\/www.mlpowered.com\/posts\/image-search\/","pubDate":"Thu, 05 Jul 2018 15:17:26 +0000","author":"mlpoweredapplications@gmail.com (Emmanuel Ameisen)","guid":"https:\/\/www.mlpowered.com\/posts\/image-search\/","description":"<figure><img src=\"https:\/\/www.mlpowered.com\/images\/image_search_cover.jpeg\"\n         alt=\"Teaching computers to look at pictures the way we\u00a0do\"\/><figcaption>\n            <p>Teaching computers to look at pictures the way we\u00a0do<\/p>\n        <\/figcaption>\n<\/figure>\n\n<h3 id=\"why-similarity-search\">Why similarity search?<\/h3>\n<p><em>An image is worth a thousand words, and even more lines of code.<\/em><\/p>\n<p>Many products <strong>fundamentally appeal to our perception<\/strong>. When browsing through outfits on clothing sites, looking for a vacation rental on Airbnb, or choosing a pet to adopt, the way something looks is often an important factor in our decision. The way we perceive things is a strong predictor of what kind of items we will like, and therefore a valuable quality to measure.<\/p>\n<p>However, making computers understand images the way humans do has been a computer science challenge for quite some time. Since 2012, Deep Learning has slowly started overtaking classical methods such as <a href=\"https:\/\/en.wikipedia.org\/wiki\/Histogram_of_oriented_gradients\">Histograms of Oriented Gradients<\/a> (HOG) in perception tasks like image classification or object detection. One of the main reasons often credited for this shift is deep learning\u2019s ability to automatically <strong>extract meaningful representations<\/strong> when trained on a large enough dataset.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/pinterest_search.gif\"\n         alt=\"Visual search at Pinterest\"\/><figcaption>\n            <p>Visual search at Pinterest<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>This is why many teams\u200a\u2014\u200alike at <a href=\"https:\/\/medium.com\/@Pinterest_Engineering\/introducing-a-new-way-to-visually-search-on-pinterest-67c8284b3684\">Pinterest<\/a>, <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2015\/09\/17\/deep-style\/\">StitchFix<\/a>, and <a href=\"http:\/\/code.flickr.net\/2017\/03\/07\/introducing-similarity-search-at-flickr\/\">Flickr<\/a>\u200a\u2014\u200astarted using Deep Learning to learn representations of their images, and <strong>provide recommendations<\/strong> based on the content users find visually pleasing. Similarly, Fellows at <a href=\"http:\/\/insightdatascience.com\/\">Insight<\/a> have used deep learning to build models for applications such as helping people find cats to adopt, recommending sunglasses to buy, and searching for art styles.<\/p>\n<p>Many recommendation systems are based on <a href=\"https:\/\/en.wikipedia.org\/wiki\/Collaborative_filtering\">collaborative filtering<\/a>: leveraging user correlations to make recommendations (\u201cusers that liked the items you have liked have also liked\u2026\u201d). However, these models require a <strong>significant amount of data<\/strong> to be accurate, and <a href=\"https:\/\/en.wikipedia.org\/wiki\/Cold_start_%28computing%29\">struggle<\/a> to handle <strong>new items<\/strong> that have not yet been viewed by anyone. Item representation can be used in what\u2019s called <a href=\"https:\/\/en.wikipedia.org\/wiki\/Recommender_system#Content-based_filtering\">content-based<\/a> recommendation systems, which do not suffer from the problem above.<\/p>\n<p>In addition, these representations allow consumers to <strong>efficiently search<\/strong> photo libraries for images that are similar to the selfie they just took (querying by image), or for photos of particular items such as cars (querying by text). Common examples of this include Google Reverse Image Search, as well as Google Image Search.<\/p>\n<p>Based on our experience providing technical mentorship for many semantic understanding projects, we wanted to write a tutorial on how you would go about <strong>building your own representations<\/strong>, both for image and text data, and <strong>efficiently do similarity search<\/strong>. By the end of this post, you should be able to build a quick semantic search model from scratch, no matter the size of your dataset.<\/p>\n<p><strong>This post is accompanied by an annotated<\/strong> <a href=\"http:\/\/insight.streamlit.io\/0.13.3-8ErS\/index.html?id=QAKzY9mLjr4WbTCgxz3XBX\"><strong>notebook<\/strong><\/a> <strong>using<\/strong> <a href=\"http:\/\/streamlit.io\/\"><strong>streamlit<\/strong><\/a> <strong>and a self-standing<\/strong> <a href=\"https:\/\/github.com\/hundredblocks\/semantic-search\"><strong>codebase<\/strong><\/a> <strong>demonstrating and applying all these techniques. Feel free to run the code and follow along!<\/strong><\/p>\n<h3 id=\"whats-ourplan\">What\u2019s our\u00a0plan?<\/h3>\n<h4 id=\"a-break-to-chat-about-optimization\">A break to chat about optimization<\/h4>\n<p>In machine learning, just like in software engineering, there are many ways to tackle a problem, each with different tradeoffs. If we are doing research or local prototyping, we can get away with very inefficient solutions. But if we are building an image similarity search engine that needs to be maintainable and scalable, we have to consider both how we can <strong>adapt to data evolution<\/strong>, and <strong>how fast our model can run<\/strong>.<\/p>\n<p>Let\u2019s imagine a few approaches:<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/approach_1.png\"\n         alt=\"Workflow for approach\u00a01\"\/><figcaption>\n            <p>Workflow for approach\u00a01<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>1\/ We build an end-to-end model that is trained on all our images to take an image as an input, and output a similarity score over all of our images. Predictions happen quickly (one forward pass), but we would need to <strong>train a new model<\/strong> every time we add a new image. We would also quickly reach a state with so many classes that it would be extremely <strong>hard to optimize<\/strong> it correctly. This approach is fast, but does not scale to large datasets. In addition, we would have to label our dataset by hand with image similarities, which could be extremely time consuming.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/approach_2.png\"\n         alt=\"Workflow for approach\u00a02\"\/><figcaption>\n            <p>Workflow for approach\u00a02<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>2\/ Another approach is to build a model that takes in two images, and outputs a pairwise similarity score between 0 and 1 (<a href=\"https:\/\/www.cs.cmu.edu\/~rsalakhu\/papers\/oneshot1.pdf\">Siamese Networks<\/a>[PDF], for example). These models are accurate for large datasets, but lead to another scalability issue. We usually want to find a similar image by <strong>looking through a vast collection of images<\/strong>, so we have to run our similarity model once for each image pair in our dataset. If our model is a CNN, and we have more than a dozen images, this becomes too slow to even be considered. In addition, this only works for image similarity, not text search. This method scales to large datasets, but is slow.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/approach_3.png\"\n         alt=\"Workflow for approach\u00a03\"\/><figcaption>\n            <p>Workflow for approach\u00a03<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>3\/ There is a simpler method, which is similar to <a href=\"https:\/\/en.wikipedia.org\/wiki\/Word_embedding\">word embeddings<\/a>. If we find an <strong>expressive vector representation, or embedding<\/strong> for images, we can then calculate their similarity by looking at <strong>how close their vectors are to each other<\/strong>. This type of search is a common problem that is well studied, and many libraries implement fast solutions (we will use <a href=\"https:\/\/github.com\/spotify\/annoy\">Annoy<\/a> here). In addition, if we calculate these vectors for all images in our database ahead of time, this approach is both fast (one forward pass, and an efficient similarity search), and scalable. Finally, if we manage to find <strong>common embeddings<\/strong> for our images and our words, we could use them to do text to image search!<\/p>\n<p>Because of its simplicity and efficiency, the third method will be the focus of this post.<\/p>\n<h4 id=\"how-do-we-getthere\">How do we get\u00a0there?<\/h4>\n<p>So, how do we actually use <strong>deep learning representations<\/strong> to create a <strong>search engine?<\/strong><\/p>\n<p>Our final goal is to have a search engine that can take in images and output either similar images or tags, and take in text and output similar words, or images. To get there, we will go through three successive steps:<\/p>\n<ul>\n<li>Searching for <strong>similar images to an input image<\/strong> (Image \u2192 Image)<\/li>\n<li>Searching for <strong>similar words to an input word<\/strong> (Text \u2192 Text)<\/li>\n<li>Generating <strong>tags for images<\/strong>, and <strong>searching images using tex<\/strong>t (Image \u2194 Text)<\/li>\n<\/ul>\n<p>To do this, we will use <strong>embeddings<\/strong>, vector representations of images and text. Once we have embeddings, searching simply becomes a matter of finding vectors close to our input vector.<\/p>\n<p>The way we find these is by calculating the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Cosine_similarity\">cosine similarity<\/a> between our image embedding, and embeddings for other images. Similar images will have similar embeddings, meaning a <strong>high cosine similarity between embeddings<\/strong>.<\/p>\n<p>Let\u2019s start with a dataset to experiment with.<\/p>\n<h3 id=\"dataset\">Dataset<\/h3>\n<h4 id=\"images\">Images<\/h4>\n<p>Our image dataset consists of a total of a <strong>1000 images<\/strong>, divided in 20 classes with 50 images for each. This dataset can be found <a href=\"http:\/\/vision.cs.uiuc.edu\/pascal-sentences\/\">here<\/a>. Feel free to use the script in the linked code to automatically download all image files. <em>Credit to Cyrus Rashtchian, Peter Young, Micah Hodosh, and Julia Hockenmaier for the dataset.<\/em><\/p>\n<p>This dataset contains a category and a set of captions for every image. To make this problem harder, and to show how well our approach generalizes, we will <strong>only use the categories<\/strong>, and disregard the captions. We have a total of 20 classes, which I\u2019ve listed out below:<\/p>\n<p><code>aeroplane<\/code> <code>bicycle<\/code> <code>bird<\/code> <code>boat<\/code> <code>bottle<\/code> <code>bus<\/code> <code>car<\/code> <code>cat<\/code> <code>chair<\/code> <code>cow<\/code> <code>dining_table<\/code> <code>dog<\/code> <code>horse<\/code> <code>motorbike<\/code> <code>person<\/code> <code>potted_plant<\/code> <code>sheep<\/code> <code>sofa<\/code> <code>train<\/code> <code>tv_monitor<\/code><\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/dataset_example.png\"\n         alt=\"Image examples. As we can see, the labels are quite\u00a0noisy.\"\/><figcaption>\n            <p>Image examples. As we can see, the labels are quite\u00a0noisy.<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>We can see our labels are pretty <strong>noisy<\/strong>: many photos contain multiple categories, and the label is not always from the most prominent one. For example, on the bottom right, the image is labeled <code>chair<\/code> and not <code>person<\/code> even though 3 people stand in the center of the image, and the chair is barely visible.<\/p>\n<h4 id=\"text\">Text<\/h4>\n<p>In addition, we load word embeddings that have been pre-trained on Wikipedia (this tutorial will use the ones from the <a href=\"https:\/\/nlp.stanford.edu\/projects\/glove\/\">GloVe<\/a> model). We will use these vectors to incorporate text to our semantic search. For more information on how these word vectors work, see <a href=\"https:\/\/blog.insightdatascience.com\/how-to-solve-90-of-nlp-problems-a-step-by-step-guide-fda605278e4e\">Step 7<\/a> of our NLP tutorial.<\/p>\n<h3 id=\"image--image\">Image -&gt;\u00a0Image<\/h3>\n<p><em>Starting simple<\/em><\/p>\n<p>We are now going to load a model that was <strong>pre-trained<\/strong> on a large data set (<a href=\"http:\/\/www.image-net.org\/\">Imagenet<\/a>), and is freely available online. We use VGG16 here, but this approach would work with any recent CNN architecture. We use this model to generate <strong>embeddings<\/strong> for our images.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/vgg16.jpeg\"\n         alt=\"VGG16 (credit to Data Wow\u00a0Blog)\"\/><figcaption>\n            <p>VGG16 (credit to Data Wow\u00a0Blog)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>What do we mean by generating embeddings? We will use our pre-trained model <strong>up to the penultimate layer<\/strong>, and store the value of the activations. In the image below, this is represented by the embedding layer highlighted in green, which is before the final classification layer.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/embedding_layer.png\"\n         alt=\"For our embeddings, we use the layer before the final classification layer.\"\/><figcaption>\n            <p>For our embeddings, we use the layer before the final classification layer.<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Once we\u2019ve used the model to generate image features, we can then store them to disk and re-use them <strong>without needing to do inference again<\/strong>! This is one of the reasons that embeddings are so popular in practical applications, as they allow for huge efficiency gains. On top of storing them to disk, we will build a <strong>fast index<\/strong> of the embeddings using <a href=\"https:\/\/github.com\/spotify\/annoy\">Annoy<\/a>, which will allow us to very quickly find the nearest embeddings to any given embedding.<\/p>\n<p>Below are our embeddings. Each image is now represented by a sparse vector of size 4096. <em>Note: the reason the vector is sparse is that we have taken the values after the activation function, which zeros out negatives.<\/em><\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/image_embeddings.png\"\n         alt=\"Image Embeddings\"\/><figcaption>\n            <p>Image Embeddings<\/p>\n        <\/figcaption>\n<\/figure>\n\n<h4 id=\"using-our-embeddings-to-search-throughimages\"><strong>Using our embeddings to search through\u00a0images<\/strong><\/h4>\n<p>We can now simply take in an image, get its embedding, and look in our fast index to find similar embeddings, and thus similar images.<\/p>\n<p>This is especially useful since image labels are often <strong>noisy<\/strong>, and there is more to an image than its label.<\/p>\n<p>For example, in our dataset, we have both a class <code>cat<\/code>, and a class <code>bottle<\/code>.<\/p>\n<p>Which class do you think this image is labeled as?<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/cat_or_bottle.png\"\n         alt=\"Cat or Bottle? (Image rescaled to 224x224, which is what the neural network\u00a0sees.)\"\/><figcaption>\n            <p>Cat or Bottle? (Image rescaled to 224x224, which is what the neural network\u00a0sees.)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>The correct answer is <strong>bottle<\/strong>\u00a0\u2026 This is an actual issue that comes up often in real datasets. Labeling images as unique categories is quite limiting, which is why we hope to use more nuanced representations. Luckily, this is exactly what <strong>deep learning is good at<\/strong>!<\/p>\n<p>Let\u2019s see if our image search using embeddings does better than human labels.<\/p>\n<p>Searching for similar images to<code>dataset\/bottle\/2008_000112.jpg<\/code>:<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/search_1.png\"\/>\n<\/figure>\n\n<p>Great\u200a\u2014\u200awe mostly get more images of <strong>cats<\/strong>, which seems very reasonable! Our pre-trained network has been trained on a wide variety of images, including cats, and so it is able to accurately find similar images, even though it has never been trained on this particular dataset before.<\/p>\n<p>However, one image in the middle of the bottom row shows a shelf of bottles. This approach perform wells to find similar images, in general, but sometimes we are only interested in <strong>part of the image<\/strong>.<\/p>\n<p>For example, given an image of a cat and a bottle, we might be only interested in similar cats, not similar bottles.<\/p>\n<h4 id=\"semi-supervised-search\">Semi-supervised search<\/h4>\n<p>A common approach to solve this issue is to use an <strong>object detection<\/strong> model first, detect our cat, and do image search on a cropped version of the original image.<\/p>\n<p>This adds a huge computing overhead, which we would like to avoid if possible.<\/p>\n<p>There is a simpler \u201chacky\u201d approach, which consists of <strong>re-weighing<\/strong> the activations. We do this by loading the last layer of weights we had initially discarded, and only use the weights tied to the index of the class we are looking for to re-weigh our embedding. This cool trick was initially brought to my attention by <a href=\"http:\/\/insightdatascience.com\/\">Insight<\/a> Fellow <a href=\"https:\/\/www.linkedin.com\/in\/daweonryu\/\">Daweon Ryu<\/a>. For example, in the image below, we use the weights of the <code>Siamese cat<\/code> class to re-weigh the activations on our dataset (highlighted in green). Feel free to check out the attached notebook to see the implementation details.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/weighted_embedding.png\"\n         alt=\"The hack to get weighted embeddings. The classification layer is shown for reference only.\"\/><figcaption>\n            <p>The hack to get weighted embeddings. The classification layer is shown for reference only.<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Let\u2019s examine how this works by weighing our activations according to class <code>284<\/code> in Imagenet, <code>Siamese cat<\/code>.<\/p>\n<p>Searching for similar images to<code>dataset\/bottle\/2008_000112.jpg<\/code> using weighted features\u2026<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/search_2.png\"\/>\n<\/figure>\n\n<p>We can see that the search has been biased to look for <strong>Siamese cat-like things<\/strong>. We no longer show any bottles, which is great. You might however notice that our last image is of a sheep! This is very interesting, as biasing our model has led to a <strong>different kind of error<\/strong>, which is more appropriate for our current domain.<\/p>\n<p>We have seen we can search for similar images in a <strong>broad<\/strong> way, or by <strong>conditioning on a particular class<\/strong> our model was trained on.<\/p>\n<p>This is a great step forward, but since we are using a model <strong>pre-trained on Imagenet<\/strong>, we are thus limited to the 1000 <strong>Imagenet classes<\/strong>. These classes are far from all-encompassing (they lack a category for people, for example), so we would ideally like to find something more <strong>flexible.<\/strong> In addition, what if we simply wanted to search for cats <strong>without providing an input image?<\/strong><\/p>\n<p>In order to do this, we are going to use more than simple tricks, and leverage a model that can understand the semantic power of words.<\/p>\n<h3 id=\"text--text\">Text -&gt;\u00a0Text<\/h3>\n<p><em>Not so different after all<\/em><\/p>\n<h4 id=\"embeddings-fortext\">Embeddings for\u00a0text<\/h4>\n<p>Taking a detour to the world of natural language processing (NLP), we can use a similar approach to <strong>index and search for words<\/strong>.<\/p>\n<p>We loaded a set of pre-trained vectors from <a href=\"https:\/\/nlp.stanford.edu\/projects\/glove\/\">GloVe<\/a>, which were obtained by crawling through all of Wikipedia and learning the semantic relationships between words in that dataset.<\/p>\n<p>Just like before, we will create an index, this time containing all of the GloVe vectors. Then, we can <strong>search our embeddings<\/strong> for similar words.<\/p>\n<p>Searching for <code>said<\/code>, for example, returns this list of [<code>word<\/code>, <code>distance<\/code>]:<\/p>\n<ul>\n<li><code>['said', 0.0]<\/code><\/li>\n<li><code>['told', 0.688713550567627]<\/code><\/li>\n<li><code>['spokesman', 0.7859575152397156]<\/code><\/li>\n<li><code>['asked', 0.872875452041626]<\/code><\/li>\n<li><code>['noting', 0.9151610732078552]<\/code><\/li>\n<li><code>['warned', 0.915908694267273]<\/code><\/li>\n<li><code>['referring', 0.9276227951049805]<\/code><\/li>\n<li><code>['reporters', 0.9325974583625793]<\/code><\/li>\n<li><code>['stressed', 0.9445104002952576]<\/code><\/li>\n<li><code>['tuesday', 0.9446316957473755]<\/code><\/li>\n<\/ul>\n<p>This seems very reasonable, most words are quite similar in meaning to our original word, or represent an appropriate concept. The last result (<code>tuesday<\/code>) also shows that this model is far from perfect, but it will get us started. Now, let\u2019s try to incorporate both words and images in our model.<\/p>\n<h4 id=\"a-sizableissue\">A sizable\u00a0issue<\/h4>\n<p>Using the distance between embeddings as a method for search is a pretty general method, but our representations for words and images seem <strong>incompatible<\/strong>. The embeddings for images are of size 4096, while those for words are of size 300\u200a\u2014\u200ahow could we use one to search for the other? In addition, even if both embeddings were the same size, they were trained in a completely different fashion, so it is incredibly unlikely that images and related words would happen to have the same embeddings randomly. We need to train a <strong>joint model<\/strong>.<\/p>\n<h3 id=\"image--text\">Image &lt;-&gt;\u00a0Text<\/h3>\n<p><em>Worlds collide<\/em><\/p>\n<p>Let\u2019s now create a <strong>hybrid<\/strong> model that can go from words to images and vice versa.<\/p>\n<p>For the first time in this tutorial, we will actually be training our own model, drawing inspiration from a great paper called <a href=\"https:\/\/papers.nips.cc\/paper\/5204-devise-a-deep-visual-semantic-embedding-model\">DeViSE<\/a>. We will not be re-implementing it exactly, though we will heavily lean on its main ideas. (For another slightly different take on the paper, check out fast.ai\u2019s implementation in their <a href=\"http:\/\/course.fast.ai\/lessons\/lesson11.html\">lesson 11<\/a>.)<\/p>\n<p>The idea is to combine both representations by re-training our image model and <strong>changing the type of its labels<\/strong>.<\/p>\n<p>Usually, image classifiers are trained to pick a category out of many (1000 for Imagenet). What this translates to is that\u200a\u2014\u200ausing the example of Imagenet\u200a\u2014\u200athe last layer is a vector of size 1000 representing the <strong>probability of each class<\/strong>. This means our model has no semantic understanding of which classes are similar to others: classifying an image of a <code>cat<\/code> as a <code>dog<\/code> results in as much of an error as classifying it as an <code>airplane<\/code>.<\/p>\n<p>For our hybrid model, we replace this last layer of our model with the <strong>word vector of our category<\/strong>. This allows our model to learn to map the semantics of images to the semantics of words, and means that similar classes will be closer to each other (as the word vector for <code>cat<\/code> is closer to <code>dog<\/code> than <code>airplane<\/code>). Instead of a target of size 1000, with all zeros except for a one, we will predict a <strong>semantically rich word vector<\/strong> of size 300.<\/p>\n<p>We do this by adding two dense layers:<\/p>\n<ul>\n<li>One intermediate layer of size 2000<\/li>\n<li>One output layer of size 300 (the size of GloVe\u2019s word vectors).<\/li>\n<\/ul>\n<p>Here is what the model looked like when it was trained on Imagenet:<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/vgg16.jpeg\"\/>\n<\/figure>\n\n<p>Here is what it looks like now:<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/vgg16_custom.jpeg\"\/>\n<\/figure>\n\n<h4 id=\"training-themodel\">Training the\u00a0model<\/h4>\n<p>We then re-train our model on a training split of our dataset, to learn to <strong>predict the word vector<\/strong> associated with the label of the image. For an image with the category cat for example, we are trying to predict the 300-length vector associated with cat.<\/p>\n<p>This training takes a bit of time, but is still much faster than on Imagenet. For reference, it took about 6\u20137 hours on my laptop that has <strong>no GPU<\/strong>.<\/p>\n<p>It is important to note how ambitious this approach is. The training data we are using here (80% of our dataset, so 800 images) is minuscule, compared to usual datasets (Imagenet has <strong>a million<\/strong> images, <strong>3 orders of magnitude more<\/strong>). If we were using a traditional technique of training with categories, we would not expect our model to perform very well on the test set, and would certainly not expect it to perform at all on completely new examples.<\/p>\n<p>Once our model is trained, we have our GloVe word index from above, and we build a new fast index of our image features by running all images in our dataset through it, saving it to disk.<\/p>\n<h4 id=\"tagging\">Tagging<\/h4>\n<p>We can now easily extract tags from any image by simply feeding our image to our trained network, saving the vector of size 300 that comes out of it, and finding the closest words in our index of English words from GloVe. Let\u2019s try with this image\u200a\u2014\u200ait\u2019s in the <code>bottle<\/code> class, though it contains a variety of items.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/fridge_example.png\"\/>\n<\/figure>\n\n<p>Here are the generated tags:<\/p>\n<ul>\n<li><code>[6676, 'bottle', 0.3879561722278595]<\/code><\/li>\n<li><code>[7494, 'bottles', 0.7513495683670044]<\/code><\/li>\n<li><code>[12780, 'cans', 0.9817070364952087]<\/code><\/li>\n<li><code>[16883, 'vodka', 0.9828150272369385]<\/code><\/li>\n<li><code>[16720, 'jar', 1.0084964036941528]<\/code><\/li>\n<li><code>[12714, 'soda', 1.0182772874832153]<\/code><\/li>\n<li><code>[23279, 'jars', 1.0454961061477661]<\/code><\/li>\n<li><code>[3754, 'plastic', 1.0530102252960205]<\/code><\/li>\n<li><code>[19045, 'whiskey', 1.061428427696228]<\/code><\/li>\n<li><code>[4769, 'bag', 1.0815287828445435]<\/code><\/li>\n<\/ul>\n<p>That\u2019s a pretty amazing result, as most of the tags are <strong>very relevant<\/strong>. This method still has room to grow, but it picks up on most of the items in the image fairly well. The model learns to extract <strong>many relevant tags<\/strong>, even from categories that it was not trained on!<\/p>\n<h4 id=\"searching-for-images-usingtext\">Searching for images using\u00a0text<\/h4>\n<p>Most importantly, we can use our joint embedding to search through our image database using <strong>any word<\/strong>. We simply need to get our pre-trained word embedding from GloVe, and find the images that have the most similar embeddings (which we get by running them through our model).<\/p>\n<p><strong>Generalized image search with minimal data<\/strong>.<br>\nLet\u2019s start first with a word that was actually in our training set by searching for <code>dog<\/code>:<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/dog_search.png\"\n         alt=\"Results for search term\u00a0&amp;lsquo;dog&amp;rsquo;\"\/><figcaption>\n            <p>Results for search term\u00a0&lsquo;dog&rsquo;<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>OK, pretty good results\u200a\u2014\u200abut we could get this from any classifier that was trained just on the labels! Let\u2019s try something harder by searching for the keyword <code>ocean<\/code>, which is not in our dataset.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/ocean_search.png\"\n         alt=\"Results for search term\u00a0&amp;lsquo;ocean&amp;rsquo;\"\/><figcaption>\n            <p>Results for search term\u00a0&lsquo;ocean&rsquo;<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>That\u2019s awesome\u200a\u2014\u200aour model understands that <code>ocean<\/code> is similar to <code>water<\/code>, and returns many items from the <code>boat<\/code> class.<\/p>\n<p>What about searching for <code>street<\/code>?<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/street_search.png\"\n         alt=\"Results for search term\u00a0&amp;lsquo;street&amp;rsquo;\"\/><figcaption>\n            <p>Results for search term\u00a0&lsquo;street&rsquo;<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Here, our images returned come from plenty of classes (<code>car<\/code>, <code>dog<\/code>, <code>bicycles<\/code>, <code>bus<\/code>, <code>person<\/code>), yet most of them contain or are near a street, despite us having never used that concept when training our model. Because we are <strong>leveraging outside knowledge<\/strong> through pre-trained word vectors to learn a mapping from images to vectors that is more <strong>semantically rich<\/strong> than a simple category, our model can generalize well to outside concepts.<\/p>\n<h4 id=\"beyond-words\">Beyond words<\/h4>\n<p>The English language has come far, but not far enough to invent a word for everything. For example, at the time of publishing this article, there is no English word for \u201ca cat lying on a sofa,\u201d which is a perfectly valid query to type into a search engine. If we want to search for multiple words at the same time, we can use a very simple approach, leveraging the arithmetic properties of word vectors. It turns out that summing two word vectors generally works very well. So if we were to just search for our images by using the average word vector for <code>cat<\/code> and <code>sofa<\/code>, we could hope to get images that are very cat-like, very sofa-like, or have a cat on a sofa.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/combining_embeddings.png\"\n         alt=\"Getting a combined embedding for multiple\u00a0words\"\/><figcaption>\n            <p>Getting a combined embedding for multiple\u00a0words<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Let\u2019s try using this hybrid embedding and searching!<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/cat_sofa_search.png\"\n         alt=\"Results for search query &amp;lsquo;cat&amp;rsquo;&#43;&amp;lsquo;sofa&amp;rsquo;\"\/><figcaption>\n            <p>Results for search query &lsquo;cat&rsquo;+&lsquo;sofa&rsquo;<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>This is a fantastic result, as most those images contain some version of a furry animal and a sofa (I especially enjoy the leftmost image on the second row, which seems like a bag of furriness next to a couch)! Our model, which was only trained on single words, can handle combinations of two words. We have not built Google Image Search yet, but this is definitely impressive for a relatively simple architecture.<\/p>\n<p>This method can actually extend quite naturally to a variety of domains (see this <a href=\"https:\/\/towardsdatascience.com\/semantic-code-search-3cd6d244a39c\">example<\/a> for a joint code-English embedding), so we\u2019d love to hear about what you end up applying it to.<\/p>\n<h3 id=\"conclusion\">Conclusion<\/h3>\n<p>I hope you found this post informative, and that it has demystified some of the world of content-based recommendation and semantic search. If you have any questions or comments, or want to share what you built using this tutorial, reach out to me on <a href=\"https:\/\/twitter.com\/mlpowered\">Twitter<\/a>!<\/p>\n"},{"title":"Reinforcement Learning from scratch","link":"https:\/\/www.mlpowered.com\/posts\/rl-from-scratch\/","pubDate":"Thu, 07 Jun 2018 16:02:46 +0000","author":"mlpoweredapplications@gmail.com (Emmanuel Ameisen)","guid":"https:\/\/www.mlpowered.com\/posts\/rl-from-scratch\/","description":"<figure><img src=\"https:\/\/www.mlpowered.com\/images\/rl_cover.png\"\n         alt=\"A movie about one of the most famous applications of Deep\u00a0RL\"\/><figcaption>\n            <p>A movie about one of the most famous applications of Deep\u00a0RL<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Recently, I gave a talk at the O\u2019Reilly AI conference in Beijing about some of the interesting <a href=\"https:\/\/blog.insightdatascience.com\/how-to-solve-90-of-nlp-problems-a-step-by-step-guide-fda605278e4e\">lessons<\/a> we\u2019ve learned in the world of NLP. While there, I was lucky enough to attend a tutorial on Deep Reinforcement Learning (Deep RL) from scratch by Unity Technologies. I thought that the session, led by <a href=\"https:\/\/medium.com\/u\/18dfe63fa7f0\">Arthur Juliani<\/a>, was extremely informative and wanted to share some big takeaways below.<\/p>\n<p>In our conversations with companies, we\u2019ve seen a rise of interesting Deep RL applications, tools and results. In parallel, the inner workings and applications of Deep RL, such as AlphaGo pictured above, can often seem esoteric and hard to understand. In this post, I will give an overview of core aspects of the field that can be <strong>understood by anyone<\/strong>.<\/p>\n<p>Many of the visuals are from the slides of the talk, and some are new. The explanations and opinions are mine. If anything is unclear, reach out to me <a href=\"https:\/\/twitter.com\/mlpowered\">here<\/a>!<\/p>\n<h3 id=\"the-rise-of-deep-reinforcement-learning\">The rise of Deep Reinforcement Learning<\/h3>\n<p>Deep RL is a field that has seen vast amounts of research interest, including learning to play Atari games, <a href=\"https:\/\/blog.openai.com\/dota-2\/\">beating<\/a> pro players at Dota 2, and <a href=\"https:\/\/deepmind.com\/research\/alphago\/\">defeating<\/a> Go champions. Contrary to many classical Deep Learning problems that often focus on <strong>perception<\/strong> (does this image contain a stop sign?), Deep RL adds the dimension of <strong>actions<\/strong> that influence the environment (what is the goal, and how do I get there?). In dialog systems for example, classical Deep Learning aims to learn the right response for a given query. On the other hand, Deep Reinforcement Learning focuses on the right sequences of sentences that will lead to a positive outcome, for example a happy customer.<\/p>\n<p>This makes Deep RL particularly attractive for tasks that require planning and adaptation, such as manufacturing or self-driving. However, industry applications have trailed behind the rapidly advancing results coming out of the research community. A major reason is that Deep RL often requires an agent to experiment millions of times before learning anything useful. The best way to do this rapidly is by using a <strong>simulation environment<\/strong>. This tutorial will be using <a href=\"https:\/\/unity3d.com\/unity\">Unity<\/a> to create environments to train agents in.<\/p>\n<p>For this workshop led by <a href=\"https:\/\/www.linkedin.com\/in\/arthur-juliani-50a38a21\/\">Arthur Juliani<\/a> and <a href=\"https:\/\/www.linkedin.com\/in\/zhongyuechen\/\">Leon Chen<\/a>, their goal was to get every participants to successfully train multiple Deep RL algorithms in 4 hours. A tall order! Below, is a <strong>comprehensive overview<\/strong> of many of the main algorithms that power Deep RL today. For a more complete set of tutorials, <a href=\"https:\/\/medium.com\/u\/18dfe63fa7f0\">Arthur Juliani<\/a> wrote an 8-part series starting <a href=\"https:\/\/medium.com\/emergent-future\/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0\">here<\/a>.<\/p>\n<h4 id=\"from-slot-machines-to-video-games-an-overview-ofrl\">From slot machines to video games, an overview of\u00a0RL<\/h4>\n<p>Deep RL can be used to best the top human players at Go, but to understand how that\u2019s done, you first need to understand a few <strong>simple concepts<\/strong>, starting with much easier problems.<\/p>\n<p><strong>1\/It all starts with slot machines<\/strong><\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/chests.png\"\n         alt=\"As a first toy problem, can we learn which of these chests has the biggest chance of containing a\u00a0reward\"\/><figcaption>\n            <p>As a first toy problem, can we learn which of these chests has the biggest chance of containing a\u00a0reward<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Let\u2019s imagine you are faced with 4 chests that you can pick from at each turn. Each of them have a different average payout, and your goal is to maximize the total payout you receive after a fixed number of turns. This is a classic problem called <a href=\"https:\/\/en.wikipedia.org\/wiki\/Multi-armed_bandit\">Multi-armed bandits<\/a> and is where we will start. The crux of the problem is to balance <strong>exploration<\/strong>, which helps us learn about which states are good, and <strong>exploitation<\/strong>, where we now use what we know to pick the best slot machine.<\/p>\n<p>Here, we will utilize a <strong>value function<\/strong> that maps our actions to an estimated reward, called the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Q-learning\">Q function<\/a>. First, we\u2019ll initialize all Q values at equal values. Then, we\u2019ll update the Q value of each action (picking each chest) based on how good the payout was after choosing this action. This allows us to <strong>learn a good value function<\/strong>. We will approximate our Q function using a neural network (starting with a very shallow one) that learns a probability distribution (by using a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Softmax_function\">softmax<\/a>) over the 4 potential chests.<\/p>\n<p>While the value function tells us how good we estimate each action to be, the <strong>policy<\/strong> is the function that determines <strong>which actions we end up taking<\/strong>. Intuitively, we might want to use a policy that picks the action with the highest Q value. This performs poorly in practice, as our Q estimates will be very wrong at the start before we gather enough <strong>experience through trial and error<\/strong>. This is why we need to add a mechanism to our policy to <strong>encourage exploration<\/strong>. One way to do that is to use <a href=\"https:\/\/en.wikipedia.org\/wiki\/Multi-armed_bandit#Semi-uniform_strategies\">epsilon greedy<\/a>, which consists of taking a <strong>random action<\/strong> with probability epsilon. We start with epsilon being close to 1, always choosing random actions, and lower epsilon as we go along and learn more about which chests are good. Eventually, we learn which chests are best.<\/p>\n<p>In practice, we might want to take a more subtle approach than either taking the action we think is the best, or a random action. A popular method is Boltzmann Exploration, which adjust probabilities based on our current estimate of how good each chest is, adding in a randomness factor.<\/p>\n<p><strong>2\/Adding different states<\/strong><\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/chests_background.png\"\n         alt=\"Here, different background colors mean different average chest\u00a0rewards\"\/><figcaption>\n            <p>Here, different background colors mean different average chest\u00a0rewards<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>The previous example was a world in which we were always in the same state, waiting to pick from the same 4 chests in front of us. Most real-word problems consist of many different states. That is what we will add to our environment next. Now, the background behind chests alternates between 3 colors at each turn, <strong>changing the average values<\/strong> of the chests. This means we need to learn a Q function that depends not only on the <strong>action<\/strong> (the chest we pick), but the <strong>state<\/strong> (what the color of the background is). This version of the problem is called Contextual Multi-armed Bandits.<\/p>\n<p>Surprisingly, <strong>we can use the same approach as before<\/strong>. The only thing we need to add is an extra dense layer to our neural network, that will take in as input a vector representing the current state of the world.<\/p>\n<p><strong>3\/Learning about the consequences of our actions<\/strong><\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/grid.png\"\n         alt=\"Here, we are the blue square trying to learn how to get to the green square without touching the red\u00a0ones\"\/><figcaption>\n            <p>Here, we are the blue square trying to learn how to get to the green square without touching the red\u00a0ones<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>There is another key factor that makes our current problem simpler than mosts. In most environments, such as in the maze depicted above, the <strong>actions that we take have an impact on the state of the world<\/strong>. If we move up on this grid, we might receive a reward or we might receive nothing, but the next turn we will be in a different state. This is where we finally introduce a need for <strong>planning<\/strong>.<\/p>\n<p>First, we will define our Q function as the <strong>immediate reward<\/strong> in our current state, plus the discounted <strong>reward we are expecting<\/strong> by taking all of our future actions. This solution works if our Q estimate of states is accurate, so how can we learn a good estimate?<\/p>\n<p>We will use a method called <strong>Temporal Difference (TD) learning<\/strong> to learn a good Q function. The idea is to only look at a limited number of steps in the future. TD(1) for example, only uses the next 2 states to evaluate the reward.<\/p>\n<p>Surprisingly, we can use TD(0), which looks at the current state, and our estimate of the reward the next turn, and get great results. The structure of the network is the same, but we need to go through one forward step before receiving the error. We then use this error to <a href=\"https:\/\/en.wikipedia.org\/wiki\/Backpropagation\">back propagate<\/a> gradients, like in traditional Deep Learning, and update our value estimates.<\/p>\n<p><strong>3+\/Introducing Monte Carlo<\/strong><\/p>\n<p>Another method to estimate the eventual success of our actions is Monte Carlo Estimates. This consists of playing out <strong>the entire episode<\/strong> with our current policy until we reach an end (success by reaching a green block or failure by reaching a red block in the image above) and use that result to update our value estimates <strong>for each traversed state<\/strong>. This allows us to <strong>propagate values efficiently<\/strong> in one batch at the end of an episode, instead of every time we make a move. The cost is that we are introducing noise to our estimates, since we attribute very distant rewards to them.<\/p>\n<p><strong>4\/The world is rarely discrete<\/strong><\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/paddle_2d.png\"\/>\n<\/figure>\n\n<p>The previous methods were using neural networks to approximate our value estimates by mapping from a <strong>discrete number of states and actions<\/strong> to a value. In the maze for example, there were 49 states (squares) and 4 actions (move in each adjacent direction). In this environment, we are trying to learn how to balance a ball on a 2 dimensional paddle, by deciding at each time step whether we want to tilt the paddle left or right. Here, <strong>the state space becomes continuous<\/strong> (the angle of the paddle, and the position of the ball). The good news is, we can still use Neural Networks to approximate this function!<\/p>\n<p>A note about <strong>off-policy vs on-policy learning<\/strong>: The methods we used previously, are off-policy methods, meaning we can generate data <strong>with any strategy<\/strong>(using epsilon greedy for example) and learn from it. On-policy methods can only learn <strong>from actions that were taken following our policy<\/strong> (remember, a policy is the method we use to determine which actions to take). This constrains our learning process, as we have to have an exploration strategy that is built in to the policy itself, but allows us to <strong>tie results directly to our reasoning<\/strong>, and enables us to learn more efficiently.<\/p>\n<p>The approach we will use here is called <strong>Policy Gradients<\/strong>, and is an on-policy method. Previously, we were first learning a value function Q for each action in each state and then building a policy on top. In <strong>Vanilla Policy Gradient<\/strong>, we still use Monte Carlo Estimates, but we <strong>learn our policy directly<\/strong> through a loss function that <strong>increases the probability of choosing rewarding actions<\/strong>. Since we are learning on policy, we cannot use methods such as epsilon greedy (which includes random choices), to get our agent to explore the environment. The way that we encourage exploration is by using a method called <strong>entropy regularization<\/strong>, which pushes our probability estimates to be wider, and thus will encourage us to <strong>make riskier choices<\/strong> to explore the space.<\/p>\n<p><strong>4+\/Leveraging deep learning for representations<\/strong><\/p>\n<p>In practice, many state of the art RL methods require learning <strong>both a policy and value estimates<\/strong>. The way we do this with deep learning is by having both be two separate outputs of the same backbone neural network, which will make it easier for our neural network to learn good representations.<\/p>\n<p>One method to do this is <strong>Advantage Actor Critic<\/strong> (A2C). We learn our policy directly with policy gradients (defined above), and learn a value function using something called <strong>Advantage.<\/strong> Instead of updating our value function based on rewards, we update it based on our advantage, which measures how much better or worse an action was than our previous value function estimated it to be. This helps make learning more stable compared to simple Q Learning and Vanilla Policy Gradients.<\/p>\n<p><strong>5\/Learning directly from the screen<\/strong><\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/pixel_input.png\"\n         alt=\"The inputs to the model are the pixels in the image\u00a0above!\"\/><figcaption>\n            <p>The inputs to the model are the pixels in the image\u00a0above!<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>There is an additional advantage to using Deep Learning for these methods, which is that Deep Neural Networks excel at <strong>perceptive tasks<\/strong>. When a human plays a game, the information received is not a list of states, but an image (usually of a screen, or a board, or the surrounding environment).<\/p>\n<p>Image-based Learning <strong>combines a Convolutional Neural Network (CNN) with RL<\/strong>. In this environment, we pass in a <strong>raw image<\/strong> instead of features, and add a 2 layer CNN to our architecture without changing anything else! We can even <strong>inspect activations<\/strong> to see what the network picks up on to determine value, and policy. In the example below, we can see that the network uses the <strong>current score and distant obstacles<\/strong> to estimate the value of the <strong>current state<\/strong>, while focusing on <strong>nearby obstacles<\/strong> for determining <strong>actions<\/strong>. Neat!<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/activations.png\"\n         alt=\"Inspecting a CNN\u2019s activations to see what is important to the value estimate (left) and the policy estimate\u00a0(right).\"\/><figcaption>\n            <p>Inspecting a CNN\u2019s activations to see what is important to the value estimate (left) and the policy estimate\u00a0(right).<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>As a side note, while toying around with the provided implementation, I\u2019ve found that visual learning is very sensitive to hyperparameters. Changing the discount rate slightly for example, completely prevented the neural network from learning even on a toy application. This is a widely known <a href=\"https:\/\/www.alexirpan.com\/2018\/02\/14\/rl-hard.html\">problem<\/a>, but it is interesting to see it first hand.<\/p>\n<p><strong>6\/Nuanced actions<\/strong><\/p>\n<p><img src=\"images\/paddle_3d.png\" alt=\"\">\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/paddle_3d.png\"\/>\n<\/figure>\n<\/p>\n<p>So far, we\u2019ve played with environments with continuous and discrete <strong>state spaces<\/strong>. However, every environment we studied had a discrete <strong>action space<\/strong>: we could move in one of four directions, or tilt the paddle to the left or right. Ideally, for applications such as self-driving cars, we would like to learn continuous actions, such as <strong>turning the steering wheel<\/strong> between 0 and 360 degrees. In this environment called 3D ball world, we can choose to tilt the paddle to any value on each of its axes. This gives us <strong>more control<\/strong> as to how we perform actions, but <strong>makes the action space much larger<\/strong>.<\/p>\n<p>We can approach this by approximating our potential choices with Gaussian distributions. We learn a probability distribution over potential actions by learning the mean and variance of a Gaussian distribution, and our policy we sample from that distribution. Simple, in theory\u00a0:).<\/p>\n<p><strong>7\/Next steps for the brave<\/strong><\/p>\n<p>There are a few concepts that separate the algorithms described above from state of the art approaches. It\u2019s interesting to see that conceptually, the best robotics and game-playing algorithms are not that far away from the ones we just explored:<\/p>\n<ul>\n<li><strong>Parallelizing<\/strong>: A3C is one of the most common approaches out there. It adds an asynchronous step to actor critic, allowing the algorithm to run in a parallelized way. This allows it to solve more interesting problems in a reasonable amount of time. Evolutionary methods can be parallelized even more, and are showing very <a href=\"https:\/\/eng.uber.com\/deep-neuroevolution\/\">encouraging<\/a> performance.<\/li>\n<li><strong>Curriculum Learning<\/strong>: in many cases, it is extremely unlikely to get to any reward by acting randomly. This makes the exploration phase extremely tricky, as we will never learn anything valuable. In that case we can simplify the problem and solve a trivial version first, then use the basic model on increasingly more complex environments.<\/li>\n<li><strong>Memory<\/strong>: Using LSTMs, for example, we can remember what happened in the past, and make decisions in a sequential way within a game playing session.<\/li>\n<li><strong>Model based RL<\/strong>: Various approach exist for algorithms to build a model of the world while they learn, so that they can infer rules about how the world works, on top of simply performing actions with high rewards. AlphaZero combines an explicit model with planning. <a href=\"http:\/\/worldmodels.github.io\">This<\/a> is a paper I found particularly exciting in the space.<\/li>\n<\/ul>\n<p>That\u2019s it for this overview, I hope this has been informative and fun! If you are looking to dive deeper into the theory of RL, give Arthur\u2019s posts a <a href=\"https:\/\/medium.com\/emergent-future\/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0\">read<\/a>, or diving deeper by following David Silver\u2019s UCL <a href=\"http:\/\/www0.cs.ucl.ac.uk\/staff\/d.silver\/web\/Teaching.html\">course<\/a>. If you are looking to learn more about the projects we do at Insight, or how we work with companies, please check us out below, or reach out to me on <a href=\"https:\/\/twitter.com\/mlpowered\">Twitter<\/a>.<\/p>\n"},{"title":"Always start with a stupid model, no exceptions.","link":"https:\/\/www.mlpowered.com\/posts\/start-with-a-stupid-model\/","pubDate":"Tue, 06 Mar 2018 17:28:53 +0000","author":"mlpoweredapplications@gmail.com (Emmanuel Ameisen)","guid":"https:\/\/www.mlpowered.com\/posts\/start-with-a-stupid-model\/","description":"<figure><img src=\"https:\/\/www.mlpowered.com\/images\/simple_model_cover.png\"\n         alt=\"To build General AI, you must first master Logistic Regression\"\/><figcaption>\n            <p>To build General AI, you must first master Logistic Regression<\/p>\n        <\/figcaption>\n<\/figure>\n\n<h3 id=\"lets-start-with-thebasics\">Let\u2019s start with the\u00a0basics<\/h3>\n<p>When trying to develop a scientific understanding of the world, most fields start with broad strokes before exploring important details. In Physics for example, we start with simple models (Newtonian physics) and progressively dive into more complex ones (Relativity) as we learn which of our initial assumptions were wrong. This allows us to solve problems efficiently, by reasoning at the <strong>simplest useful level<\/strong>.<\/p>\n<blockquote>\n<p>Everything should be made as simple as possible, but not simpler. -Albert Einstein<\/p>\n<\/blockquote>\n<p>The exact same approach of starting with a very simple model can be applied to machine learning engineering, and it usually proves very valuable. In fact, after seeing hundreds of projects go from ideation to finished products at Insight, we found that starting with a simple model as a baseline consistently led to a better end product.<\/p>\n<p>When tackling complex problems, simple solutions, like the baselines we\u2019ll describe below, have many flaws:<\/p>\n<ul>\n<li>They sometimes ignore important aspects of the input. For example, simple models often ignore the <a href=\"https:\/\/blog.insightdatascience.com\/how-to-solve-90-of-nlp-problems-a-step-by-step-guide-fda605278e4e\">order of words<\/a> in a sentence or the correlations between variables.<\/li>\n<li>They have a limited ability to produce nuanced outputs. Most simple models may need to be coupled with heuristics or hand-crafted rules before being put in front of a customer.<\/li>\n<li>They are not as fun to work with, and might not get you the cutting-edge research experience you are looking to develop.<\/li>\n<\/ul>\n<p>The misguided output often produced by these solutions can appear very silly to us, hence the title <strong>stupid models<\/strong>. However, as we describe in this post, they provide an incredibly useful first step, and allow us to understand our problem better in order to inform us on the best way to approach it. In the words of George E. P. Box:<\/p>\n<blockquote>\n<p>All models are wrong, but some are useful.<\/p>\n<\/blockquote>\n<p>In other words: if you want to play with fun toys, start with a complex model. If you want to solve problems and build products, start with a stupid one.<\/p>\n<h3 id=\"what-is-a-baseline\">What is a baseline?<\/h3>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/xkcd_regression.png\"\n         alt=\"Different distributions require different baselines (source)\"\/><figcaption>\n            <p>Different distributions require different baselines (<a href=\"https:\/\/xkcd.com\/1725\/\">source<\/a>)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Fundamentally, a baseline is a model that is both simple to set up and has a reasonable chance of providing decent results. Experimenting with them is usually quick and low cost, since implementations are widely available in popular packages.<\/p>\n<p>Here are a few baselines that can be useful to consider:<\/p>\n<ul>\n<li><strong>Linear Regression<\/strong>. A solid first approach for predicting continuous values (prices, age,\u00a0\u2026) from a set of features.<\/li>\n<li><strong>Logistic Regression.<\/strong> When trying to classify structured data or natural language, logistic regressions will usually give you quick, solid results.<\/li>\n<li><strong>Gradient Boosted Trees.<\/strong> A Kaggle classic! For time series predictions and general structured data, it is hard to beat Gradient Boosted Trees. While slightly harder to interpret than other baselines, they usually perform very well.<\/li>\n<li><strong>Simple Convolutional Architecture<\/strong>. Fine tuning <a href=\"https:\/\/arxiv.org\/abs\/1409.1556\">VGG<\/a> or re-training some variant of a <a href=\"https:\/\/arxiv.org\/abs\/1505.04597\">U-net<\/a> is usually a great start for most image classification, detection, or segmentation problems.<\/li>\n<li><strong>And many more!<\/strong><\/li>\n<\/ul>\n<p>Your choice of a simple, baseline model depends on the kind of data you are working with and the kind of task you are targeting. A linear regression makes sense if you are trying to predict house prices from various characteristics (predicting a value from a set of features), but not if you are trying to build a speech-to-text algorithm. In order to choose the best baseline, it is useful to think of what you are hoping to gain by using one.<\/p>\n<h3 id=\"why-start-with-a-baseline\">Why start with a baseline?<\/h3>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/michelangelo.png\"\n         alt=\"Deploying a model takes a lot of work, make sure to explore before you commit\u00a0(source)\"\/><figcaption>\n            <p>Deploying a model takes a lot of work, make sure to explore before you commit\u00a0(<a href=\"https:\/\/eng.uber.com\/michelangelo\/\">source<\/a>)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>When starting on a project, the first priority is learning about what potentially unforeseen challenges will stand in your way. Even if they will not be the final version of your model, baselines allow you to iterate very quickly, while wasting minimal time. Below are a few reasons why.<\/p>\n<h4 id=\"a-baseline-will-take-you-less-than-110th-of-the-time-and-could-provide-up-to-90-of-theresults\">A baseline will take you less than 1\/10th of the time, and could provide up to 90% of the\u00a0results.<\/h4>\n<p>Multiply your productivity by 9!<\/p>\n<p>Here is a very common story: a team wants to implement a model to predict something like the probability of a user clicking an ad. They start with a logistic regression and quickly (after some minor tuning) reach 90% accuracy.<\/p>\n<p>From there, the question is: <strong>Should the team focus on getting the accuracy up to 95%, or should they solve other problems 90% of the way?<\/strong><\/p>\n<p>Most state-of-the-art models still leave you with non-zero error rates due to their stochastic nature. This depends on your use case, but most system efficiencies are multiplicative in nature, meaning you\u2019d rather have 10 successive steps at 90% accuracy (leading to 34% overall accuracy), rather than one at 99%, followed by 9 at 10% (0.00000000099%% overall accuracy).<\/p>\n<p>Starting with a baseline lets you address the bottlenecks first!<\/p>\n<h4 id=\"a-baseline-puts-a-more-complex-model-intocontext\">A baseline puts a more complex model into\u00a0context<\/h4>\n<p>Usually there are three levels of performance you can easily estimate:<\/p>\n<ul>\n<li>The <strong>trivially attainable<\/strong> performance, which is a metric you would hope any model could beat. An example of this value could be the accuracy you would get by guessing the most frequent class in a classification task.<\/li>\n<li><strong>Human performance<\/strong>, which is the level at which a human can accomplish this task. Computers are much better than humans at some tasks (like playing Go) and worse at others (like writing poetry). Knowing how good a human is at something can help you set expectations ahead of time for an algorithm, but since the human\/computer difference varies widely by field, it may require some literature search to calibrate.<\/li>\n<li>The <strong>required to deploy<\/strong> performance, which is the minimal value that would make your model suitable for production from a business and usability standpoint. Usually, this value can be made more attainable by smart design decisions. <a href=\"http:\/\/.\">Google Smart Reply<\/a>, for example, shows three suggested responses, significantly increasing their chances of showing a useful result.<\/li>\n<\/ul>\n<p>What is missing from those levels is something I would call <strong>\u201creasonable automated performance&quot;<\/strong>, which represents what can be attained by a relatively simple model. Having this benchmark is vital in evaluating whether a complex model is performing well, and enables us to address the accuracy\/complexity tradeoff.<\/p>\n<p>Many times we find that baselines match or outperform complex models, especially when the complex model has been chosen without looking at where the baseline fails. In addition, complex models are usually harder to deploy, which means measuring their lift over a simple baseline is a necessary precursor to the engineering efforts needed to deploy them.<\/p>\n<h4 id=\"baselines-are-easy-todeploy\">Baselines are easy to\u00a0deploy<\/h4>\n<p>By definition, baseline models are simple. They usually consist of relatively few trainable parameters, and can be quickly fit to your data without too much work.<\/p>\n<p>This means that when it comes to engineering, simple models are:<\/p>\n<ul>\n<li><strong>Faster to train<\/strong>, giving you very quick feedback on performance.<\/li>\n<li><strong>Better studied<\/strong>, meaning most of the errors you encounter will either be easy bugs in the model, or will highlight that something is wrong with your data.<\/li>\n<li><strong>Quicker for inference<\/strong>, which means deploying them does not require much infrastructure engineering, and will not increase latency.<\/li>\n<\/ul>\n<p>Once you\u2019ve built and deployed a baseline model, you are in the best position to decide which step to take next.<\/p>\n<h3 id=\"what-to-do-after-building-a-baselinemodel\">What to do after building a baseline\u00a0model?<\/h3>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/learning_to_learn_paper.png\"\n         alt=\"Is it time to bring out some research papers yet?\u00a0(source)\"\/><figcaption>\n            <p>Is it time to bring out some research papers yet?\u00a0(<a href=\"https:\/\/arxiv.org\/abs\/1606.04474\">source<\/a>)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>As mentioned above, your baseline model will allow you to get a quick performance benchmark. If you find that the performance it provides is not sufficient, then <strong>inspecting what the simple model is struggling with can help you choose a next approach.<\/strong><\/p>\n<p>For example, in our <a href=\"https:\/\/blog.insightdatascience.com\/how-to-solve-90-of-nlp-problems-a-step-by-step-guide-fda605278e4e\">NLP primer<\/a>, by inspecting our baseline\u2019s errors, we can see that it fails to separate meaningful words from filler words. This guides us to use a model that can capture this sort of nuance.<\/p>\n<h4 id=\"a-baseline-helps-you-understand-yourdata\">A baseline helps you understand your\u00a0data<\/h4>\n<p>If a baseline does well, then you\u2019ve saved yourself the headache of setting up a more complex model. If it does poorly, the kind of mistakes it makes are very instructive as to the biases and particular problems with your data. Most issues with machine learning are solved by <strong>understanding and preparing data better<\/strong>, not by simply picking a more complex model. Looking at how a baseline behaves will teach you about:<\/p>\n<ul>\n<li><strong>Which classes are harder to separate.<\/strong> For most classification problems, looking at a confusion matrix will be very informative in learning which classes are giving your model trouble. Whenever performance is particularly poor on a set of classes, it is worth exploring the data to understand why.<\/li>\n<li><strong>What type of signal your model picks up on.<\/strong> Most baselines will allow you to extract feature importances, revealing which aspects of the input are most predictive. Analyzing feature importance is a great way to realize how your model is making decisions, and what it might be missing.<\/li>\n<li><strong>What signal your model is missing.<\/strong> If there is a certain aspect of the data that seems intuitively important but that your model is ignoring, a good next step is to engineer a feature or pick a different model that could better leverage this particular aspect of your data.<\/li>\n<\/ul>\n<h4 id=\"a-baseline-helps-you-understand-yourtask\">A baseline helps you understand your\u00a0task<\/h4>\n<p>Beyond learning from your data, a baseline model will allow you to see which parts of your inference are easy, and which parts are hard. In turn, this allows you to explore i<strong>n which direction you should refine your model for it to address the hard parts better<\/strong>.<\/p>\n<p>For example, when trying to <a href=\"https:\/\/blog.insightdatascience.com\/hero2vec-d42d6838c941\">predict the chance of a given team winning in Overwatch<\/a>, Bowen Yang started with a logistic regression. He quickly noticed that prediction accuracy drastically improved after the game was more than halfway done. This observation helped him to decide on his next modeling choice, an embedding technique that allowed him to learn from a priori information, which boosted accuracy even before the first minute of the match.<\/p>\n<p>Most machine learning problems follow the \u201cno free lunch\u201d theorem: there is no one-size-fits-all solution. The challenge resides in picking from a variety of architectures, embedding strategies, and models to determine the one that can best extract and leverage the structure of your data. Seeing what a simple baseline struggles to model is a great way to inform that decision.<\/p>\n<p>As another example, when trying to segment cardiac MRIs, Chuck-Hou Yee started with a vanilla U-net architecture. This led him to notice that many of the segmentation errors made by his model were due to a lack of context awareness (small receptive field). To address the problem, he moved to using dilated convolutions, which <a href=\"https:\/\/blog.insightdatascience.com\/heart-disease-diagnosis-with-deep-learning-c2d92c27e730\">improved his results significantly<\/a>.<\/p>\n<h4 id=\"when-a-baseline-just-wont-cutit\">When a baseline just won\u2019t cut\u00a0it<\/h4>\n<p>Finally, for some tasks, it is very hard to build an effective baseline. If you are working on separating different speakers from an audio recording (the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Cocktail_party_effect\">cocktail party problem<\/a>), you might need to start with a complex model to get satisfying results. In these cases, instead of simplifying the model, a good alternative is to simplify the data: try to get your complex model to <strong>overfit to a very small subset of your data<\/strong>. If your model has the expressive power required to learn, it should be easy. If this part proves hard, then it usually means you want to try a different model!<\/p>\n<h3 id=\"conclusion\">Conclusion<\/h3>\n<p>It\u2019s easy to overlook simple methods once you are aware of the existence of more powerful ones, but in machine learning like in most fields, it is always valuable to start with the basics.<\/p>\n<p>While learning how to apply complex methods is certainly a challenge, the <strong>biggest challenge<\/strong> faced by machine learning engineers is deciding on a modeling strategy for a given task. That decision can be informed by trying a simple model first; if its performance is lackluster, move to a more complex model that would be especially good at avoiding the specific mistakes you\u2019ve seen your baseline make.<\/p>\n<p>At Insight, this is an approach that we\u2019ve seen collectively save thousands of hours for our Fellows, and for the teams that we work with. We hope that you find it useful as well, feel free to reach out to us with any questions or comments!<\/p>\n"},{"title":"How to solve 90% of NLP problems: a step-by-step guide","link":"https:\/\/www.mlpowered.com\/posts\/how-to-solve-90-nlp\/","pubDate":"Wed, 24 Jan 2018 17:14:49 +0000","author":"mlpoweredapplications@gmail.com (Emmanuel Ameisen)","guid":"https:\/\/www.mlpowered.com\/posts\/how-to-solve-90-nlp\/","description":"<figure><img src=\"https:\/\/www.mlpowered.com\/images\/how_to_nlp_cover.png\"\n         alt=\"How you can apply the 5 W\u2019s and H to Text\u00a0Data!\"\/><figcaption>\n            <p>How you can apply the 5 W\u2019s and H to Text\u00a0Data!<\/p>\n        <\/figcaption>\n<\/figure>\n\n<h3 id=\"text-data-is-everywhere\">Text data is everywhere<\/h3>\n<p>Whether you are an established company or working to launch a new service, you can always leverage text data to validate, improve, and expand the functionalities of your product. The science of extracting meaning and learning from text data is an active topic of research called Natural Language Processing (NLP).<\/p>\n<p>NLP produces <a href=\"https:\/\/arxiv.org\/abs\/1704.01444\">new<\/a> and <a href=\"https:\/\/arxiv.org\/abs\/1711.00043\">exciting<\/a> <a href=\"https:\/\/arxiv.org\/abs\/1708.04729\">results<\/a> on a daily basis, and is a very large field. However, having worked with hundreds of companies, the Insight team has seen a few key practical applications come up much more frequently than any other:<\/p>\n<ul>\n<li>Identifying different cohorts of users\/customers (e.g. predicting churn, lifetime value, product preferences)<\/li>\n<li>Accurately detecting and extracting different categories of feedback (positive and negative reviews\/opinions, mentions of particular attributes such as clothing size\/fit\u2026)<\/li>\n<li>Classifying text according to intent (e.g. request for basic help, urgent problem)<\/li>\n<\/ul>\n<p>While many NLP papers and tutorials exist online, we have found it hard to find guidelines and tips on how to approach these problems <strong>efficiently<\/strong> from the ground up.<\/p>\n<h3 id=\"how-this-article-canhelp\">How this article can\u00a0help<\/h3>\n<p>After leading hundreds of projects a year and gaining advice from top teams all over the United States, we wrote this post to explain how to build Machine Learning solutions to solve problems like the ones mentioned above. We\u2019ll begin with <strong>the simplest method<\/strong> that could work, and then move on to more nuanced solutions, such as feature engineering, word vectors, and deep learning.<\/p>\n<p>After reading this article, you\u2019ll know how to:<\/p>\n<ul>\n<li>Gather, prepare and inspect data<\/li>\n<li>Build simple models to start, and transition to deep learning if necessary<\/li>\n<li>Interpret and understand your models, to make sure you are actually capturing information and not noise<\/li>\n<\/ul>\n<p>We wrote this post as a step-by-step guide; it can also serve as a high level overview of highly effective standard approaches.<\/p>\n<p><strong>This post is accompanied by<\/strong> <a href=\"https:\/\/github.com\/hundredblocks\/concrete_NLP_tutorial\/blob\/master\/NLP_notebook.ipynb\"><strong>an interactive notebook<\/strong><\/a> <strong>demonstrating and applying all these techniques. Feel free to run the code and follow along!<\/strong><\/p>\n<h3 id=\"step-1-gather-yourdata\">Step 1: Gather your\u00a0data<\/h3>\n<h4 id=\"example-datasources\">Example data\u00a0sources<\/h4>\n<p>Every Machine Learning problem starts with data, such as a list of emails, posts, or tweets. Common sources of textual information include:<\/p>\n<ul>\n<li>Product reviews (on Amazon, Yelp, and various App Stores)<\/li>\n<li>User-generated content (Tweets, Facebook posts, StackOverflow questions)<\/li>\n<li>Troubleshooting (customer requests, support tickets, chat logs)<\/li>\n<\/ul>\n<p><strong>\u201cDisasters on Social Media\u201d dataset<\/strong><\/p>\n<p>For this post, we will use a dataset generously provided by <a href=\"http:\/\/www.figure-eight.com\/data-for-everyone\">Figure Eight<\/a>, called \u201cDisasters on Social Media\u201d, where:<\/p>\n<blockquote>\n<p>Contributors looked at over 10,000 tweets culled with a variety of searches like \u201cablaze\u201d, \u201cquarantine\u201d, and \u201cpandemonium\u201d, then noted whether the tweet referred to a disaster event (as opposed to a joke with the word or a movie review or something non-disastrous).<\/p>\n<\/blockquote>\n<p>Our task will be to detect which tweets are about a <strong>disastrous event<\/strong> as opposed to an <strong>irrelevant topic<\/strong> such as a movie. Why? A potential application would be to exclusively notify law enforcement officials about urgent emergencies while ignoring reviews of the most recent Adam Sandler film. A particular challenge with this task is that both classes contain the same search terms used to find the tweets, so we will have to use subtler differences to distinguish between them.<\/p>\n<p>In the rest of this post, we will refer to tweets that are about disasters as \u201c<strong>disaster<\/strong>\u201d, and tweets about anything else as \u201c<strong>irrelevant<\/strong>\u201d.<\/p>\n<h4 id=\"labels\">Labels<\/h4>\n<p>We have labeled data and so we know which tweets belong to which categories. As Richard Socher outlines below, it is usually faster, simpler, and cheaper to <strong>find and label enough data<\/strong> to train a model on, rather than trying to optimize a complex unsupervised method.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/socher_tweet.png\"\n         alt=\"Richard Socher\u2019s\u00a0pro-tip\"\/><figcaption>\n            <p>Richard Socher\u2019s\u00a0pro-tip<\/p>\n        <\/figcaption>\n<\/figure>\n\n<h3 id=\"step-2-clean-yourdata\">Step 2: Clean your\u00a0data<\/h3>\n<blockquote>\n<p>The number one rule we follow is: \u201cYour model will only ever be as good as your data.\u201d<\/p>\n<\/blockquote>\n<p>One of the key skills of a data scientist is knowing whether the next step should be working on the model or the data. A good rule of thumb is to look at the data first and then clean it up. <strong>A clean dataset will allow a model to learn meaningful features and not overfit on irrelevant noise.<\/strong><\/p>\n<p>Here is a checklist to use to clean your data: (see the <a href=\"https:\/\/github.com\/hundredblocks\/concrete_NLP_tutorial\/blob\/master\/NLP_notebook.ipynb\">code<\/a> for more details):<\/p>\n<ol>\n<li>Remove all irrelevant characters such as any non alphanumeric characters<\/li>\n<li><a href=\"https:\/\/nlp.stanford.edu\/IR-book\/html\/htmledition\/tokenization-1.html\">Tokenize<\/a> your text by separating it into individual words<\/li>\n<li>Remove words that are not relevant, such as \u201c@\u201d twitter mentions or urls<\/li>\n<li>Convert all characters to lowercase, in order to treat words such as \u201chello\u201d, \u201cHello\u201d, and \u201cHELLO\u201d the same<\/li>\n<li>Consider combining misspelled or alternately spelled words to a single representation (e.g. \u201ccool\u201d\/\u201dkewl\u201d\/\u201dcooool\u201d)<\/li>\n<li>Consider <a href=\"https:\/\/nlp.stanford.edu\/IR-book\/html\/htmledition\/stemming-and-lemmatization-1.html\">lemmatization<\/a> (reduce words such as \u201cam\u201d, \u201care\u201d, and \u201cis\u201d to a common form such as \u201cbe\u201d)<\/li>\n<\/ol>\n<p>After following these steps and checking for additional errors, we can start using the clean, labelled data to train models!<\/p>\n<h3 id=\"step-3-find-a-good-data-representation\">Step 3: Find a good data representation<\/h3>\n<p>Machine Learning models take numerical values as input. Models working on images, for example, take in a matrix representing the intensity of each pixel in each color channel.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/image_matrix.png\"\n         alt=\"A smiling face represented as a matrix of\u00a0numbers.\"\/><figcaption>\n            <p>A smiling face represented as a matrix of\u00a0numbers.<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Our dataset is a list of sentences, so in order for our algorithm to extract patterns from the data, we first need to find a way to represent it in a way that our algorithm can understand, i.e. as a list of numbers.<\/p>\n<h4 id=\"one-hot-encoding-bag-ofwords\">One-hot encoding (Bag of\u00a0Words)<\/h4>\n<p>A natural way to represent text for computers is to encode each character individually as a number (<a href=\"https:\/\/en.wikipedia.org\/wiki\/ASCII\">ASCII<\/a> for example). If we were to feed this simple representation into a classifier, it would have to learn the structure of words from scratch based only on our data, which is impossible for most datasets. We need to use a higher level approach.<\/p>\n<p>For example, we can build a <strong>vocabulary<\/strong> of all the unique words in our dataset, and associate a unique index to each word in the vocabulary. Each sentence is then represented as a list that is as long as the number of distinct words in our vocabulary. At each index in this list, we mark how many times the given word appears in our sentence. This is called a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Bag-of-words_model\"><strong>Bag of Words<\/strong><\/a> <strong>model<\/strong>, since it is a representation that completely ignores the order of words in our sentence. This is illustrated below.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/bow.png\"\n         alt=\"Representing sentences as a Bag of Words. Sentences on the left, representation on the right. Each index in the vectors represent one particular word.\"\/><figcaption>\n            <p>Representing sentences as a Bag of Words. Sentences on the left, representation on the right. Each index in the vectors represent one particular word.<\/p>\n        <\/figcaption>\n<\/figure>\n\n<h4 id=\"visualizing-the-embeddings\">Visualizing the embeddings<\/h4>\n<p>We have around 20,000 words in our vocabulary in the \u201cDisasters of Social Media\u201d example, which means that every sentence will be represented as a vector of length 20,000. The vector will contain <strong>mostly 0s<\/strong> because each sentence contains only a very small subset of our vocabulary.<\/p>\n<p>In order to see whether our embeddings are capturing information that is <strong>relevant to our problem<\/strong> (i.e. whether the tweets are about disasters or not), it is a good idea to visualize them and see if the classes look well separated. Since vocabularies are usually very large and visualizing data in 20,000 dimensions is impossible, techniques like <a href=\"https:\/\/en.wikipedia.org\/wiki\/Principal_component_analysis\">PCA<\/a> will help project the data down to two dimensions. This is plotted below.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/pca_bow.png\"\n         alt=\"Visualizing Bag of Words embeddings.\"\/><figcaption>\n            <p>Visualizing Bag of Words embeddings.<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>The two classes do not look very well separated, which could be a feature of our embeddings or simply of our dimensionality reduction. In order to see whether the Bag of Words features are of any use, we can train a classifier based on them.<\/p>\n<h3 id=\"step-4-classification\">Step 4: Classification<\/h3>\n<p>When first approaching a problem, a general best practice is to start with the simplest tool that could solve the job. Whenever it comes to classifying data, a common favorite for its versatility and explainability is <a href=\"https:\/\/en.wikipedia.org\/wiki\/Logistic_regression\">Logistic Regression<\/a>. It is very simple to train and the results are interpretable as you can easily extract the most important coefficients from the model.<\/p>\n<p>We split our data in to a training set used to fit our model and a test set to see how well it generalizes to unseen data. After training, we get an <strong>accuracy of 75.4%.<\/strong> Not too shabby! Guessing the most frequent class (\u201cirrelevant\u201d) would give us only 57%. However, even if 75% precision was good enough for our needs, <strong>we should never ship a model without trying to understand it.<\/strong><\/p>\n<h3 id=\"step-5-inspection\">Step 5: Inspection<\/h3>\n<h4 id=\"confusion-matrix\">Confusion Matrix<\/h4>\n<p>A first step is to understand the types of errors our model makes, and which kind of errors are least desirable. In our example, <strong>false positives<\/strong> are classifying an irrelevant tweet as a disaster, and <strong>false negatives<\/strong> are classifying a disaster as an irrelevant tweet. If the priority is to react to every potential event, we would want to lower our false negatives. If we are constrained in resources however, we might prioritize a lower false positive rate to reduce false alarms. A good way to visualize this information is using a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Confusion_matrix\">Confusion Matrix<\/a>, which compares the predictions our model makes with the true label. Ideally, the matrix would be a diagonal line from top left to bottom right (our predictions match the truth perfectly).<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/confusion_matrix_bow.png\"\n         alt=\"Confusion Matrix (Green is a high proportion, blue is\u00a0low)\"\/><figcaption>\n            <p>Confusion Matrix (Green is a high proportion, blue is\u00a0low)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Our classifier creates more false negatives than false positives (proportionally). In other words, our model\u2019s most common error is inaccurately classifying disasters as irrelevant. If false positives represent a high cost for law enforcement, this could be a good bias for our classifier to have.<\/p>\n<h4 id=\"explaining-and-interpreting-ourmodel\">Explaining and interpreting our\u00a0model<\/h4>\n<p>To validate our model and interpret its predictions, it is important to look at which words it is using to make decisions. If our data is biased, our classifier will make accurate predictions in the sample data, but the model would not generalize well in the real world. Here we plot the <strong>most important words<\/strong> for both the disaster and irrelevant class. Plotting word importance is simple with Bag of Words and Logistic Regression, since we can just extract and rank the coefficients that the model used for its predictions.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/bow_importance.png\"\n         alt=\"Bag of Words: Word importance\"\/><figcaption>\n            <p>Bag of Words: Word importance<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Our classifier correctly picks up on some patterns (hiroshima, massacre), but clearly seems to be overfitting on some meaningless terms (heyoo, x1392). Right now, our Bag of Words model is dealing with a huge vocabulary of different words and <strong>treating all words equally<\/strong>. However, some of these words are very frequent, and are only contributing noise to our predictions. Next, we will try a way to represent sentences that can account for the frequency of words, to see if we can pick up more signal from our data.<\/p>\n<h3 id=\"step-6-accounting-for-vocabulary-structure\">Step 6: Accounting for vocabulary structure<\/h3>\n<h4 id=\"tf-idf\">TF-IDF<\/h4>\n<p>In order to help our model focus more on meaningful words, we can use a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Tf%E2%80%93idf\">TF-IDF score<\/a> (Term Frequency, Inverse Document Frequency) on top of our Bag of Words model. TF-IDF weighs words by how rare they are in our dataset, discounting words that are too frequent and just add to the noise. Here is the PCA projection of our new embeddings.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/pca_tfidf.png\"\n         alt=\"Visualizing TF-IDF embeddings.\"\/><figcaption>\n            <p>Visualizing TF-IDF embeddings.<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>We can see above that there is a clearer distinction between the two colors. This should make it easier for our classifier to separate both groups. Let\u2019s see if this leads to better performance. Training another Logistic Regression on our new embeddings, we get <strong>an accuracy of 76.2%.<\/strong><\/p>\n<p>A very slight improvement. Has our model started picking up on more important words? If we are getting a better result while preventing our model from \u201ccheating\u201d then we can truly consider this model an upgrade.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/tfidf_importance.png\"\n         alt=\"TF-IDF: Word importance\"\/><figcaption>\n            <p>TF-IDF: Word importance<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>The words it picked up look much more relevant! Although our metrics on our test set only increased slightly, we have much more confidence in the terms our model is using, and thus would feel more comfortable deploying it in a system that would interact with customers.<\/p>\n<h3 id=\"step-7-leveraging-semantics\">Step 7: Leveraging semantics<\/h3>\n<h4 id=\"word2vec\">Word2Vec<\/h4>\n<p>Our latest model managed to pick up on high signal words. However, it is very likely that if we deploy this model, we will encounter words that we have not seen in our training set before. The previous model will not be able to accurately classify these tweets, <strong>even if it has seen very similar words during training<\/strong>.<\/p>\n<p>To solve this problem, we need to capture the <strong>semantic meaning of words<\/strong>, meaning we need to understand that words like \u2018good\u2019 and \u2018positive\u2019 are closer than \u2018apricot\u2019 and \u2018continent.\u2019 The tool we will use to help us capture meaning is called Word2Vec.<\/p>\n<p><strong>Using pre-trained words<\/strong><\/p>\n<p><a href=\"https:\/\/arxiv.org\/abs\/1301.3781\">Word2Vec<\/a> is a technique to find continuous embeddings for words. It learns from reading massive amounts of text and memorizing which words tend to appear in similar contexts. After being trained on enough data, it generates a 300-dimension vector for each word in a vocabulary, with words of similar meaning being closer to each other.<\/p>\n<p>The authors of the <a href=\"https:\/\/arxiv.org\/abs\/1301.3781\">paper<\/a> open sourced a model that was pre-trained on a very large corpus which we can leverage to include some knowledge of semantic meaning into our model. The pre-trained vectors can be found in the <a href=\"https:\/\/github.com\/hundredblocks\/concrete_NLP_tutorial\">repository<\/a> associated with this post.<\/p>\n<h4 id=\"sentence-level-representation\">Sentence level representation<\/h4>\n<p>A quick way to get a sentence embedding for our classifier is to average Word2Vec scores of all words in our sentence. This is a Bag of Words approach just like before, but this time <strong>we only lose the syntax of our sentence, while keeping some semantic information.<\/strong><\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/w2v.png\"\n         alt=\"Word2Vec sentence embedding\"\/><figcaption>\n            <p>Word2Vec sentence embedding<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Here is a visualization of our new embeddings using previous techniques:<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/pca_w2v.png\"\n         alt=\"Visualizing Word2Vec embeddings.\"\/><figcaption>\n            <p>Visualizing Word2Vec embeddings.<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>The two groups of colors look even more separated here, our new embeddings should help our classifier find the separation between both classes. After training the same model a third time (a Logistic Regression), we get <strong>an accuracy score of 77.7%<\/strong>, our best result yet! Time to inspect our model.<\/p>\n<h4 id=\"the-complexityexplainability-trade-off\">The Complexity\/Explainability trade-off<\/h4>\n<p>Since our embeddings are not represented as a vector with one dimension per word as in our previous models, it\u2019s harder to see which words are the most relevant to our classification. While we still have access to the coefficients of our Logistic Regression, they relate to the 300 dimensions of our embeddings rather than the indices of words.<\/p>\n<p>For such a low gain in accuracy, losing all explainability seems like a harsh trade-off. However, with more complex models we can leverage <strong>black box explainers<\/strong> such as <a href=\"https:\/\/arxiv.org\/abs\/1602.04938\">LIME<\/a> in order to get some insight into how our classifier works.<\/p>\n<p><strong>LIME<\/strong><\/p>\n<p>LIME is <a href=\"https:\/\/github.com\/marcotcr\/lime\">available on Github<\/a> through an open-sourced package. A black-box explainer allows users to explain the decisions of any classifier <strong>on one particular example<\/strong> by perturbing the input (in our case removing words from the sentence) and seeing how the prediction changes.<\/p>\n<p>Let\u2019s see a couple explanations for sentences from our dataset.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/correct_lime.png\"\n         alt=\"Correct disaster words are picked up to classify as \u201crelevant\u201d.\"\/><figcaption>\n            <p>Correct disaster words are picked up to classify as \u201crelevant\u201d.<\/p>\n        <\/figcaption>\n<\/figure>\n\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/incorrect_lime.png\"\n         alt=\"Here, the contribution of the words to the classification seems less\u00a0obvious.\"\/><figcaption>\n            <p>Here, the contribution of the words to the classification seems less\u00a0obvious.<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>However, we do not have time to explore the thousands of examples in our dataset. What we\u2019ll do instead is run LIME on a representative sample of test cases and see which words keep coming up as strong contributors. Using this approach we can get word importance scores like we had for previous models and validate our model\u2019s predictions.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/w2v_importance.png\"\n         alt=\"Word2Vec: Word importance\"\/><figcaption>\n            <p>Word2Vec: Word importance<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p>Looks like the model picks up highly relevant words implying that it appears to make understandable decisions. These seem like the most relevant words out of all previous models and therefore we\u2019re more comfortable deploying in to production.<\/p>\n<h3 id=\"step-8-leveraging-syntax-using-end-to-end-approaches\">Step 8: Leveraging syntax using end-to-end approaches<\/h3>\n<p>We\u2019ve covered quick and efficient approaches to generate compact sentence embeddings. However, by omitting the order of words, we are discarding all of the syntactic information of our sentences. If these methods do not provide sufficient results, you can utilize more complex model that take in whole sentences as input and predict labels without the need to build an intermediate representation. A common way to do that is to treat a sentence as <strong>a sequence of individual word vectors<\/strong> using either Word2Vec or more recent approaches such as <a href=\"https:\/\/nlp.stanford.edu\/projects\/glove\/\">GloVe<\/a> or <a href=\"https:\/\/arxiv.org\/abs\/1708.00107\">CoVe<\/a>. This is what we will do below.<\/p>\n<figure><img src=\"https:\/\/www.mlpowered.com\/images\/cnn_architecture.png\"\n         alt=\"A highly effective end-to-end architecture (source)\"\/><figcaption>\n            <p>A highly effective end-to-end architecture (<a href=\"https:\/\/arxiv.org\/abs\/1408.5882\">source<\/a>)<\/p>\n        <\/figcaption>\n<\/figure>\n\n<p><a href=\"https:\/\/arxiv.org\/abs\/1408.5882\">Convolutional Neural Networks for Sentence Classification<\/a> train very quickly and work well as an entry level deep learning architecture. While Convolutional Neural Networks (CNN) are mainly known for their performance on image data, they have been providing excellent results on text related tasks, and are usually much quicker to train than most complex NLP approaches (e.g. <a href=\"http:\/\/colah.github.io\/posts\/2015-08-Understanding-LSTMs\/\">LSTMs<\/a> and <a href=\"https:\/\/www.tensorflow.org\/tutorials\/seq2seq\">Encoder\/Decoder<\/a> architectures). This model preserves the order of words and learns valuable information on which sequences of words are predictive of our target classes. Contrary to previous models, it can tell the difference between \u201cAlex eats plants\u201d and \u201cPlants eat Alex.\u201d<\/p>\n<p>Training this model does not require much more work than previous approaches (see <a href=\"https:\/\/github.com\/hundredblocks\/concrete_NLP_tutorial\/blob\/master\/NLP_notebook.ipynb\">code<\/a> for details) and gives us a model that is much better than the previous ones, <strong>getting 79.5% accuracy<\/strong>! As with the models above, the next step should be to explore and explain the predictions using the methods we described to validate that it is indeed the best model to deploy to users. By now, you should feel comfortable tackling this on your own.<\/p>\n<h3 id=\"final-notes\">Final Notes<\/h3>\n<p>Here is a quick recap of the approach we\u2019ve successfully used:<\/p>\n<ul>\n<li>Start with a quick and simple model<\/li>\n<li>Explain its predictions<\/li>\n<li>Understand the kind of mistakes it is making<\/li>\n<li>Use that knowledge to inform your next step, whether that is working on your data, or a more complex model.<\/li>\n<\/ul>\n<p>These approaches were applied to a particular example case using models tailored towards understanding and leveraging short text such as tweets, but the ideas are <strong>widely applicable to a variety of problems<\/strong>. I hope this helped you, if you have comments or questions, feel free to reach out on <a href=\"https:\/\/twitter.com\/mlpowered\">Twitter<\/a>.<\/p>\n"}]}}