<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kunj Mehta on Medium]]></title>
        <description><![CDATA[Stories by Kunj Mehta on Medium]]></description>
        <link>https://medium.com/@kunjmehta10?source=rss-ab5f9f992f70------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M53yqcP-vojKHPIqUkQV-g.jpeg</url>
            <title>Stories by Kunj Mehta on Medium</title>
            <link>https://medium.com/@kunjmehta10?source=rss-ab5f9f992f70------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:08:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kunjmehta10/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[5-Minute Paper Explanations: Food AI Part IV]]></title>
            <link>https://medium.com/data-science/5-minute-paper-explanations-food-ai-part-iv-902e5131fd8d?source=rss-ab5f9f992f70------2</link>
            <guid isPermaLink="false">https://medium.com/p/902e5131fd8d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[multimodal-learning]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Kunj Mehta]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 14:26:46 GMT</pubDate>
            <atom:updated>2022-09-07T14:26:46.794Z</atom:updated>
            <content:encoded><![CDATA[<h4>Intuitive deep dive of im2recipe related paper “Transformer Decoders with Multimodal Regularization for Cross-Modal Food Retrieval”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FcL1qGEatUCXFy60" /><figcaption>Photo by <a href="https://unsplash.com/@islandsandsunsets?utm_source=medium&amp;utm_medium=referral">Olayinka Babalola</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction to the Problem</h3><p>Welcome to part fourth and last part of the Food AI series of papers!</p><p><a href="https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-i-9276b61873c1">Part 1</a>: “Learning Cross-modal Embeddings for Cooking Recipes and Food Images”</p><p><a href="https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-ii-c085b2789bd1">Part 2</a>: “Dividing and Conquering Cross-Modal Recipe Retrieval: from Nearest Neighbours Baselines to SoTA”</p><p><a href="https://medium.com/towards-data-science/5-minute-paper-explanations-food-ai-part-iii-bd7256473c4d">Part 3</a>: “Cross-Modal Retrieval and Synthesis (X-MRS): Closing the Modality Gap in Shared Representation Learning”</p><p>As mentioned in previous articles, these explanations aim at charting the progress of research in a particular domain of machine learning. So, today, we will be looking at the <a href="https://arxiv.org/abs/2204.09730">paper</a> titled “Transformer Decoders with Multimodal Regularization for Cross-Modal Food Retrieval” published in 2022. This paper furthers research on the im2recipe problem introduced <a href="http://pic2recipe.csail.mit.edu/im2recipe.pdf">here</a> and explained in <a href="https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-i-9276b61873c1">Part I</a> of this series by primarily 1) <strong>using cross-modal vanilla transformers and attention</strong>, that is, attention over the <em>image and text encodings</em> together instead of just the <em>text</em> as in Part III; 2) using the very powerful <strong>Vision and Language Pre-trained (VLP) model CLIP</strong>; 3) <strong>using a dynamic triplet loss</strong> that mimics curriculum training; 4)<strong> using a multi-modal regularization technique</strong> instead of regularizing via the tasks of classification as in Part I and via generation as in Part III.</p><p>An aside here: VLP aims to learn multi-modal representations from a large dataset of image-text pairs. This pretrained model can then be used in downstream vision-language tasks such as this one after finetuning on the Recipe1M dataset. The VLP models adopt a CNN-Transformer architecture, which embeds images with a CNN, and then aligns images and texts with a Transformer. A very good overview of VLP models is presented <a href="https://theaisummer.com/vision-language-models/">here</a></p><h3>Related Work and Improvements</h3><p><strong>One: </strong>In previous papers we saw that the text encodings can either be encoded separately for each component (ingredient, instructions, title) or together. The improvement made here in this paper is sort of encoding the text encodings both independently and together. The authors use a hierarchical transformer module to encode the components separately first, and use those outputs to get the final text encoding.</p><p><strong>Two: </strong>The image encoder is no longer just a convolutional neural network but rather a vision transformer pre-trained on VLP tasks. This ensures the power of the transformer is leveraged while learning image encodings as well, and not just text encodings, as before.</p><p><strong>Three: </strong>Previously, we had a separate regularization module either through classification (incorporating Food-101 or other classification dataset information) or image generation (making generated image distribution similar to actual image distribution). Here, we again have a regularizer but this one is more complex. It uses vanilla transformers and cross-attention between the image and text encodings to make them as similar to each other as possible, for the same recipe. What’s more is that this module is used only during training, and removed during test and inference.</p><p><strong>Four: </strong>Dynamic triplet loss that acts similar to curriculum training is introduced</p><h3>Architecture: TFood</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*Hfq4TbHp1ksa0R_jkrUZ_g.png" /><figcaption>Overall architecture (from paper, by author)</figcaption></figure><p>The overall architecture can be seen above and is quite similar to all the other architectures we have seen till now. We have an image and an image encoder, the corresponding text and text encoder. The encodings are then projected onto a shared space. Some losses are applied, while these encodings are also passed to a “MMR” module. This module works as both an alignment and regularizer module thus complementing triplet loss and replacing GANs / semantic regularization via classification, respectively.</p><p><strong>Image Encoder: </strong>As mentioned before, the image encoder is a Vision Transformer (specifically, finetuned CLIP ViT B/16) ensuring that we reap the benefits of a transformer for image encodings as well. As before, with transformers we use the output of the [CLS] token as the encoding for the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*QSKA-z0dpnAfZHV8oSk3WA.png" /><figcaption>Text encoder in detail (from paper, by author)</figcaption></figure><p><strong>Text Encoder: </strong>The text encoder is hierarchical. As in part II, we have separate transformers <strong><em>T </em></strong>encoding the title, instructions and ingredients. Here, the instructions and ingredients are encoded one ingredient or instruction at a time. Next, we have separate transformers <strong><em>HT </em></strong>that encode the sequence of instruction and ingredient encodings. Now, obviously encoding each component separately will lead to the model not learning how they relate to each other. So, the authors use transformer decoders <strong><em>HTD </em></strong>to achieve this.</p><p>The way these decoders work is for each decoder, the query Q is the output of the corresponding <strong><em>HT </em></strong>while the key K and value V is the concatenation of the output of the other two <strong><em>HT.</em></strong> For example, for the ingredient decoder, the query is the ingredient and the key and value is the concatenation of the title and instruction. This means we are cross-attending the ingredients on both the title and instructions. <strong>This basically, achieves complete independence on how the different data formats are encoded while also being able to learn the relation between them.</strong></p><p>Note here that for text, we work with the whole output of the transformer and not just the [CLS] token. The final recipe encoding is obtained by averaging values of all output tokens of the <strong><em>HTD</em></strong>, concatenating this averaged output across all <strong><em>HTD </em></strong>and projecting to a shared space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*tLlwvJB18xwY2MAiIet-cQ.png" /><figcaption>Multimodal regularization + alignment module (from paper, by author)</figcaption></figure><p><strong>Multimodal Regularization: </strong>Note that this module is used only during training time and it replaces the simple projection onto a shared space followed by contrastive (triplet) loss that was being done previously to align the text and image encodings. Instead we have a transformer decoder using cross-attention where the queries Q come from one modality and the keys and values K, V (which are the same) come from the other modality.</p><p>In this module, we have two sub-modules. Image Tokens Enhancement Module (ITEM) is a “transformer decoder that takes the image tokens as queries and text tokens as keys and values”. This “enriches the image tokens by attending to the text elements. The Multimodal Transformer Decoder (MTD) is the submodule that actually applies cross-attention on the recipe tokens and the enhanced image tokens. The matching score that measures the level of alignment between image and text tokens is obtained as given in below diagram. The matching score is not the cosine similarity as in previous papers but a score in the range [0,1] output by the decoder directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*cgxh6adJDhK-ISD_3Hbapw.png" /><figcaption>MTD matching score equation (image by author, from paper)</figcaption></figure><p>So, in summary we have a VLP pre-trained Vision Transformer for encoding images, a hierarchical transformer module to encode the text (first for individual components and then by cross-attention between these components). Both the image and text encodings are then projected to a shared space where: 1) the image encodings are passed through the encoding enhancer ITEM which attends to the text elements; 2) the enhanced image encodings and text encodings are passed through a multimodal transformer decoder that is used to calculate the matching or alignment score.</p><h3>Loss Function</h3><p><strong>Image-Text Matching Loss: </strong>ITM is a BCE loss that tracks whether or not an image-text pair matches. The sampling process followed for calculating this loss is that of hard negative mining. We see below that the equation is pretty similar to the actual BCE loss function. <em>y </em>is 1 for a matching image-text pair and 0 otherwise and <em>s </em>is the score output from the decoder. The cross-entropy is then calculated between these two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*SD7yIqGqpMfCZTJlLRdvXA.png" /><figcaption>ITM loss (image by author, from paper)</figcaption></figure><p><strong>Triplet Loss / IncMargin Loss: </strong>The triplet loss proposed is the normal triplet loss with an adaptive margin. The margin is kept between an acceptable range with the margin being small (and hence easier to optimize) when starting and increasingly becoming larger.</p><p>Now, the authors also adapt the dynamic triplet loss (called IncMargin) by using an adaptive weighing strategy for the triplets as in the <a href="https://arxiv.org/abs/1804.11146">Adamine paper</a>. Normally, how the triplet loss works is that the update for each mini-batch is obtained by averaging the gradient for each triplet in the mini-batch. The problem is that after many epochs, some of the triplets have converged and have zero gradient for the loss. Using some math magic (not gonna go into details here), the adaptive weighing strategy manages to give more weight to triplets that have not yet converged.</p><p><strong>Semantic Loss: </strong>The authors also use another triplet-type loss which captures the semantics of a given query image and recipe images similar to the query. For example, any two pizzas should be closer in the latent space than a pizza and another item from any other class, like salad. This optimization is done directly in the latent space together with the other optimizations. This contrasts with using a separate classification regularization module as in Part I.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*0mfY1LRQJWVI7NzcSTJhYA.png" /><figcaption>Semantic triplet type loss (image by author, from Adamine paper)</figcaption></figure><p>Here, <em>xq </em>is the query, <em>xₚ</em> belongs to the same semantic class as the query, and <em>xₙ</em> belongs to the semantic class different from the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*JVxIpDiROWHTBM7oL7z06Q.png" /><figcaption>Total loss (image by author, from paper)</figcaption></figure><h3>Experiments and Results</h3><p>Different models used in the experiments: ViT-B/16 and CLIP-ViT-B/16 as image encoders; for the recipe encoder, the transformer encoders have 2 layers and 4 heads for the hierarchical transformers <strong><em>T</em></strong> and <strong><em>HT</em></strong>. <strong><em>HTD</em></strong> uses a transformer decoder (wihout masking) with 2 layers and 4 heads. The hidden layer dimension is kept 512 in the recipe encoder. The image and recipe embeddings are obtained with a different linear layers of output dimension 1024. The image and recipe tokens are then projected using different linear layers of the same output dimension of 1024 before going to the <strong><em>MMR</em></strong> module. The <strong><em>ITEM </em></strong>module consists of a transformer decoder of only 1 layer and 4 heads with hidden size 1024. The <strong><em>MTD</em></strong> consists of a transformer decoder with 4 layers, 4 heads and hidden dimension 1024.</p><p>The actual numbers aside, we can see from the results in the paper that using CLIP-ViT initialized from the CLIP weights works best in this architecture. Another notable observation is that as the sample size for testing increases from 10k, the difference in performance between TFood and the others increases meaning TFood is more scalable.</p><p>From the ablation studies, the following points are validated: 1) <strong><em>HTD </em></strong>leads to better alignment hence proving that the recipe components are entangled and should not be encoded separately; 2) <strong><em>MTD </em></strong>brings additional improvement showing multi-modal transformers are a good module to add in problems like these. Furthermore, both adaptive triplet loss and ViT also bring significant additional improvements.</p><h3>Personal Thoughts</h3><p>This paper looks very tough to understand but is actually very simple because the only thing it uses is transformers. I am of the opinion that it benefits very much from the discovery of Vision Transformers. The idea of using transformers everywhere also seems to have worked. This paper is also more satisfying to the mind because the authors have been able to separate the learning of every encoding, and also the relationship between these encodings, using the transformer decoder. One issue with the method in this paper, though, is the complexity in terms of computation and resources that is required.</p><p>This is the final part of the Food AI series I have started in my sequence of intuitive paper explanations. I am picking a subdomain in the industry and going through papers in that domain. <strong>The next sequence I will be writing will be on VLP models</strong>. If you like what I write, consider subscribing or following me <a href="https://www.medium.com/@kunjmehta10">here</a> or connecting with me on <a href="http://www.linkedin.com/in/kunjmehta">Linkedin</a> or <a href="https://www.twitter.com/@kunjmehta10">Twitter</a>! For codes pertaining to my previous Medium articles, visit my <a href="https://github.com/kunjmehta/Medium-Article-Codes">GitHub</a>.</p><p><strong>Paper Citation</strong></p><p>[1] Shukor, Mustafa and Couairon, Guillaume and Grechka, Asya and Cord, Matthieu, “Transformer Decoders with MultiModal Regularization for Cross-Modal Food Retrieval”. 2022</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=902e5131fd8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/5-minute-paper-explanations-food-ai-part-iv-902e5131fd8d">5-Minute Paper Explanations: Food AI Part IV</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5-Minute Paper Explanations: Food AI Part III]]></title>
            <link>https://medium.com/data-science/5-minute-paper-explanations-food-ai-part-iii-bd7256473c4d?source=rss-ab5f9f992f70------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd7256473c4d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Kunj Mehta]]></dc:creator>
            <pubDate>Mon, 22 Aug 2022 14:08:39 GMT</pubDate>
            <atom:updated>2022-08-22T14:08:39.141Z</atom:updated>
            <content:encoded><![CDATA[<h4>Intuitive deep dive of im2recipe related paper “Cross-Modal Retrieval and Synthesis (X-MRS): Closing the Modality Gap in Shared Representation Learning”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sId4RP3Us-OcrpcD" /><figcaption>Photo by <a href="https://unsplash.com/@luisabrimble?utm_source=medium&amp;utm_medium=referral">Luisa Brimble</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction to the Problem</h3><p>Welcome to part three of the Food AI series of papers!</p><p><a href="https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-i-9276b61873c1">Part 1</a>: “Learning Cross-modal Embeddings for Cooking Recipes and Food Images”</p><p><a href="https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-ii-c085b2789bd1">Part 2</a>: “Dividing and Conquering Cross-Modal Recipe Retrieval: from Nearest Neighbours Baselines to SoTA”</p><p>As mentioned in previous articles, these explanations aim at charting the progress of research in a particular domain of machine learning. So, today, we will be looking at the <a href="https://arxiv.org/abs/2012.01345">paper</a> titled “Cross-Modal Retrieval and Synthesis (X-MRS): Closing the Modality Gap in Shared Representation Learning” published in 2020. This paper furthers research on the im2recipe problem introduced <a href="http://pic2recipe.csail.mit.edu/im2recipe.pdf">here</a> and explained in <a href="https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-i-9276b61873c1">Part I</a> of this series by using a <strong>transformer based text encoder </strong>instead of LSTM in the original, and Average Word Embeddings in the paper <a href="https://arxiv.org/abs/1911.12763">here</a> (explained in <a href="https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-ii-c085b2789bd1">Part II</a>). Furthermore, the authors of X-MRS use <strong>multilingual translation to regularize the model</strong> while adding multi-lingual functionality, and show the <strong>power of the learned embeddings through a generative model</strong> that generates food images.</p><h3>Related Work and Improvements</h3><p>As we have seen in previous parts of this series, previous work on the cross-modal recipe task featured either models that were trained end-to-end, or pre-trained encoders that were finetuned on the recipe data on top of which a cross-modal alignment module was applied. In the latter case, there are also methods which encoded each textual component (viz. title, ingredients and instructions) separately and then concatenated the individual embeddings.</p><p>Previous work also used a regularization module mainly using some external data to setup a classification or clustering task over the learnt representations. Some other papers which we have not seen, used GANs to regularize the model. How would this work, you ask. Well, based on the performance of the GAN, i.e., its ability to generate realistic food images, the representations being learnt would be modified. Here, the GANs effectively work as decoders (from embeddings to actual images), and “learning decoders in high-dimensional space is a complex task, which can lead to sub-optimal representations.”</p><p>The authors differ in their approach with the aforementioned ones by 1) they do not treat and encode the different components of the textual data independently; 2) their models are trained end-to-end and not pre-trained; 3) they do not use GANs or setup a classification task to regularize the learnt representations. Instead, they use multilingual encoding and back-translation for this.</p><p>This offers an opportunity to attend to the real-world use case of having the im2recipe application be applied to different languages around the world. Back-translation is a concept where for example, a sentence is translated from English to French and back to English. Then the original English sentence and the “back-translated” Englished sentence which are in effect paraphrases of each other, can be compared and used for regularization</p><p>Aside: Many famous and super-large generative image models in the world right now are text induced conditional image synthesis models. This means that these models are trained to generate images on the basis of encoding of some text description given to them. These current models can take in a long description that describes the image and synthesize the image, but the authors of the X-MRS paper refer to papers, and to a time when the textual descriptions for these kind of models had to be short to make them work. In addition, none of the textual descriptions had an inherent sequence to them being modified over time, as is the case for recipe ingredients and instructions. And this is the improvement the authors make when building their own image synthesis model from the learned embeddings.</p><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUrFLPRpZFH0BJ8v2YkIBw.png" /><figcaption>Model architecture (Image by Author, from paper)</figcaption></figure><h4>Encoders</h4><p>For encoding the images, ResNet-50 is used. The “last fully connected layer of ResNet-50 is replaced by 2, 1024-dimensional fully connected layers with the last layer being shared with the textual encoder”.</p><p>The textual data is not treated separately for each component. Instead, the title, instruction and ingredient is treated as one long text description, tokenized using <a href="https://huggingface.co/docs/transformers/tokenizer_summary#wordpiece">WordPiece</a> tokenizer, embedded into a dimension size of 768 and passed through a 2-layer 2-head transformer encoder (emphasis: just the encoder of the transformer). Note here that the output of the tokenizer also includes a <a href="https://stackoverflow.com/questions/62705268/why-bert-transformer-uses-cls-token-for-classification-instead-of-average-over">[CLS] (classification) token</a> and both of them are trimmed to result in just 512 tokens to control memory footprint of the model.</p><p>Those who have worked with transformers would know that the [CLS] token can be thought of and used as an aggregate sequence representation, which is what the authors also do. The output of the [CLS] token is “passed through two 1024 dimensional FC layers, before a final 1024 dimensional FC layer projects the text encoding into the shared representation space”.</p><h4>GAN Synthesis Module</h4><p>The logic behind using a GAN is two-fold: 1) if the learnt representations are good enough, the GAN should be able to generate images that actually show the recipe ingredients in the image, apart from the image being realistic; 2) just using the trained GAN in a stand-alone application, we would be able to generate a realistic image of a given recipe if the ingredients and instructions are provided, even if its not in the training data.</p><p>The GAN module is based on StackGAN where the “intermediate resolution images are discarded”. The discriminator of the GAN also has a recipe classifier, similar to the one seen in Part I leveraging class information constructed from the Recipe1M and other datasets. Next, as discussed previously, the GAN has to be conditioned on text to generate an image. So, in the module, the recipe encoding is passed through a “conditional augmentation sub-network” to create a conditioning code which is passed to the decoder (along with noise) to generate the image. The discriminator then attempts to classify real from fake, and put the image into its correct recipe class.</p><h3>Loss Function</h3><p>Note: Added some notations for better understanding below. For all notations, please refer paper.</p><h4>Encoders</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*1EufyOnFwJH9lIN9MdL4WA.png" /><figcaption>Encoding loss function (Image by Author, from paper)</figcaption></figure><p>For learning the representations, the encoders use a simple triplet with margin loss where the similarity between the anchors, positives and negatives is calculated using cosine similarity function. The anchor can either be a image or text encoding and the positive will be the corresponding text or image encoding from the same recipe, while the negative will be the image or text encoding from a different recipe.</p><p>The sampling strategy followed for the anchors, positives and negatives is that of hard negative mining. In this, the negative that is selected is of a different class but it has the highest similarity with the anchor among all other negatives.</p><h4>GAN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJ90CToekzhdRU9jqevhNQ.png" /><figcaption>Discriminator training loss (Image by Author, from paper)</figcaption></figure><p>As mentioned before, the discriminator tries to classify real from fake and also classify the image into its correct recipe class. Losses corresponding to both of these tasks are added to get the final discriminator loss. The loss is a simple cross-entropy loss.</p><p><strong><em>x</em>₁ </strong>is the actual image encoding, <strong><em>G(v₂, z) </em></strong>is the generated image where <strong><em>z </em></strong>is Gaussian noise. <strong><em>E(x₁ ~ x₁data) </em></strong>represents that the data comes from the image encoder. <strong><em>E(v₂ ~ v₂data) </em></strong>represents that the data comes from the text encoder which is then passed onto the generator. <strong><em>Dᵣ</em></strong> and <strong><em>D𝒸 </em></strong>are sub-networks inside the discriminator representing the networks that classify real from fake, and recipe classes respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V2ZaQms9cYdtv68zOmkEzg.png" /><figcaption>Generator training loss (Image by Author, from paper)</figcaption></figure><p>The generator loss is basically one minus the discriminator loss plus the regularization terms from the Conditional Augmentation (CA) subnetwork and the supervision term <strong><em>ret. </em></strong>The CA loss is the KL Divergence of the Gaussian with the mean and standard deviation from the text encoding and the unit Gaussian, while the supervision term enforces that the generator generate the “correct” food images having the “correct” ingredients by forcing the distance between the representation of the (fake image, text) and (fake image, real image) be minimized. The latter part is pretty self-explanatory.</p><h3>Experiments and Results</h3><p>The experiments are conducted on the Recipe1M dataset. “R1M English (EN) recipes were augmented via back translation from German (EN- DE-EN) and Russian (EN-RU-EN). Translations from/to German, Russian and French were obtained using pre-trained models from the <a href="https://fairseq.readthedocs.io/en/latest/">fairseq</a> neural translation toolbox.”</p><p>Retrieval results are reported using the same metrics as in Part II. “For the GAN synthesis model, besides reporting the retrieval performance on synthetic food images, Fretchet Inception Distance (FID) score, which measures the similarity between real and synthetic image distributions is also calculated.” Lower FID values indicate better performance.</p><p>During training and evaluation, some augmentation performed by the authors is:</p><p><strong>Image augmentation:</strong> 1) Random input image for sample recipes with more than one. 2) Randomly select, pad (with a random choice between zeros, edge duplication or image reflection) to square and resized to 256, or resized to 256. 3) Random rotation ±10◦ 4) Randomly cropped to 224. 5) Random horizontal flip.</p><p><strong>Recipe augmentation:</strong> 1) Randomly select between original EN representation and back translation from EN-DE-EN or EN-RU-EN. 2) Random selection between previous EN choice and either KO, DE, RU or FR.</p><p>As always, exact results can be referred to from the paper. Here, we focus on the analysis of the results. One very significant result is that the X-MRS model with transformer-based text encoder is not able to surpass the baseline we walked through in Part II of this series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fiW58tqoQXUnKJQTjqEGbg.png" /><figcaption>Image-to-recipe qualitative top-3 retrieval results with attention. Leftmost image is query image with corresponding recipe. In both languages, we can see that the textual attention map is focused on things that describe the image the best. (Image by Author, from paper)</figcaption></figure><p>The authors also perform ablation studies where they test retrieval performance using different textual data components. It is observed that using all the information leads to best performance (duh!), followed by instructions + ingredients. This makes the title the least informative. Again, not surprising! Very early research into food classification was already working with just titles and not getting far. <strong>One interesting thing here is using the full ingredient text as in the dataset, and not just the extracted ingredient names leads to better retrieval performance.</strong></p><p>Retrieval results for different languages are also presented. It should be noted here that the paper’s overall best performing retrieval model that also beats the CkNN baseline is the one trained on multi-lingual data and uses English for retrieval. And it is not mentioned in the paper, exactly how the multi-lingual training is done.</p><p>For the synthesis module, the realism of the generated images and the retrieval performance of recipe given the synthesized image is tested. It is observed that there are models that do better in generating more realistic food images, but the proposed model trained on multi-lingual data is the best in retrieval. Plus, the retrieval using synthetic images is better than using real images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ob_u5l1E1Zn_Fy3lD_HGkg.png" /><figcaption>Recipe to image synthesis examples. (Image by Author, from paper)</figcaption></figure><p>Because the generator is trained to generate food images based on a full recipe embedding, meaning it also has the corresponding textual information, it is easier to have a higher recall than when using the original images (which do not contain textual information). So, to test the purity of the image-text learnt representations, the authors perform an experiment where they train the generator to generate images conditioned on the image embedding (and not the text embedding). They find that the realism of the generated images does not degrade, but the retrieval performance does. This makes sense because now the generated images do not contain textual information, showing that the textual and image embeddings are independent, but close enough in the shared space not to affect the realism of the generated images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOGBl97ADzpWTwcvFaVACA.png" /><figcaption>Image synthesis using text data in different languages (Image by Author, from paper)</figcaption></figure><h3>Personal Thoughts</h3><p>The fact that the X-MRS model without multi-lingual training cannot surpass the CkNN baseline from Part II goes on to show the power of a strong theoretically sound pipeline, no matter if it uses traditional methods or modern “cool” deep networks. That being said, the use of a transformer has been done properly in the pipeline and the idea of augmenting and regularizing with the help of multi-lingual data and back-translation is a cool one, which also works.</p><p>This is one of the papers that relies more on experimental analysis than theoretical intuitions. The analysis of generated recipe images shines a different perspective onto how the learnt embeddings can be analyzed and it even shows that if learnt properly, the image encoding and text encoding can be interchanged, as it should be.</p><p>This is part three of a new series I have started on intuitive paper explanations. I am picking a subdomain in the industry and going through papers in that domain. If you like what I write, consider subscribing or following me <a href="https://www.medium.com/@kunjmehta10">here</a> or connecting with me on <a href="http://www.linkedin.com/in/kunjmehta">Linkedin</a> or <a href="https://www.twitter.com/@kunjmehta10">Twitter</a>! For codes pertaining to my previous articles visit my <a href="https://github.com/kunjmehta/Medium-Article-Codes">GitHub</a></p><p><strong>Paper Citation</strong></p><p>[1] Ricardo Guerrero, Hai Xuan Pham and Vladimir Pavlovic, “Cross-modal Retrieval and Synthesis {(X-MRS): Closing the modality<br> gap in shared subspace”. CoRR, 2020</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd7256473c4d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/5-minute-paper-explanations-food-ai-part-iii-bd7256473c4d">5-Minute Paper Explanations: Food AI Part III</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5-Minute Paper Explanations: Food AI Part II]]></title>
            <link>https://medium.com/data-science/5-minute-paper-explanations-food-ai-part-ii-c085b2789bd1?source=rss-ab5f9f992f70------2</link>
            <guid isPermaLink="false">https://medium.com/p/c085b2789bd1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-lear]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[multimodal-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Kunj Mehta]]></dc:creator>
            <pubDate>Thu, 18 Aug 2022 09:41:57 GMT</pubDate>
            <atom:updated>2022-08-21T21:24:44.237Z</atom:updated>
            <content:encoded><![CDATA[<h4>Intuitive deep dive of im2recipe related paper “Dividing and Conquering Cross-Modal Recipe Retrieval: from Nearest Neighbours Baselines to SoTA”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*drewTtEmZEDLLqWI" /><figcaption>Photo by <a href="https://unsplash.com/es/@briewilly?utm_source=medium&amp;utm_medium=referral">Chad Montano</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction to the Problem</h3><p>Welcome to part two of the Food AI series of papers! <a href="https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-i-9276b61873c1">Last week</a>, I wrote an article explaining the seminal im2recipe paper that introduced cross-modality into dealing with machine learning related to food applications such as searching for the correct recipe using a photo, automatically determining the number of calories in a dish or improving the performance of various recipe recommendation and ranking systems. I refer the reader to that article for an introduction and motivation to the problem and for details regarding the Recipe1M dataset and evaluation metrics.</p><p>As mentioned in the previous article, these explanations aim at charting the progress of research in a particular domain of machine learning. So, today, we will be looking at the <a href="https://arxiv.org/abs/1911.12763">paper</a> titled “Dividing and Conquering Cross-Modal Recipe Retrieval: from Nearest Neighbours Baselines to SoTA” published in 2019. This paper furthers research on the im2recipe problem introduced <a href="http://pic2recipe.csail.mit.edu/im2recipe.pdf">here</a> and explained <a href="https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-i-9276b61873c1">here</a> by <strong>defining a different and better baseline for comparison of the retrieval task</strong> at hand. This baseline intends to replace the CCA baseline in the original paper.</p><h3>Related Work and Improvements</h3><p>The reasons for improving the baseline are: <strong>1)</strong> “the CCA baseline for Recall@1 was 14.0 on a test set of 1,000 recipes. This result was eclipsed and quadrupled inside two years to reach 51.8” The authors argue that this has more to do with “mis-specified baselines” rather than genuine improvement in retrieval methods. <strong>2)</strong> <strong>In the original im2recipe paper, the model was trained end-to-end</strong> and hence it was difficult to understand how each element of the model was performing individually(the elements being the image encoder, text encoder, etc). This is overcome by building a conceptually simple and interpretable model to serve as a baseline for the problem.</p><p>Specifically, the retrieval function in the model is a cross-modal adaptation of the kNN algorithm called the <strong>CkNN</strong> “applied on top of pre-computed image-text embeddings where the image and text encoders are <strong>not trained end-to-end with CkNN but independently using self-supervision</strong>.” This makes it easy to test and analyze their performance in separation.</p><p>Lastly, the authors extend this method to obtain a new state-of-the-art performance on the problem.</p><p>Some important related work that the paper references (apart from the im2recipe paper):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*EVZOpRSlicRA8r0LZXYn2g.png" /><figcaption>AdaMine Double Triplet Loss (Image by Author, from paper)</figcaption></figure><ol><li><a href="https://arxiv.org/pdf/1804.11146.pdf">AdaMine</a> - The alignment module was improved by using “double triplet loss” as the loss function. Simply, this is triplet loss applied to two sets of triplets: one set that represents individual image-pair instances and helps the model learn to map embeddings from the different modalities for individual recipes together, and the other set representing classes of image-pair instances which helps the model learn, through the class information, which recipes are similar to each other. The latter is similar to semantic regularization in the im2recipe paper.</li><li>R2GAN - used GANs to help learn better image and text embeddings</li><li>ACME - This was the state-of-the-art when the CkNN paper was published and used “GANs + cross-modal triplet loss together + modality alignment using an adversarial learning strategy + a cross-modal translation consistency loss”. Not to get into the specifics of how it works (that is probably for another article), but the point is that a really competitive result to ACME can be achieved by CkNN, as we will see soon.</li></ol><h3>Architecture</h3><h4><strong>Encoders</strong></h4><p><strong>Text Encoder (Average Word Embedding): </strong>Average Word Embeddings are a very basic way of encoding text. It is depicted in the image below. For a document (which can be a sentence or a paragraph or anything else), the embedding for the document is generated by calculating an average of the word embeddings in the document. The word embeddings themselves can be generated in many ways.</p><p>In the paper, the way this is done is: “instructions and ingredients are treated as the document and the class labels are the most frequent unigrams and bigrams contained in the recipe title (class generation is similar to im2recipe)”. The word embedding size is <em>d=300 </em>and while it is randomly initialized, the training uses <strong>softmax activation with Binary Cross Entropy loss </strong>on the average of the word embeddings in the document to learn the word embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*00l6gE97lYE23Yz68JTOfQ.png" /><figcaption>Architecture for average word embedding for text modality (Image by Author)</figcaption></figure><p><strong>Image Encoder: </strong>The image embedding is obtained using the last layer before the classification layer of ResNet-50, again regularized using Binary Cross Entropy on a set of class labels generated using the same technique from the recipe title.</p><p>Note here that the set of labels generated for text encoder and image encoder are different (3453 for text and 5036 for image, to be precise). The reason for this is that since the encoders are being trained independently, we are not restricted to solely using image-text pairs as data but we can use data of recipes that include only text or only images. Hence, we have different number of data points for text and image and different classes.</p><h4>CkNN - Cross-Modal kNN</h4><p>CkNN like kNN, is a non-parametric model. It serves as an image-text embedding alignment module, and as with other components in this proposed system, it is applied independently. First the encoders are trained to get the image and text embeddings and then CkNN is applied on top of them. This differs from the im2recipe paper where the system was trained end-to-end and we had transformations to bring the embeddings to a shared space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cyoo9HuLzLuz0g8VN__dtw.png" /><figcaption>CkNN (Image by Author, from paper)</figcaption></figure><p>There are two parts to CkNN: one works in the text embedding space and the other in the image embedding space Let’s see how it works in the text embedding space (follow the numbers in image): [1]</p><ol><li>Encode a <strong>candidate text document</strong> (that is, recipe instructions and ingredients) <em>T</em> using the text encoder <em>e(T)</em></li><li>Find the <em>k</em>ₜ nearest neighbours based on the <strong>text embeddings</strong> using cosine similarity in the text embedding space, denoted by <em>Rₜ</em> .</li><li>Extract the<strong> set of images</strong> <em>Iₜ </em>associated with <em>Rₜ</em> leveraging the Recipe1M dataset</li><li>Encode each <em>I ∈ Iₜ </em>in <strong>the image embedding space</strong> using the image encoder <em>e(I).</em></li><li>Return the mean of the obtained <strong>image embeddings</strong> as the result</li></ol><p>The corresponding algorithm for the image embedding space would be:</p><ol><li>Encode a <strong>candidate image <em>I</em></strong><em> </em>using the image encoder <em>e(I)</em></li><li>Find the <em>k</em>ᵢ nearest neighbours based on the<strong> image embeddings </strong>using cosine similarity in the image embedding space, denoted by <em>R</em>ᵢ .</li><li>Extract the <strong>set of texts</strong> <em>Tᵢ </em>associated with <em>Rᵢ</em> leveraging the Recipe1M dataset</li><li>Encode each <em>T∈ Tᵢ </em>in the<strong> text embedding space</strong> using the text encoder <em>e(T).</em></li><li>Return the mean of the obtained<strong> text embeddings</strong> as the result</li></ol><p>Let’s call the component in the image space as <em>Mᵢ </em>and the component in the text space as <em>Mₜ.</em></p><h3>Loss Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*YXd1vUxHryz8bEAtuWjqmA.png" /><figcaption>CkNN loss function (Image by Author, from paper)</figcaption></figure><p>The loss function is basically a linear combination of the distance between the obtained image and text embeddings in the 1) image embedding space and, 2) text embedding space. Easy!</p><h3>Experiments and Results</h3><p>Not focusing on the exact results which can be seen in the tables in the paper, I will be focusing on their analysis. In short, the results show the retrieval performance measured in the same way as in the original im2recipe paper (plus also with a sample size of 10,000) for the new baseline CkNN and other methods that are used for comparison.</p><p>To prove that training the encoders separately and then applying CkNN to it works as well as training the system end-to-end as in ACME (the state-of-the-art at the time), different combinations of pre-trained image and text encoders from related works are used for generating embeddings, on which CkNN is then used to measure retrieval performance. It is shown that the end-to-end Recall@1 is 20.6 while with CkNN, it is 17.9, which is competitive. This analysis also shows that the quality of the encoders, and not cross-modal alignment is the primary driving force behind improving results in previous research.</p><p><strong>Extension to SoTA</strong></p><p>Finally, encouraged by the above competitive results with ACME, the authors add their own alignment module on top of the CkNN using triplet loss to create a joint embedding space of image and text.</p><p>“Two feed-forward neural networks with one hidden layer, dropout and batch normalization are trained with triplet loss with margin: one for image (<em>gᵢ</em>) and another for textual (<em>gₜ</em>) features.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBLk34F4tRXpDTnQ6NYlsg.png" /><figcaption>Alignment module (Image by Author, from paper)</figcaption></figure><h3>Personal Thoughts</h3><p>Reading this paper makes me think that deep learning is not the only way to go. Sure, the image encoder used here is deep but ResNet has been ruling that domain for some time now. And the actual alignment that is happening is a simple kNN. Adding a MLP to that gets you a state-of-the-art performance! This is a clever paper that takes the concept of cross-modality introduced in the im2recipe paper and instead of improving the results (as most papers would), asks the question from the other side: what if the baseline is too low? And, this gives you a sanity check.</p><p>In conclusion, this paper redefined the baseline for the im2recipe task. The new baseline is created using a very simple architecture which is not trained end-to-end which simplifies model exploration and model comparison. In the next post, we will look at how this new baseline is used in another paper that again improves SoTA performance. Stay tuned!</p><p>This is part two of a new series I have started on intuitive paper explanations. I am picking a subdomain in the industry and going through papers in that domain. If you like what I write, consider subscribing or following me <a href="https://www.medium.com/@kunjmehta10">here</a> or connecting with me on <a href="http://www.linkedin.com/in/kunjmehta">Linkedin</a> or <a href="https://www.twitter.com/@kunjmehta10">Twitter</a>! For codes pertaining to my previous article visit my <a href="https://github.com/kunjmehta/Medium-Article-Codes">GitHub</a></p><p><strong>Paper Citation</strong></p><p>[1] Mikhail Fain, Andrey Ponikar, Ryan Fox and Danushka Bollegala, “Dividing and Conquering Cross-Modal Recipe Retrieval: from Nearest Neighbours Baselines to SoTA”. CoRR, 2019</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c085b2789bd1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/5-minute-paper-explanations-food-ai-part-ii-c085b2789bd1">5-Minute Paper Explanations: Food AI Part II</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Minute Paper Explanations: Food AI Part I]]></title>
            <link>https://medium.com/data-science/5-minute-paper-explanations-food-ai-part-i-9276b61873c1?source=rss-ab5f9f992f70------2</link>
            <guid isPermaLink="false">https://medium.com/p/9276b61873c1</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[multimodal-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kunj Mehta]]></dc:creator>
            <pubDate>Mon, 08 Aug 2022 17:56:29 GMT</pubDate>
            <atom:updated>2022-08-08T17:56:29.619Z</atom:updated>
            <content:encoded><![CDATA[<h4>Intuitive deep dive of the im2recipe paper “Learning Cross-modal Embeddings for Cooking Recipes and Food Images”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZqrtA7Ab65WRZnbq" /><figcaption>Photo by <a href="https://unsplash.com/@briewilly?utm_source=medium&amp;utm_medium=referral">Chad Montano</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction to the Problem</h3><p>Welcome to my new series of paper explanations! You may ask what’s different from what’s out there? Well, I will not be covering the trendy or the famous papers, but instead picking up sub-(sub)domains in machine learning research and charting their research progress through these articles.</p><p>Let’s get started — today, we will learn about the <a href="https://arxiv.org/abs/1905.01273">paper</a> (published in 2018) that introduced a huge dataset for research of machine learning in food and introduced the <em>im2recipe </em>retrieval problem.</p><p><strong>Problem Statement: </strong>Given an image of food (imagine your favourite food here!), retrieve the recipe for making that food. To be able to do so, make model(s) learn the corresponding image and recipe embeddings, transform these embeddings to a shared joint embedding space and minimize a loss that measures retrieval performance of the recipe, given the image. Eezy-peasy, right?</p><p>An aside for people who do not know what cross-modality is: a modality is a type of source of information that we feed into the model. It can be video, image, text, audio, etc. In <em>im2recipe </em>we have image and text. So, we work with two modalities and go from one to the other, hence cross-modal.</p><h3>Domain Background and Improvements</h3><p>There has been previous research crossing food with AI or machine learning. A prominent example with a big dataset is Food-101 and the <a href="https://link.springer.com/chapter/10.1007/978-3-319-10599-4_29">paper</a> that introduced it. This was a <strong>classification problem</strong> over food images. The <em>im2recipe </em>paper by contrast introduces a <strong>retrieval problem</strong> with a much richer dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*BO5x1Qm9gByZkzdhUjWrhg.png" /><figcaption>Some examples of Food-101 dataset classes (Image by Author)</figcaption></figure><p>If we see the classes in the Food-101 dataset, it just contains information about the food name. In the <em>im2recipe </em>dataset called <em>Recipe1M, </em>we not only have a higher number of data points, but those data points include food images, titles (names), instructions on making that dish and ingredients.</p><p>One advantage of this rich data is that we are now able to have sort of a step-by-step information on the state of the recipe through its instructions and ingredients. We can know whether an ingredient is raw, baked, fried, etc. at any stage and theoretically be able to learn corresponding different images at these stages with a good model.</p><h3>Dataset</h3><p>The huge <em>Recipe1M </em>dataset contains 1 million recipe ingredients and instructions and 800 thousand corresponding images of those prepared recipes extracted and downloaded from cooking websites and organized into JSON format files.</p><p>In the text modality, we have a title, a list of ingredients, and a sequence of instructions for preparing the dish. In the second modality, we have any images with which the recipe is associated in RGB/JPEG format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DEhXgmybNjgoCNoEK2MXA.png" /><figcaption>Example of text data for a recipe. The id maps to the images for the corresponding recipe (Image by Author)</figcaption></figure><p>Some analysis the authors have done on the collected dataset:</p><ol><li>The average recipe in the dataset consists of nine ingredients which are transformed over the course of ten instructions.</li><li>Exact duplicates of recipe-image pairs have been removed</li><li>4,000 of the 16,000 ingredients identified account for 95% occurrences of ingredients in the data</li></ol><h3>Architecture</h3><p>As mentioned earlier, there are two modalities and four types of data: title, ingredients, instructions and images. We embed each of them in a different way.</p><p>As shown below, ingredients are first extracted from the ingredients list in the data using bidirectional LSTM and then encoded to a word2vec representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X77Ki-DPzCWR25kYTVmLPA.png" /><figcaption>Learning ingredient embeddings (Image by Author)</figcaption></figure><p>Each of the instruction element is encoded using the <em>skip method </em>as used in word2vec where each instruction has the one before and after it as a target and the encoding is optimized to improve the prediction of these adjacent instructions. The modification made here is that start and end instruction tokens are introduced as well. Next, these individual instructions encodings are passed through a LSTM to produce instruction embedding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJTCDWDjBzurNJWx-GHVKg.png" /><figcaption>Learning instructions embeddings (Image by Author)</figcaption></figure><p>Next, these instruction and ingredient embeddings are concatenated and transformed via an affine transformation (linear transformation with learnt weights and bias) to a shared embedding space. The same is done for image embeddings which the are the features extracted from a pre-trained ResNet-50 / VGG-16.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIFBnB8J6kXPdMW8iq0v0w.png" /><figcaption>Learning Shared Embeddings (Image by Author)</figcaption></figure><p><strong>Semantic Regularization</strong></p><p>In addition to the above primary architecture, the authors also perform regularization by making the joint embedding model (with shared weights) learn to classify any recipe image or text information into one of the Food-101 classes. Intuitively, this ensures that the model roughly knows some embedding clusters (in terms of these classes) already and it does not try to make one cluster for each image-recipe pair, and hence overfit. Because the weights are shared between the two modalities, it also ensures that the image-recipe pair embeddings learnt are aligned to each other (we do not get individual clusters for image and text information for the same dish).</p><p>However, the authors of the paper found that the Food-101 classes only covered 13% of the <em>Recipe1M</em> dataset and so, they augmented it with 946 most frequent bigrams in recipe titles from the <em>Recipe1M</em> training set (after cleaning). Doing this, they achieved a coverage of 50%</p><h3>Loss Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*ejRKksQpkPY2-v80ft8jWg.png" /><figcaption>Cosine similarity with margin loss (Image from paper, by Author)</figcaption></figure><p>The loss function that is used is cosine similarity with margin loss. The training is done in a pairwise fashion similarly to how triplet loss function is trained — with positive and negative image-recipe pairs. This training method and the above loss function ensures that the image-recipe embeddings of the positive pairs (<em>y=1</em>) are brought closer together (the difference closer to 0), and the negative pairs are pushed farther apart with a fixed margin <strong>α </strong>in between.</p><p><strong>Addition of Semantic Regularization</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*6eRYYPuJgnCP-M_HwTJrUw.png" /><figcaption>Combined cosine and regularization loss (Image from paper, by Author)</figcaption></figure><p>With the regularized loss added to get the combined, we can intuitively see the learning process as bringing the image-recipe embeddings of the positive pair together, pushing the image-recipe embeddings of the negative pair farther away while all the time keeping the image-recipe pair embeddings aligned to each other through shared weights and classification. Specifically, if cᵣ and cᵥ (the class predictions for image and recipe embeddings, respectively) are different than the regularization loss will increase, else it will decrease.</p><h3>Experiments and Results</h3><p>This is the way the results are reported: On a subset of randomly selected 1,000 recipe-image pairs from the test set. We repeat the experiments 10 times and report the mean results. We report median rank (MedR), and recall rate at top K (R@K) for all the retrieval experiments.</p><p>If I am retrieving 100 recipes for each image, then median rank is the median of the position the correct recipe came in per pair per experiment. Similarly, R@5 in the im2recipe task represents the percentage of all the image queries where the corresponding recipe is retrieved in the top 5, hence higher is better.</p><p>The baseline result is the result using CCA. As an aside, CCA is a technique much like PCA but for multiple sets of variables. Canonical correlation analysis determines a set of canonical variates, orthogonal linear combinations of the variables within each set that best explain the variability both within and between sets. The detailed results and ablation studies can be seen in the paper, and are pretty self-explanatory</p><p>What I want to focus on here is the analysis of the embeddings. The authors presented using vector arithmetic that the embeddings that the model learns make semantic sense. An example is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*1DqZTSlDhQWLFh6RqCwvlQ.png" /><figcaption>word2vec type vector arithmetic shows semantic meaning in learnt embeddings (Image from paper, by Author)</figcaption></figure><p>The authors also extract and visualize local unit activations using the top activating images, ingredient lists, and cooking instructions for a given neuron, and focusing on specific image and text regions that contribute the most to the activation of these units. Results below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XswzK-hmR5nj5kFzGgcQeg.png" /><figcaption>Specific unit detectors are learnt. Unit 352 learns to detect cream in both images and instruction text, which also shows the models are aligned across modalities (Image from paper, by Author)</figcaption></figure><p>This is part of a new series I am starting on intuitive paper explanations. I will be picking a subdomain in the industry and going through papers in that domain. If you like what I write, consider subscribing or following me <a href="https://www.medium.com/@kunjmehta10">here</a> or connecting with me on <a href="http://www.linkedin.com/in/kunjmehta">Linkedin</a> or <a href="https://www.twitter.com/@kunjmehta10">Twitter</a>! For codes pertaining to my previous article visit my <a href="https://github.com/kunjmehta/Medium-Article-Codes">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9276b61873c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/5-minute-paper-explanations-food-ai-part-i-9276b61873c1">5 Minute Paper Explanations: Food AI Part I</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Gradient Descent Works?]]></title>
            <link>https://medium.com/data-science/why-gradient-descent-works-4e487d3c84c1?source=rss-ab5f9f992f70------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e487d3c84c1</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Kunj Mehta]]></dc:creator>
            <pubDate>Wed, 20 Oct 2021 22:17:14 GMT</pubDate>
            <atom:updated>2021-10-20T22:17:14.985Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everybody knows what Gradient Descent is and how it works. Ever wondered why it works? Here’s a mathematical explanation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UuWQSZLhG7BvlXjq" /><figcaption>Photo by <a href="https://unsplash.com/@ychemerys?utm_source=medium&amp;utm_medium=referral">Yuriy Chemerys</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Gradient Descent?</h3><p>Gradient descent is an iterative optimization algorithm that is used to optimize the weights of a machine learning model (linear regression, neural networks, etc.) by minimizing the cost function of that model.</p><p>The intuition behind gradient descent is this: Picture the cost function (denoted by <strong><em>f(</em>Θ̅ <em>) </em></strong>where <strong>Θ̅</strong> =[Θ₁, … Θₙ<strong><em>]</em></strong>)<strong><em> </em></strong>plotted in <strong><em>n</em></strong><em> </em>dimensions as a bowl. Imagine a randomly placed point on that bowl represented by <strong><em>n</em></strong><em> </em>coordinates (this is the initial value of your cost function). The minimum of this “function” then will be the bottom of the bowl.</p><p>The goal is then to reach to the bottom of the bowl (or minimize the cost) by progressively moving downwards on the bowl. For this to happen, we should know the slope of the bowl in different directions from where the point currently is, so that we can decide which direction to move in for fastest convergence. To determine this, we calculate the gradient of the function at that point. On iteratively doing this, we will eventually reach some minimum-valued point and the coordinates of that point will be the optimal weights of the model.</p><h3>How Gradient Descent Works</h3><p>Here is a more formal definition of Gradient Descent:</p><p>Starting with the input matrix <strong><em>X</em></strong> which represents the list of <strong><em>n</em></strong>-dimensional input vectors and an initial value to the weights <strong>Θ̅, </strong>we know that in the linear regression equation is given by: <strong><em>y̅ =</em> Θ̅ᵗ<em>X</em>.</strong> Now, if the cost function is given by <strong><em>f(</em>Θ̅ <em>), </em></strong>this is how we formulate Gradient Descent:</p><figure><img alt="Gradient Descent Algorithm Formulation" src="https://cdn-images-1.medium.com/max/392/1*kL62kPkeS9aOCti5GfJG7Q.png" /><figcaption>Gradient Descent Algorithm Formulation (Image by Author)</figcaption></figure><p>Here, <strong><em>t</em></strong><em> </em>is the iteration counter and <strong><em>tₘₐₓ </em></strong>is the maximum number of iterations we run the loop for.</p><h3>Why it Works</h3><p>The first question here should be: The second derivative test and hence the second derivative of any function <strong><em>f(</em>Θ̅<em>)</em></strong><em> </em>when equated to zero tells you whether <strong>Θ̅ </strong>is a local maximum or a local minimum of that function. Now, since we are interested in minimizing, we can reverse engineer this concept and solve for <strong>Θ̅ </strong>given the second derivative of <strong><em>f(</em>Θ̅<em>)</em></strong><em> </em>is negative.</p><p>So, why do we not do that and instead solve the minimization problem iteratively (as in gradient descent)? Well, the answer lies in the fact that first and foremost, the second derivative is not guaranteed to always exist. Second, the computational complexity of solving the second derivative equation for <strong>Θ̅ₘᵢₙ</strong> is very high. In fact, sometimes it is not possible to solve using calculus, and has to be solved numerically.</p><h4>The Minimization Problem</h4><p>So, specifying the general minimization problem numerically (and hence iteratively), we say that <strong>Θ̅ₜ₊₁ = Θ̅ₜ + <em>dₜ</em></strong> where <strong><em>dₜ </em></strong>is some general direction of minimization (look back at the bowl example) at time <strong><em>t</em></strong></p><figure><img alt="Specification of the General Format of a Minimization Algorithm" src="https://cdn-images-1.medium.com/max/637/1*FSjUaTITXUZoxIOV_lOc5w.png" /><figcaption>Specification of the General Format of a Minimization Algorithm (Image by Author)</figcaption></figure><p>Now, to choose the appropriate <strong><em>dₜ </em></strong>so that <strong>Θ̅ₜ₊₁ &lt; Θ̅ₜ </strong>— and we move towards minimization.</p><h4>Taylor Series</h4><p>To solve the above minimization problem, we make use of the Taylor series for <strong><em>n </em></strong>dimensions. We calculate the <strong><em>f</em></strong>(<strong>Θ̅ₜ₊₁</strong>) using the Taylor series centered at <strong><em>f(</em>Θ̅ₜ<em>). </em></strong>This is what it looks like:</p><figure><img alt="n-dimensional Taylor Series and its Corresponding terms in 1-dimensional Taylor Series" src="https://cdn-images-1.medium.com/max/656/1*9Un57Vw4qnMGyk826_aIJA.png" /><figcaption>n-dimensional Taylor Series and its Corresponding terms in 1-dimensional Taylor Series (Image by Author)</figcaption></figure><figure><img alt="Hessian Matrix" src="https://cdn-images-1.medium.com/max/478/1*Kb9yjPogecUbByC2RmCOFg.png" /><figcaption>Hessian Matrix (Image by Author)</figcaption></figure><p>Here the matrix <strong><em>H </em></strong>is the Hessian matrix, representing the second-order partial derivative of the function <strong><em>f(</em>Θ̅ₜ<em>)</em></strong></p><p>Next, we substitute the equation from the definition of minimization: <strong>Θ̅ₜ₊₁ = Θ̅ₜ + <em>dₜ</em></strong></p><figure><img alt="Solving the Taylor Series" src="https://cdn-images-1.medium.com/max/606/1*mnTU8VW9S4nP_oPx5-RDYA.png" /><figcaption>Solving the Taylor Series (Image by Author)</figcaption></figure><p>In the above image, we incorporate the cubic terms in the asymptotic term itself since we only want to work with the first two terms and we get <strong><em>O(||dₜ||</em></strong>²<strong><em>). </em></strong>Next, as mentioned before we try to choose the direction of minimization <strong><em>dₜ </em></strong>that will give us <strong><em>f</em></strong>(<strong>Θ̅ₜ₊₁) &lt; <em>f</em></strong><em>(</em><strong>Θ̅ₜ) </strong>and hence lead us towards minimization over <strong><em>t </em></strong>time steps.</p><p>We select <strong><em>dₜ </em></strong>to be the negative of the gradient of the cost function at time <strong><em>t — </em></strong>and the similarity to gradient descent starts to appear, and we obtain the last line. Now, notice that in the equation on the last line above, the first and the second term are similar to each other and the end result of that can either be positive or negative. This actually depends on the higher order terms encapsulated within the asymptotic bound. To make sure that we end up with a negative value on the right and a decreasing value over time, we introduce a new term <strong><em>α</em></strong>.</p><h4>…and Viola!</h4><figure><img alt="Introducing the Learning Rate in Minimization (Image by Author)" src="https://cdn-images-1.medium.com/max/638/1*i5Wzn0zZjbzZ7XRKgM-j4w.png" /><figcaption>Introducing the Learning Rate in Minimization (Image by Author)</figcaption></figure><p>You guessed it right! <strong><em>α </em></strong>is the learning rate that we normally see in Gradient Descent. Introducing <strong><em>α </em></strong>and making sure that it is very less guarantees that the second term in the final equation above is always less than the first term and hence, we get a negative result on the right hand side. This, in turn ensures that we minimize the function <strong><em>f(</em>Θ̅<em>) </em></strong>over time <strong><em>t</em></strong></p><p>This article is inspired by the lecture series of Dr. Cowan at Rutgers University.</p><p>You can find the Latex file for the equations <a href="https://github.com/kunjmehta/Medium-Article-Codes/blob/master/why_gradient_descent_works.pdf">here</a>. I’d love to connect on <a href="http://www.linkedin.com/in/kunjmehta">Linkedin</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e487d3c84c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/why-gradient-descent-works-4e487d3c84c1">Why Gradient Descent Works?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Philosophical Look at Climate Change]]></title>
            <link>https://medium.com/the-environmental-reporter/a-philosophical-look-at-climate-change-5f5a2922f761?source=rss-ab5f9f992f70------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f5a2922f761</guid>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[climate-change]]></category>
            <category><![CDATA[climate]]></category>
            <dc:creator><![CDATA[Kunj Mehta]]></dc:creator>
            <pubDate>Sat, 31 Jul 2021 21:36:27 GMT</pubDate>
            <atom:updated>2021-10-25T18:54:46.247Z</atom:updated>
            <content:encoded><![CDATA[<h4>… And why its here to stay</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DUYBJzNGQ1tscm3z" /><figcaption>Photo by <a href="https://unsplash.com/@redcharlie?utm_source=medium&amp;utm_medium=referral">redcharlie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Disclaimer</strong>: This article is about 2 years old and written for the university magazine.</p><p>In 2019, Greta Thunberg said “how dare you” and she was right, how dare we! But now we have to dare to reverse this climate change and it may still be an improbable task. Because for all the protests and the media attention that ‘Fridays for Future’ has been getting, there is not much action on the ground where it matters. There are many reasons for this, most of which can be traced back to the opportunism that has been hardwired into our brains.</p><p>Humans try to accrue the most beneficial of opportunities, and if none are forthcoming, they will take the easiest way out. The Amazon fires started because of people burning their farms and dashing. They did not have an economic opportunity (read, incentive) or knowledge to try other methods and ‘burn and dash’ was the easiest one available. Urbanization happens because the rural people think that there are a plethora of opportunities in the cities while they cannot find one in their villages. In the past, low opportunity for infants to live beyond infancy resulted in a higher birth rate. The earliest humans lived alongside rivers because opportunities for obtaining food and water were the highest there. If the world provided opportunities to girls as they do to boys, boys would not be pined for and female infanticide would end.</p><p>Human beings as a species are intelligent but not responsible. Instead of using our intelligence to exist blissfully with Nature and all its life forms, we use it to keep generating new opportunities for ourselves. What’s more is a human tends to see opportunities as being present only for himself and has to make a conscious effort to realize how that same opportunity can benefit someone else. This is how narrow-minded and opportunistic we are. There was a time when humans used to coexist with Nature (when human survival depended on it), but once they could generate opportunities on their own, they left caring for it. This effectively happened after the Industrial Revolution.</p><p>Post-Industrial Revolution, we have only increased the intensity with which we harm Nature. This makes the challenge of reversing the climate crisis very severe. <a href="https://www.gatesnotes.com/energy/my-plan-for-fighting-climate-change">Research</a> by the Intergovernmental Panel on Climate Change shows that the greenhouse gas emissions that have long been held (and proven) as the major cause for warming our planet and accelerating climate change will need to be cut to net zero in every sector within 50 years, the efforts for which need to be started within 10 years. The research also gives a breakup of the major sources of these emissions: electricity generation is 25%, manufacturing is 21% and transportation is 14%. This means that within 10 years, we need to be on the way to using only solar and wind power for generating electricity and even this will only account for a quarter of the emissions; we need to more or less start manufacturing products like plastic, cement and steel by pre-Industrial Revolution methods (if that is even possible) and the hype around electric vehicles is not going to amount to much. Add to this that the climate cycle is always late to react so we do not know when the climate had latently reached the bad stage that has now manifested, and how much worse is yet to come.</p><p>Extrapolating the human opportunism to climate, the biggest hurdle apart from convincing 7.8 billion people that climate change is real will be to achieve international cooperation in living a life of net zero greenhouse emissions. This will be especially tough because at present, there are no fathomable opportunities to be accrued by living at net zero emissions, and without opportunities the status quo cannot be changed. Because technological circumstances to support net zero emissions have not yet arisen, the governments of the world cannot just enact laws to enforce it and in the process shut down existing industries wholly. People have a tendency to continue living life in the way they have been cultured and habituated to. That is why old people are resistant to change. Generations of humans have been cultured to the Modern Age, and a return to an era preceding it would prove an uphill task. Ask the people supporting Greta how many of them would be willing to abandon their modern lives!</p><p>Time does not move backwards, always forwards. What has been done, has been done; there is no going back to what it was. What we can hope for is that the worse that is yet to come from Nature is not much worse than the present and that the late reaction of climate has reached its end. What we can do is try our best to return to pre-Industrial Revolution conditions while also preserving our modern cultural, social and technological ethos in an attempt to realize climate restoration in the long term. It is a long road downhill but we have finally started noticing the steepness of it, and taken steps in the right direction. Let&#39;s all work to reach the bottom safely, together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f5a2922f761" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-environmental-reporter/a-philosophical-look-at-climate-change-5f5a2922f761">A Philosophical Look at Climate Change</a> was originally published in <a href="https://medium.com/the-environmental-reporter">The Environmental Reporter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Points to Make it Big in the  Data Industry]]></title>
            <link>https://medium.com/data-science/10-points-to-make-it-big-in-the-data-industry-db62dfdcd9f2?source=rss-ab5f9f992f70------2</link>
            <guid isPermaLink="false">https://medium.com/p/db62dfdcd9f2</guid>
            <category><![CDATA[advice-and-opinion]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[industry-insights]]></category>
            <dc:creator><![CDATA[Kunj Mehta]]></dc:creator>
            <pubDate>Sat, 24 Jul 2021 17:44:03 GMT</pubDate>
            <atom:updated>2021-07-24T17:44:03.652Z</atom:updated>
            <content:encoded><![CDATA[<h3>10 Points to Make it Big in the Data Industry</h3><h4>People want to make careers here. But they are often deafened by the noise that surrounds them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W-tYoxX1k6QpZCO7" /><figcaption>Photo by <a href="https://unsplash.com/@sortino?utm_source=medium&amp;utm_medium=referral">Joshua Sortino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Suppose you are someone who just got awed by the flashy terms of artificial intelligence, machine learning and data science and have decided to either get a degree in one of these fields or pivot your career and enter into the data industry. You get in on the hype, jump on the bandwagon, enroll in Andrew Ng’s courses on Coursera, some more courses on Udacity, buy some detailed books and scour through them, start Kaggling, implement some projects and publish research papers. You start feeling good for what you have accomplished. But when you go and apply for a job or an internship, you don’t get it and you wonder why.</p><p>Well, the thing is all of what you did above is good for getting to know the basics and being exposed to what the industry has to offer. However, the data industry is inherently interdisciplinary, broad and constantly evolving, and the ecosystem around it very noisy. I mean, just search any of the buzz words and you will get thousands of articles — all of them claiming to be different from the rest; this one does not — blasting opinions, advice, tutorials and what not. I recently read an article where the author was bemoaning the lack of helpful online resources for experts in the field. Almost everything is targeted towards newcomers. Imagine that!</p><p>What newcomers actually need is to develop the ability to navigate around this huge industry, decide for themselves what they want within it and how to get it.</p><blockquote>In the data industry, be an expert vertically, not an ‘expert’ horizontally</blockquote><h3>Honing the Thought Process</h3><p>To make it big in data and to filter the noise, it is necessary for every individual to know at every stage of their never-ending learning process:</p><ol><li>How the data industry works</li><li>What technology it uses</li><li>How it&#39;s moving forward</li></ol><p>and align that with what the individual:</p><ol><li>Imagines their role within the industry to be</li><li>Has planned to get to their desired position</li><li>Knows are the resources available at their disposal to get there — all of which is a cyclical process.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBTNvLBq4dXjUWlnunjWGA.png" /><figcaption>Thought Process of a Data Industry Veteran (Image by Author)</figcaption></figure><p>That being said, here is a deep dive into the available types of interconnected knowledge resources.</p><h3>The 10 Resources</h3><ol><li><strong>MOOCs / Certifications: </strong>Online courses and certifications are a great way to get started — much like a crash course. One advantage of the noise here is the immense amount of options available. Given that one starts with a highly recommended course, MOOCs get one familiarized with the concepts, terminologies, differences and layout of the data industry and its various sub-industries. To top it off, there is a certificate — many universities have started recognizing these for credits — to show for it!</li><li><strong>Reference Books: </strong>Reference books on AI, deep learning and machine learning can be good for a deep dive into any selected topic. This type of resource will cover in-depth theory and give a solid understanding of the underlying concepts. Plus, an introduction to the underlying math as well!</li><li><strong>Mathematics: </strong>Maths, in itself is not necessary. However, to have a full rounded understanding of any concept, algorithm or technique in the data industry, it is a must that one know the underlying mathematics. This will allow them to understand the concept at a grassroots level as well as understand and tweak the workings of the concept at the programmatic level (think: implementation libraries)</li><li><strong>Technology: </strong>Every day, better and more optimized libraries and frameworks in many different languages are built on top of the concepts in the data industry, for developers. For someone looking to a career developing ML models or data pipelines, it is imperative they keep up-to-date with the newest offerings while also understanding the underlying concepts and mathematics so that they can use them to the fullest extent.</li><li><strong>Research Papers: </strong>On the contrary, for someone looking forward to a career as a researcher in the industry, keeping up with the newest offerings from the <em>theoretical </em>perspective is imperative. Which is why reading research papers and publishing their own work goes a long way. Here too, the mathematical understanding helps.</li><li><strong>Kaggle: </strong>After getting into the theory and the concepts, the next thing is leveraging the theory and the libraries learnt to work on some actual data. Kaggle is the best platform to work on real world data from real world use cases — from data analysis to hyperparameter tuning. The only disadvantage — also its biggest downside — is that model deployment and building an application around the model is not possible on the platform. Kaggle can prove best for future data analysts and machine learning engineers.</li><li><strong>Projects: </strong>To get over Kaggle’s disadvantage, stand-alone projects need to be built. For the same, data from Kaggle can be leveraged, but in any project not being done on Kaggle, make it a point to wrap an application around the model and deploy it. This way one can get some experience in end-to-end development of applications in the data industry.</li><li><strong>Cloud: </strong>Speaking of end-to-end development, much of the development that happens and the services that are offered now leverage the cloud. Hence, it is imperative that someone who wants to make a career in deploying data applications (think MLOps) is familiar with the various cloud technologies in the space.</li><li><strong>Internships: </strong>Lastly, all of the implementation and theoretical knowledge can be leveraged in internships or on jobs to ideate, plan, architect and build something from scratch as per client requirements. The difference between this and projects is that in projects, the problem definition is already given and there is no need to think from the business perspective. In essence, internships and jobs provide an opportunity to expand the brainstorming capacity of a person as the requirements are seldom straight-fit and straightforward. This can be an ideal experience for future data scientists</li><li><strong>Domain Knowledge: </strong>Remember, the data industry is like running a marathon. Marrying any type of business requirement to data is tough and gaining enough knowledge to always do that for a business domain requires time and association with the business domain for a number of years. Once achieved, one will be on top of the data pyramid for that domain!</li></ol><p>This article is based on my journey and experience in the industry so far. I would consider it humbling if someone improves upon the post or points out anything I have missed out or have got wrong.</p><p>Lastly, I would love to connect on <a href="https://www.linkedin.com/in/kunjmehta">Linkedin</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db62dfdcd9f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/10-points-to-make-it-big-in-the-data-industry-db62dfdcd9f2">10 Points to Make it Big in the  Data Industry</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Mainstream AI is (Not) Doing]]></title>
            <link>https://medium.com/data-science/what-mainstream-ai-is-not-doing-9a2f7236a4f7?source=rss-ab5f9f992f70------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a2f7236a4f7</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[opinion]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[data-for-change]]></category>
            <dc:creator><![CDATA[Kunj Mehta]]></dc:creator>
            <pubDate>Tue, 06 Jul 2021 03:49:00 GMT</pubDate>
            <atom:updated>2021-07-09T01:10:51.058Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/data-for-change">Data for Change</a></h4><h4>The pandemic accelerated AI adoption — and made Big Tech richer — but did AI adoption happen in the places where it was needed?</h4><p>After dabbling in machine learning during my undergrad, I scored a job as a Business Analyst catering to the Public Sector and Education business of one of the leading AI service providers in India. Having landed the job in the pandemic — which I must say, I consider myself fortunate to — and onboarded onto the role fully online, I have been at the forefront of the transition of organizations from real-world to digital world. And I say this not only for the company I work for, but for the numerous governmental agencies and educational institutions that have approached us seeking to undergo a digital transformation in order to enhance their processes in the current situation as well as for the future.</p><p>I genuinely believe that these past one-and-a-half years have been a blessing for the entire IT industry and in association to the AI industry — since AI is now nearly ubiquitous when it comes to IT — as evidenced by the <a href="https://www.nytimes.com/2021/04/29/technology/big-tech-pandemic-economy.html">incredulous growth the Big Tech has achieved</a> by a two-prong strategy of undergoing digital transformation themselves (thereby cutting expenditures) and providing the same services to other industries (and generating immense revenue).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jv8pxjzDELpLNHdw" /><figcaption>Mainstream AI needs to bridge the gap between commercial and social applications. (Photo by <a href="https://unsplash.com/@indiratjokorda?utm_source=medium&amp;utm_medium=referral">Indira Tjokorda</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>)</figcaption></figure><h3>Increasing AI Adoption</h3><p>As previously mentioned, Big Tech companies, while initially apprehensive of the impact of the ‘new normal’, soon realized its potential and took full advantage of it. Everything increased — from ad revenues due to digital ads becoming the major avenue to reach consumers, online shopping, sales of laptops and mobiles as everything went online, social media engagement to <a href="https://www.forbes.com/sites/forbestechcouncil/2021/01/15/how-the-pandemic-has-accelerated-cloud-adoption/?sh=951186e66214">increased cloud consumption</a> as businesses went digital. Inadvertently, this forced shift to online along with the fear of missing out acted as a catalyst for stakeholders to adopt not only traditional digital transformation but also to jump onto the bandwagon of newer technologies like cloud, artificial intelligence and blockchain.</p><p>As per a <a href="https://info.kpmg.us/news-perspectives/technology-innovation/thriving-in-an-ai-world/ai-adoption-accelerated-during-pandemic.html">KPMG survey</a>, there has been a 37% increase in AI adoption in at least one function in FinTech, 20% increase in Tech and 29% increase in Retail compared to last year. Couple this with the <a href="https://aiindex.stanford.edu/wp-content/uploads/2021/03/2021-AI-Index-Report_Master.pdf">$67.9 billion</a> in investment AI saw in 2020 — including Microsoft’s <a href="https://www.theverge.com/2019/7/22/20703578/microsoft-openai-investment-partnership-1-billion-azure-artificial-general-intelligence-agi">$1 billion investment</a> in Open AI, previously a <a href="https://techcrunch.com/2019/03/11/openai-shifts-from-nonprofit-to-capped-profit-to-attract-capital/">not-for-profit organization</a> — and the representative mapping of use cases this money was spent on based on a <a href="https://www.mckinsey.com/Business-Functions/McKinsey-Analytics/Our-Insights/Global-survey-The-state-of-AI-in-2020">report by McKinsey</a>. About 50% of use cases in AI in 2020 were related to Natural Language Processing and 20% to Computer Vision across industries like IT, FMCG, Healthcare, FinTech, Legal and Automotive. In comparison to this mainstream, Google via their <a href="https://ai.google/social-good/impact-challenge/">AI for Social Good</a> initiative offered just $25 million for research of AI applications that improve society.</p><p>This renewed push for digital transformation, the change in the adoption mindset and the amount of money being poured into the space (this time even from the public sector) was the perfect opportunity for the AI community to capitalize and enhance their efforts to tackle the problems facing AI and to build applications for the social good, <em>especially </em>in these times. Unfortunately, examples of that happening are few and far between.</p><h3>Use Cases that need AI (based on UN SDGs)</h3><p>International organizations like <a href="https://www.itu.int/en/mediacentre/backgrounders/Pages/artificial-intelligence-for-good.aspx">International Telecommunication Unit </a>(ITU) and <a href="https://www.mckinsey.com/featured-insights/artificial-intelligence/applying-artificial-intelligence-for-social-good#">McKinsey</a> use the <a href="https://www.undp.org/sustainable-development-goals">United Nation’s Sustainable Development Goals</a> (UN SDG) adopted in 2015 as a guideline for the world’s major problems today and try to map how AI can be used to these problems. Serendipitously, a <a href="https://www.nature.com/articles/s41467-019-14108-y">research paper published in Nature</a> estimates that 79% of the targets within the 17 SDGs can be reached using AI in some manner. Let’s look at the 17 SDGs and how AI can achieve these targets as set forth by the UN:</p><ul><li><strong>No Poverty: </strong>To achieve UN’s goal to eradicate extreme poverty by 2030, AI can be used to analyze satellite data or mobile usage data and detect areas of poverty followed by complementing policies to aid the residents in these areas. Better weather prediction leveraging AI can help in evacuating these people to safety. Economically, in a bid to bridge the gap between the rich and poor, AI can be give credit ratings for loans to those below the poverty line (assuming the underlying data is not biased)</li><li><strong>Zero Hunger: </strong>Ancillary AI applications that indirectly contribute to this goal have already been gaining traction in the agriculture sector, while l<a href="https://healthitanalytics.com/news/machine-learning-helps-reduce-food-insecurity-during-covid-19">ast mile routing solutions</a> were developed to provide for food during the pandemic. Examples in agriculture include using Computer Vision to detect crop diseases, analyzing and modeling historical data to support farmer decisions, harvest forecasting, weather forecasting and IoT-enabled, AI-powered farm equipment. However, agricultural AI research will count for nothing if the end-product cannot be put into the hands of the poor farmers of third-world countries.</li><li><strong>Good Health and Well Being: </strong>This goal falls squarely into the healthcare sector which has received focus and funds to battle the pandemic. <a href="https://newsroom.intel.com/wp-content/uploads/sites/11/2020/11/AdvancingAI-Infographic.pdf">Intel research</a> shows that there has been a 39 percentage point increase in healthcare leaders adopting or wanting to adopt AI, post the pandemic. Examples of AI use cases in the healthcare sector include AI and data powered support systems in hospitals, automation of drug discovery, tuberculosis and cancer detection, increasing AIDS awareness, solutions to reduce traffic accidents (cue autonomous vehicles), suicide prevention and reduction of distressing posts on social media (credit where its due: this last one is Facebook). However, many of these solutions are borderline ethical and with the dangers of <a href="https://www.technologyreview.com/2020/04/27/1000658/google-medical-ai-accurate-lab-real-life-clinic-covid-diabetes-retina-disease/">datasets not representing the real world</a> and lives being at stake, it is a big gamble for now.</li><li><strong>Quality Education: </strong>Another sector that has seen tremendous increase in AI adoption due to the pandemic. I can say from personal experience that AI is increasingly being used to monitor students’ attention or to carry out emotional surveillance to determine how comfortable children are learning certain subjects, identifying students who are struggling before their test results become available. Attempts at using AI to deliver personalized and adaptive teaching are being made, especially on online learning platforms. However, AI in education has a long way to go to provide truly personalized education.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22D4xmj_28Rm9mGWVECRAQ.png" /><figcaption>AI Investment Increased in Education and Healthcare Roughly During the Pandemic (Image via <a href="https://aiindex.stanford.edu/wp-content/uploads/2021/03/2021-AI-Index-Report_Master.pdf">Stanford AI Index, 2021</a> under the Attribution-NoDerivatives 4.0 International license)</figcaption></figure><ul><li><strong>Gender Equality: </strong>There has been very little direct involvement of AI in achieving gender equality, mainly because it is a socio-cultural problem. That being said, the AI community needs to make sure that it does not promote gender bias by ensuring the underlying datasets and deployed systems do not have bias inherent in them.</li><li><strong>Clean Water and Sanitation: </strong>The only properly researched use case pertaining to this goal is using AI to predict and suggest steps to improve the quality of water in a water treatment plant. Potential use cases include catchment area management and water pipeline / flow management</li><li><strong>Affordable and Clean Energy: </strong>Again, a not frequently researched field, most of the efforts have been towards how AI can optimize energy production and consumption and better predict demand. More research is needed into how AI can help setup Smart Grids.</li><li><strong>Decent Work and Economic Growth: </strong>This is again a more socio-cultural problem then a technological problem. However, generally speaking the rise of the AI industry and its share in the global economy can spur economic growth but at the risk of replacing low-skilled workers, which is why the AI industry needs to be self-aware and balance the advantages and disadvantages it brings to society as well as to the environment. In addition, with the automation that AI provides, productivity will also increase.</li><li><strong>Industry, Innovation and Infrastructure: </strong>Though research into many applications of AI in infrastructure is ongoing and the underlying concepts are sound, there is not much adoption in this area. There is a need for an adoption push in use cases such as air and water quality management, energy management, asset and construction management, predictive maintenance, enhancing productivity, automation and smart cities and grids.</li><li><strong>Reduced Inequalities: </strong>This social problem can be indirectly solved in part by using AI. For financial equality, applications can be developed that predict credit ratings and provide loans for the low-income group as well as help them understand the personal investment world through data. For cultural, racial and caste equality, I believe it would be more beneficial if all AI applications managed to eradicate the underlying bias in data itself rather than coming up with specific applications targeted to promoting equality. A representative example here would be tweaking recommendation engines to not promote hate speech. On a larger scale, data related to demographics and social patterns in a particular community can be analyzed to conclude how inclusive the community is.</li><li><strong>Sustainable Cities and Communities: </strong>Many points pertaining to this goal have been covered above. Large-scale AI can help achieve sustainable and smart cities through solutions geared towards better transportation infrastructure and reduced accidents, water and energy management, predicting earthquakes, spread of wildfires and oil spills, ecology analysis, air quality analysis, etc. Again, the challenge here is large-scale adoption and policy support.</li><li><strong>Responsible Consumption and Production: </strong>AI-enabled systems can leverage historical data and patterns to optimize production and consumption schedules in various sectors like manufacturing, energy, etc. while the automation that AI brings will improve productivity. From a policy standpoint, the process of government procurement of services and goods which is very slow and corrupt in many places can thank AI for systems that automate the filtering out of unqualified vendors.</li><li><strong>Climate Action: </strong>AI cuts both ways when it comes to climate action with the humongous energy requirements for developing and running AI models indirectly adding to the CO2 in the air, while the possibility of automating energy management, climate modeling and predicting natural disasters being its positive side.</li><li><strong>Life Below Water: </strong>Research has shown oceans and sea-life can be conserved by leveraging AI in the detection and mitigation planning automation of oil spills and catchment area management. Satellite data analysis can be useful in ecological forecasting (which includes coral bleaching and algal blooms among other events), tracking and regulating trawler activities.</li><li><strong>Life on Land: </strong>Research shows AI can be used to identify forest animals through their footprints which can play a non-invasive part in wildlife conservation efforts. Remote sensing leveraging AI can be used for assessing, predicting, and mapping forest structural features which serve as indicators of forest condition and help in conserving forests. Neural networks and objective-oriented techniques can be used to better classify vegetation cover types and hence detect desertification and droughts.</li><li><strong>Peace, Justice and Strong Institutions: </strong>AI can be leveraged in surveillance systems and social media to detect, notify and filter violent people and/or content, bullying and child pornography. Facial recognition software can also be used in predictive policing. However, this is one section for which the required technology is ready but its adoption is controversial due to <a href="https://www.technologyreview.com/2020/06/12/1003482/amazon-stopped-selling-police-face-recognition-fight/">ethical, privacy and discrimination concerns.</a></li><li><strong>Partnerships for the Goals: </strong>This particular section in the UN’s SDG list lists down targets towards collaboration for achieving the other 16 goals and as such is not related to technology. So, we will skip this.</li></ul><h3>How Big Tech and Government can Control AI</h3><p>To pursue research of any kind in any sector or industry requires funding. Research will be focused where the funds are. Keeping this in mind, let’s take a look at how Big Tech and international governments have the potential to centralize AI research and determine how the industry moves forward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*FKs0jOxa6yca2GOkKrO3_Q.png" /><figcaption>Corporate Participation in Academic Research Across Conferences (Image via <a href="https://aiindex.stanford.edu/wp-content/uploads/2021/03/2021-AI-Index-Report_Master.pdf">Stanford AI Index, 2021</a> under the Attribution-NoDerivatives 4.0 International license)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B3ySZ8TQk5XUlkQ3.png" /><figcaption>Big Tech’s Acquisition of AI Startups (Image via <a href="https://aiindex.stanford.edu/wp-content/uploads/2021/03/2021-AI-Index-Report_Master.pdf">Stanford AI Index, 2021</a> under the Attribution-NoDerivatives 4.0 International license)</figcaption></figure><p>From 2012, when Big Tech started entering the AI field after a breakthrough in machine learning techniques to 2019, there has been a <a href="https://www.wired.com/story/dark-side-big-tech-funding-ai-research/">550% increase in footfall</a> at NeurIPS, the largest machine learning conference that is held. And Big Tech reps attend it with the aim of luring PhDs into their companies. These companies also hire tenure-track professors to help them in their research. Big Tech’s talent grab is not only limited to academia but has even expanded to startups in recent years, as <a href="https://www.washingtonpost.com/technology/interactive/2021/amazon-apple-facebook-google-acquisitions/">this</a> article diagrammatically presents.</p><p>The two graphs below reinforce the belief that corporate has a strong interest in academic AI research, especially in America. The position of corporates in peer-reviewed research is replicated in research papers published in journals or showcased in conferences as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C91_kiqR2mhGv70rrnWIfA.png" /><figcaption>Private Investment in AI Across Countries. USA has the highest (Image via <a href="https://aiindex.stanford.edu/wp-content/uploads/2021/03/2021-AI-Index-Report_Master.pdf">Stanford AI Index, 2021</a> under the Attribution-NoDerivatives 4.0 International license)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBnnZ2Oq9Ir_vsQjKl-3Sw.png" /><figcaption>Peer-Reviewed AI Publications in the USA. Corporate has the highest involvement(Image via <a href="https://aiindex.stanford.edu/wp-content/uploads/2021/03/2021-AI-Index-Report_Master.pdf">Stanford AI Index, 2021</a> under the Attribution-NoDerivatives 4.0 International license)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arYk-nZ0fXlQwlMlZE0Dhw.png" /><figcaption>Peer-Reviewed AI Publications in China. Government has the highest involvement(Image via <a href="https://aiindex.stanford.edu/wp-content/uploads/2021/03/2021-AI-Index-Report_Master.pdf">Stanford AI Index, 2021</a> under the Attribution-NoDerivatives 4.0 International license)</figcaption></figure><p>It is instantly noticeable from the graphs above: USA, China, and the European Union are the leaders in AI research. In America, corporate has a much larger interest than the government or academia. However, in China, the government — and not the corporates — is the one that centralizes AI, which is obvious if we come to think of China’s political structure. The image below reinforces this as we can see that the corporate-academic partnership for publishing papers is much less in China (in spite of the large number of papers that China publishes) than in the USA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUBlPBKPC3m8hZQ6yV4yxw.png" /><figcaption>Academic-Corporate Partnership in AI Publications. USA leads the others by a large margin (Image via <a href="https://aiindex.stanford.edu/wp-content/uploads/2021/03/2021-AI-Index-Report_Master.pdf">Stanford AI Index, 2021</a> under the Attribution-NoDerivatives 4.0 International license)</figcaption></figure><p>China is a case of more than average AI centralization by the government. Nonetheless, the reason that governments have a stake in AI is that they have the power to roll out legislation concerning the proper use of publicly and privately available data for AI applications (case in point: EU’s GDPR). And specifically for projects in the social realm—and not to mention the large scale sectors of infra, smart cities, water management, etc over which the government has a larger control — the government is the one that can announce policies, development schemes, and scope out and fund large-scale projects which leverage AI to achieve the project objective. To that extent, <a href="https://www.itu.int/en/mediacentre/backgrounders/Pages/artificial-intelligence-for-good.aspx">ITU’s research</a> shows that 131 countries have already passed or are in the process of passing a data policy with 18 countries having a specific AI policy in place, as of 2020.</p><h3>Challenges in the Industry</h3><p>However the AI industry moves forward as a result of corporate and/or government support, the things that need to be addressed foremost to ensure that it isn’t ‘two steps forward, one step back’ are the problems facing the industry and community right now.</p><ul><li><strong>Explainability of AI: </strong>Machine learning models — neural networks especially — frequently behave as a black box and it is often unclear how they arrive at their conclusion. Sometimes it is preferable to have a model that provides a result that can be backtracked so as to be able to modify the proper parameters in the model whenever required. This aspect gains increased focus in the healthcare industry because of the stakes involved and also, recently in facial recognition systems because of <a href="https://www.technologyreview.com/2021/06/14/1026148/ai-big-tech-timnit-gebru-paper-ethics/">erroneous outputs leading to disastrous results</a>.</li><li><strong>Unavailability of Data: </strong>In many use cases, collecting the right data and creating an actionable dataset is a time-consuming task. This because firstly, what are the avenues from where data can be collected has to be figured out; secondly, gathering this data from disparate sources takes time; thirdly, organizations have to modify the collected data to comply with data and privacy regulations, while still keeping the data actionable. For academia though, getting past the first stage itself is tough because Big Tech and government has much of the data (collected from their various services) which it keeps private or classified, as the case may be.</li><li><strong>Bias and Misrepresented Datasets: </strong>The data that organizations collect and the method with which they do so represent the reality of the place from where the data has been collected. This results in cultural or social prejudices making its way into the datasets and it becomes the organization’s responsibility to weed the bias out. Taking it a step further, it is also the organization’s responsibility to make sure that the application is deployed in a place that has an identical representative population to the one from which the dataset was prepared to ensure that <a href="https://www.technologyreview.com/2020/06/12/1003482/amazon-stopped-selling-police-face-recognition-fight/">controversies </a>and <a href="https://www.technologyreview.com/2020/04/27/1000658/google-medical-ai-accurate-lab-real-life-clinic-covid-diabetes-retina-disease/">failed deployments</a> do not occur. Bias creeping into the models is a real threat for facial recognition systems and large language models.</li><li><strong>Generalizability: </strong>OpenAI is the torchbearer for the AI industry’s quest towards a Artificial General Intelligence — a single AI that can do everything a human can do. At present, this is a distant possibility and so for <em>every </em>use case discussed above, chances are the whole process from data collection to model deployment will be redone specifically for that use case. This seems like a waste of time and effort, which it is. However, generalizability in itself isn’t as bad as the next point that it brings us to.</li><li><strong>Energy Consumption: </strong>OpenAI itself, chasing generalizability in natural language processing has kept outdoing itself and building bigger neural language models (cue GPT-3). The energy that is required to train (even once) and deploy these models is<a href="https://www.technologyreview.com/2020/12/04/1013294/google-ai-ethics-research-paper-forced-out-timnit-gebru/"> really, really huge </a>— so much so that it gets you thinking that if the current trend of building ever-bigger models continues then whatever advantages AI brings for the environment won’t actually matter. Add to this the fact that GPT-3 doesn’t even understand human language; it is just a master in manipulating it.</li><li><strong>Corporate-Academia Gap: </strong>The gap between corporate and academic resources and research is there for all to see. Which is why the AI community needs to refocus itself and build <em>more </em>applications that do actual good, irrespective of corporate or government interests.</li></ul><h3>Conclusion</h3><p>We can clearly see that sectors such as healthcare and education that had some presence of AI saw a wild rise in AI adoption during the pandemic. Other sectors have had research being conducted but lack large-scale visibility, interest, investment, implementation and adoption. This can be partly attributed to the problems that the AI industry is facing, majorly in relation to availability of data and the control that Big Tech and government policies wield on the industry. That being said, the presence of Big Tech and government interest in AI is a good thing because it keeps the technology from becoming a thing of the past through continuous funding. The only thing that is needed is a shift in focus by all the stakeholders in the industry.</p><p>However, fear not, because not all hope is lost! AI clearly has the technical capability to help society as evidenced by the <a href="https://www.mckinsey.com/featured-insights/artificial-intelligence/applying-artificial-intelligence-for-social-good">mapping of capability to social goals</a>. And as the title of the article implies, AI <em>is </em>being used for much social good; it has just not reached a tipping point towards mainstream interest and investment. <a href="https://www.technologyreview.com/innovators-under-35/2021/">People</a>, <a href="https://ai-for-sdgs.academy/">think tanks</a> and <a href="https://ai4good.org/ai-for-sdgs/">organizations</a> are actively involved in research and development of applications that aim for a better society. Here is to hoping they get the support they deserve!</p><p>I’d love to connect on <a href="http://www.linkedin.com/in/kunjmehta">Linkedin</a>!</p><h3>References</h3><ol><li><a href="https://www.nytimes.com/2021/04/29/technology/big-tech-pandemic-economy.html">New York Times: ‘A Perfect Positive Storm’: Bonkers Dollars for Big Tech</a></li><li><a href="https://www.forbes.com/sites/forbestechcouncil/2021/01/15/how-the-pandemic-has-accelerated-cloud-adoption/?sh=951186e66214">Forbes: How The Pandemic Has Accelerated Cloud Adoption</a></li><li><a href="https://aiindex.stanford.edu/wp-content/uploads/2021/03/2021-AI-Index-Report_Master.pdf">Stanford AI Index, 2021</a></li><li><a href="https://www.mckinsey.com/Business-Functions/McKinsey-Analytics/Our-Insights/Global-survey-The-state-of-AI-in-2020">McKinsey: The State of AI in 2020</a></li><li><a href="https://www.itu.int/en/mediacentre/backgrounders/Pages/artificial-intelligence-for-good.aspx">International Telecommunication Unit: Artificial Intelligence for good</a></li><li><a href="https://www.undp.org/sustainable-development-goals">United Nations Sustainable Development Goals</a></li><li><a href="https://www.mckinsey.com/featured-insights/artificial-intelligence/applying-artificial-intelligence-for-social-good">McKinsey: Applying AI for Social Good</a></li><li><a href="https://www.nature.com/articles/s41467-019-14108-y">Nature: The Role of Artificial Intelligence in Achieving the Sustainable Development Goals</a></li><li><a href="https://peltarion.com/blog/applied-ai/17-ways-to-reach-un-sdgs-with-ai">17 ways to reach the UN’s sustainable goals with AI</a></li><li><a href="https://www.wired.com/story/dark-side-big-tech-funding-ai-research/">Wired: The Dark Side of Big Tech’s Funding for AI Research</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a2f7236a4f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-mainstream-ai-is-not-doing-9a2f7236a4f7">What Mainstream AI is (Not) Doing</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to PySpark via AWS EMR and Hands-on EDA]]></title>
            <link>https://pub.towardsai.net/introduction-to-pyspark-via-aws-emr-and-hands-on-eda-de1866d641f5?source=rss-ab5f9f992f70------2</link>
            <guid isPermaLink="false">https://medium.com/p/de1866d641f5</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Kunj Mehta]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 07:12:02 GMT</pubDate>
            <atom:updated>2021-03-02T02:35:33.660Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/data-analysis">Data Analysis</a>, <a href="https://towardsai.net/p/category/programming">Programming</a></h4><h4>Performing EDA on NY Taxi Fare Dataset to see PySpark in action — because cloud computing is the next big thing!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d3jLbRiQJQwhjRQU" /><figcaption>Photo by <a href="https://unsplash.com/@dianamia?utm_source=medium&amp;utm_medium=referral">C Dustin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introducing the Technologies</h3><h4>What is Spark and PySpark — Spark SQL and Spark MLlib?</h4><p>From Wikipedia, Spark by Apache is an open-source analytics engine for large-scale data processing. It enables programmers to work upon data stored in multiple clusters with inherent data parallelism and fault tolerance.</p><p>At the base of the Spark engine are Resilient Distributed Databases (RDDs) that are a set of data items maintained over a cluster of machines in a fault-tolerant manner. These RDDs were developed to overcome the limitation of the Map-Reduce paradigm that forced a linear flow of data in programs by reading from disk, <em>mapping </em>and <em>reducing</em> and writing back to disk. RDDs on the other hand, function as a working set across clusters and offer a restricted form of shared memory during execution of the program.</p><p><strong>Spark Core</strong> is the foundation of the overall project. It provides distributed task dispatching, scheduling, and basic I/O functionalities, exposed through an API centered on the RDD abstraction discussed above. <strong>Spark SQL </strong>is a component on top of Spark Core that introduced a data abstraction called DataFrames, which provides support for structured and semi-structured data. It provides both a domain-specific language (similar to pandas) to manipulate DataFrames and basic SQL support, with CLIs and ODBC servers. Similarly, <strong>Spark MLlib </strong>is a distributed machine learning framework on top of Spark Core.</p><p>Basically, <strong>PySpark </strong>is a Python API for the Scala-written Spark framework. This API contains libraries and wrappers that allow the programmer to leverage the functionalities and features of the underlying SparkSQL and Spark MLlib modules, among others.</p><h4>What is AWS EMR?</h4><p>Amazon Elastic Map Reduce is the industry-leading cloud big data platform for processing vast amounts of data using open source tools such as Apache Spark, Apache Hive, Apache HBase, Apache Flink and Apache Hudi. Amazon EMR makes it easy to set up, operate, and scale your big data environments by automating time-consuming tasks like provisioning capacity and tuning clusters.</p><blockquote>Basically, it is distributed data processing using Spark on the cloud.</blockquote><h3>Setting it Up — AWS EMR vs Local PySpark Instance</h3><p>There are two options that a programmer has in using the Spark framework. He can either decide to install it on his local system or use a service provided by some cloud provider.</p><p>If he goes with the first option, then the cores of the processor in the local system act as the clusters and parallelism is achieved at the core level. The problem with this approach is that some part of the RAM is already reserved as a <em>working memory </em>which is used to combine the results after distributed processing on the data is completed. This along with the RAM specifications on personal laptops today (8GB or 16GB) make this option very unattractive; the data processing is understandably very slow. On the other hand, using clusters in the cloud on a pay-as-you-use model offer unlimited options of system configurations and are clearly the better choice.</p><p>A brief on how to setup a cluster and a notebook on <a href="https://console.aws.amazon.com/elasticmapreduce/home?region=us-east-1">AWS EMR</a> follows:</p><ol><li>Click on the link above. Then click on ‘Clusters’ on the side bar.</li><li>Click on the blue ‘Create Cluster’ and go to ‘Advanced Options’</li></ol><figure><img alt="Step 3: Check the Spark framework for it to be installed on the cluster. The software settings needs a config file or JSON file stored in a S3 bucket that specifies the amount of working memory and core memory." src="https://cdn-images-1.medium.com/max/1024/1*ruEOeK3_Bk30fiyNNs_fyw.png" /><figcaption>Step 3: Check the Spark framework for it to be installed on the cluster. The software settings needs a config file or JSON file stored in a S3 bucket that specifies the amount of working memory and core memory. Source: Image by the author.</figcaption></figure><figure><img alt="Step 4: In Hardware, select the type and number of instances in the cluster as required for the task. Everything else can be kept as is." src="https://cdn-images-1.medium.com/max/1024/1*THS2PgxH_EO9oqxIq1myng.png" /><figcaption>Step 4: In Hardware, select the type and number of instances in the cluster as required for the task. Everything else can be kept as is. Source: Image by the author.</figcaption></figure><figure><img alt="Step 5: We can keep the default settings in ‘General Cluster Settings’ as is. In ‘Security’, an EC2 key pair will have to be specified before a cluster is finally created." src="https://cdn-images-1.medium.com/max/1024/1*ZUSuYfnelfWPFZGloApAmA.png" /><figcaption>Step 5: We can keep the default settings in ‘General Cluster Settings’ as is. In ‘Security’, an EC2 key pair will have to be specified before a cluster is finally created. Source: Image by the author.</figcaption></figure><p>After the cluster has been created, go to the ‘Notebooks’ on the sidebar and create a notebook associated with the cluster. And you are good to go!</p><h3>The Dataset</h3><p>Now that we have had a brief look at the different technologies we will be using and decided upon a configuration option, let’s look at the dataset we will be working on.</p><p>The dataset can be downloaded on <a href="https://www.kaggle.com/c/new-york-city-taxi-fare-prediction/data">Kaggle</a> and contains 55 million records of trips of taxis in New York — perfect for big data and Spark. It has the following features:</p><ul><li><em>key</em>: this is the timestamp of the start of the trip</li><li><em>fare amount</em>: the fare for the trip (in dollars)</li><li><em>pickup_datetime: </em>the same as the key, this is the timestamp of the start of the trip</li><li><em>pickup_longitude: </em>the longitude co-ordinates of the pickup</li><li><em>pickup_latitude</em>: the latitude co-ordinates of the pickup</li><li><em>dropoff_longitude: </em>the longitude co-ordinates of the drop</li><li><em>dropoff_latitude: </em>the latitude co-ordinates of the drop</li><li><em>passenger_count: </em>the number of passengers in the taxi for the trip</li></ul><p>The objective of this problem statement is to apply appropriate EDA and feature engineering to predict taxi fares from a particular pickup point to dropoff point as closely as possible (as compared against the test set ground truth).</p><h3>Finally, the EDA</h3><p>Now, let’s dive into the EDA that was done for this dataset. As mentioned before in passing, using cloud provider services for distributed processing of data is beneficial, and that view is vindicated by looking at the size of the NY Taxi dataset — which would not have been possible to process on PCs anyway.</p><h4>Initial Analysis</h4><p>We import the libraries and read in the data as given below. Next, we perform very basic analysis as to the size of the dataset, schema and the columns present in it.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import pandas as pd</pre><pre># all data manipulation functions<br>import pyspark.sql.functions as F<br>from pyspark.sql import Row</pre><pre>#PySpark does not have visualization capabilities<br>from pyspark_dist_explore import Histogram, hist, distplot, pandas_histogram</pre><pre>train_data_path = &#39;s3://ny-taxi-emr/train.csv&#39;<br>test_data_path = &#39;s3://ny-taxi-emr/test.csv&#39;</pre><pre>train_data = spark.read.csv(train_data_path, header = True, inferSchema = True, mode=&quot;DROPMALFORMED&quot;)<br>test_data = spark.read.csv(test_data_path, header = True, inferSchema = True, mode=&quot;DROPMALFORMED&quot;)</pre><p>Next, we convert the data type of the columns with date-time values into the <em>date-time </em>data type. Here, <strong>withColumn() </strong>is used to create and replace an existing column while <strong>col()</strong> is used to access the column values.</p><pre>train_data = train_data.withColumn(&quot;pickup_datetime&quot;, F.to_timestamp(F.col(&quot;pickup_datetime&quot;), &quot;yyyy-MM-dd HH:mm:ss&quot;))</pre><pre>def create_date_columns():<br>    &quot;&quot;&quot;<br>        Create new rows from pickup_datetime, <br>        namely, date, day, hour, day_of_week, month and year<br>    &quot;&quot;&quot;<br>    # Get datetime.date objects and create a new column pickup_date<br>    new_train_data = train_data.withColumn(&quot;pickup_date&quot;, F.to_date(F.col(&quot;pickup_datetime&quot;)))<br>    new_train_data = new_train_data.withColumn(&quot;pickup_day&quot;, F.dayofmonth(F.col(&quot;pickup_datetime&quot;)))<br>    new_train_data = new_train_data.withColumn(&quot;pickup_hour&quot;, F.hour(F.col(&quot;pickup_datetime&quot;)))<br>    new_train_data = new_train_data.withColumn(&quot;pickup_day_of_week&quot;, F.dayofweek(F.col(&quot;pickup_datetime&quot;)))<br>    new_train_data = new_train_data.withColumn(&quot;pickup_month&quot;, F.month(F.col(&quot;pickup_datetime&quot;)))<br>    new_train_data = new_train_data.withColumn(&quot;pickup_year&quot;, F.year(F.col(&quot;pickup_datetime&quot;)))<br>    <br>    return new_train_data</pre><p>Next, we check for null values and drop rows with null values.</p><pre>new_train_data.select([F.count(F.when(F.isnull(col), col)).alias(col) for col in new_train_data.columns]).show()</pre><h4>Visualizing Dimension Distributions</h4><p>We first start with visualizing the distributions of the appropriate dimensions. We start with the <em>fare </em>dimension and remove fares that are either too high or negative in value. <strong>collect() </strong>is used to retrieve the end-results from all the slaves to the master or driver node.</p><pre>print(&quot;Maximum Fare:{}\n Minimum Fare: {}&quot;.format(new_train_data.agg({&quot;fare_amount&quot;: &quot;max&quot;}).collect()[0],\<br>      new_train_data.agg({&quot;fare_amount&quot;: &quot;min&quot;}).collect()[0]))</pre><pre>train_data_fare_filtered = new_train_data.filter(F.col(&quot;fare_amount&quot;).between(2.5, 100))</pre><figure><img alt="Distribution of fare amount(binned)" src="https://cdn-images-1.medium.com/max/807/1*0pQve395IwlUqA-OjJKTDw.png" /><figcaption>Distribution of fare amount(binned). Source: Image by the author.</figcaption></figure><p>Similarly, we analyze the passenger count distribution and find that the maximum value is 208, which does not make sense. We take into consideration 7-seater cars as the maximum passenger count.</p><figure><img alt="Distribution of passenger count" src="https://cdn-images-1.medium.com/max/813/1*hV2_W_3vsblpYeZOR0TBLA.png" /><figcaption>Distribution of passenger count. Source: Image by the author.</figcaption></figure><p>Again, we similarly do the same boundary analysis for the co-ordinate fields and remove trips which have co-ordinates beyond 2 degrees from the centre of NY. (40.771133, -73.974187).</p><pre>train_data_filtered = train_data_passenger_filtered.filter((F.col(&quot;pickup_latitude&quot;).between(38.5, 42.5)))<br>train_data_filtered = train_data_filtered.filter((F.col(&quot;dropoff_latitude&quot;).between(38.5, 42.5)))<br>train_data_filtered = train_data_filtered.filter((F.col(&quot;pickup_longitude&quot;).between(-76, -72)))<br>train_data_filtered = train_data_filtered.filter((F.col(&quot;dropoff_longitude&quot;).between(-76, -72)))</pre><h4>Airport Fare Analysis</h4><p>Plotting the trip co-ordinates on a map, we see that there are many pickups and drops from and to airports in NY. We go on to analyze this after obtaining the co-ordinates of the airports in NY.</p><pre>1. Coordinates of Newark Airport = 40.6895° N, 74.1745° W<br><br>2. Coordinates of JFK Airport = 40.6413° N, 73.7781° W<br><br>3. Coordinates of La Guardia Airport = 40.7769° N, 73.8740° W</pre><figure><img alt="Pickup fare distribution at JFK" src="https://cdn-images-1.medium.com/max/811/1*dey_H63AzAuigDGmskmLXg.png" /><figcaption>Pickup fare distribution at JFK. Source: Image by the author</figcaption></figure><figure><img alt="Dropoff fare distribution at JFK" src="https://cdn-images-1.medium.com/max/826/1*Yzr2mhJbzpm2lVy0eEubGQ.png" /><figcaption>Dropoff fare distribution at JFK. Source: Image by the author.</figcaption></figure><p>We can see that the pickup and dropoff fares for JFK are more in the $40–$60 range which can suggest fixed pricing. To confirm, let’s compare this with average fare for all trips.</p><figure><img alt="Distribution of fare amount" src="https://cdn-images-1.medium.com/max/770/1*YjyD8vPsRhGTVLLu3AE7tg.png" /><figcaption>Distribution of fare amount. Source: Image by the author.</figcaption></figure><p>We find that the average fare is much higher when trips are related to airports. So, differentiating these records by feature engineering will help us build a better model as it will be able to differentiate and recognize the difference in pattern between airport trips and non-airport trips. So, we create features that specify whether a record (trip) is to any of the 3 airports.</p><h4>Feature Engineering</h4><p>For feature engineering and making additional dimensions related to airports, we use something called an <a href="https://docs.databricks.com/spark/latest/spark-sql/udf-python.html">User-Defined Function</a> (UDF) in PySpark. This allows us to use user-defined Python functions with the Spark framework.</p><pre>from pyspark.sql.functions import udf<br>from pyspark.sql.types import BooleanType</pre><pre># user-defined Python function<br>def isTripRelatedToAirport(latitude,longitude,airport_name=&#39;JFK&#39;):   <br>    if ((latitude &gt;= nyc_airports[airport_name][&#39;min_lat&#39;]) &amp; <br>        (latitude &lt;= nyc_airports[airport_name][&#39;max_lat&#39;]) &amp; <br>        (longitude &gt;= nyc_airports[airport_name][&#39;min_lng&#39;]) &amp; <br>       (longitude &lt;= nyc_airports[airport_name][&#39;max_lng&#39;])):<br>        return True<br>    else:<br>        return False</pre><pre># name the UDF using lambdas<br>featureEngineeringUDF = udf(lambda x, y, z: isTripRelatedToAirport(x,y,z),BooleanType())</pre><pre># register the Python UDF with Spark<br>spark.udf.register(&quot;featureEngineeringUDF&quot;, featureEngineeringUDF)</pre><p>Using this UDF, we build the airport-related dimensions. <strong>lit</strong> is used to pass a hardcoded string into the UDF.</p><pre>train_data_filtered = train_data_filtered.withColumn(&quot;is_pickup_JFK&quot;, featureEngineeringUDF(F.col(&quot;pickup_latitude&quot;),F.col(&quot;pickup_longitude&quot;), lit(&quot;JFK&quot;)))</pre><pre>train_data_filtered = train_data_filtered.withColumn(&quot;is_dropoff_JFK&quot;, featureEngineeringUDF(F.col(&quot;dropoff_latitude&quot;),F.col(&quot;dropoff_longitude&quot;), lit(&quot;JFK&quot;)))</pre><pre>train_data_filtered = train_data_filtered.withColumn(&quot;is_pickup_EWR&quot;, featureEngineeringUDF(F.col(&quot;pickup_latitude&quot;),F.col(&quot;pickup_longitude&quot;), lit(&quot;EWR&quot;)))</pre><pre>train_data_filtered = train_data_filtered.withColumn(&quot;is_dropoff_EWR&quot;, featureEngineeringUDF(F.col(&quot;dropoff_latitude&quot;),F.col(&quot;dropoff_longitude&quot;), lit(&quot;EWR&quot;)))</pre><pre>train_data_filtered = train_data_filtered.withColumn(&quot;is_pickup_LaGuardia&quot;, featureEngineeringUDF(F.col(&quot;pickup_latitude&quot;),F.col(&quot;pickup_longitude&quot;), lit(&quot;LaGuardia&quot;)))</pre><pre>train_data_filtered =  train_data_filtered.withColumn(&quot;is_dropoff_LaGuardia&quot;, featureEngineeringUDF(F.col(&quot;dropoff_latitude&quot;),F.col(&quot;dropoff_longitude&quot;), lit(&quot;LaGuardia&quot;)))</pre><p>Next, we calculate the trip distance in kilometers from the co-ordinates using the <a href="https://en.wikipedia.org/wiki/Haversine_formula"><strong>Haversine Formula</strong></a><strong>.</strong></p><pre>from pyspark.sql.types import DoubleType, ArrayType, DecimalType<br>import math<br><br>def trip_distance(lat1, lat2, lon1, lon2):<br>    &quot;&quot;&quot;<br>    Calculate trip distance based on Haversine formula<br>    Args:<br>        lat1: Latitude of first point<br>        lat2: Latitude of second point<br>        lon1: Longitude of first point<br>        lon2: :ongitude of second point<br>    Returns:<br>        Distance between the two points in miles<br>    &quot;&quot;&quot;<br>    # pi / 180<br>    p = 0.017453292519943295<br>    a = 0.5 - math.cos((lat2 - lat1) * p)/2 + math.cos(lat1 * p) * math.cos(lat2 * p) * (1 - math.cos((lon2 - lon1) * p)) / 2<br>    return 0.6213712 * 12742 * math.asin(math.sqrt(a))<br><br>haversineUDF = udf(lambda a, b, c, d: trip_distance(a,b,c,d), DoubleType())<br>spark.udf.register(&quot;haversineUDF&quot;, haversineUDF)</pre><pre>train_data_filtered = train_data_filtered.withColumn(&quot;trip_distance&quot;, haversineUDF(F.col(&quot;pickup_latitude&quot;), F.col(&quot;dropoff_latitude&quot;), F.col(&quot;pickup_longitude&quot;), F.col(&quot;dropoff_longitude&quot;)))</pre><h4>Borough-wise Analysis</h4><p>We also do a borough-wise trip fare analysis, similar to the airport analysis by obtaining the co-ordinates of all the boroughs in NY — Queens, Brooklyn, Bronx, Manhattan, Staten Island.</p><pre>def getBorough(lat,lng):<br>    &quot;&quot;&quot;<br>    Get the borough based on latitude and longitude<br>    Args:<br>        lat: Latitude of the place<br>        lng: Longitude of the place<br>    Returns:<br>        A string representing the name of the borough<br>    &quot;&quot;&quot;<br>    locations = nyc_boroughs.keys()<br>    for location in locations:<br>        if (lat &gt;= nyc_boroughs[location][&#39;min_lat&#39;] and <br>            lat &lt;= nyc_boroughs[location][&#39;max_lat&#39;] and <br>            lng &gt;= nyc_boroughs[location][&#39;min_lng&#39;] and <br>            lng &lt;= nyc_boroughs[location][&#39;max_lng&#39;]):<br>            return location<br>    return &#39;others&#39;<br><br>boroughUDF = udf(lambda a, b: getBorough(a,b))<br>spark.udf.register(&quot;boroughUDF&quot;, boroughUDF)</pre><pre><br>train_data_filtered = train_data_filtered.withColumn(&quot;pickup_borough&quot;, boroughUDF(F.col(&quot;pickup_latitude&quot;), F.col(&quot;pickup_longitude&quot;)))</pre><pre>train_data_filtered = train_data_filtered.withColumn(&quot;dropoff_borough&quot;, boroughUDF(F.col(&quot;dropoff_latitude&quot;), F.col(&quot;dropoff_longitude&quot;)))</pre><figure><img alt="Fare distribution for Manhattan" src="https://cdn-images-1.medium.com/max/804/1*pUf2YZnb7nMuRNCVSW9FFQ.png" /><figcaption>Fare distribution for Manhattan. Darker red is for pickup fares and ligher red for drop-off fares. Source: Image by the author.</figcaption></figure><figure><img alt="Fare distribution for Bronx" src="https://cdn-images-1.medium.com/max/731/1*linApxSg-QUDo2wPlautVQ.png" /><figcaption>Fare distribution for Bronx. Darker red is for pickup fares and ligher red for drop-off fares. Source: Image by the author.</figcaption></figure><figure><img alt="Fare distribution for Queens" src="https://cdn-images-1.medium.com/max/818/1*Ny-91mbxh0DLNchoP1D4Gw.png" /><figcaption>Fare distribution for Queens. Darker red is for pickup fares and ligher red for drop-off fares. Source: Image by the author.</figcaption></figure><figure><img alt="Fare distribution for Brooklyn" src="https://cdn-images-1.medium.com/max/775/1*PkUA-IEmBMgEo5r58_NY7w.png" /><figcaption>Fare distribution for Brooklyn. Darker red is for pickup fares and ligher red for drop-off fares. Source: Image by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*xcIbC4-0VGSc90fsoFOfyw.png" /><figcaption>Fare distribution for Staten Island. Darker red is for pickup fares and ligher red for drop-off fares. Source: Image by the author.</figcaption></figure><p>We conclude the following from the above borough-wise graphs:</p><ol><li>Pickup and dropoff fare amount are almost similarly distributed for Manhattan.</li><li>Dropoff fare is higher for Bronx, Brooklyn and Staten Island meaning people come from far out into the Bronx, Brooklyn and Staten Island</li><li>For Queens, both averages are higher meaning people usually take longer trips in general</li></ol><h4>Time-based Analysis</h4><p>Lastly, we do some time-based analysis before going on to predictions with the Spark MLlib. To better help with visualizations, the end results from PySpark DataFrames have been converted into Pandas dataframes using <strong>toPandas()</strong></p><pre>trips_by_year = train_data_filtered.groupBy(&quot;pickup_year&quot;).count().toPandas()<br>trips_by_year = trips_by_year.sort_values(by = &quot;pickup_year&quot;)<br>trips_by_year</pre><pre>trips_by_month = train_data_filtered.groupBy(&quot;pickup_month&quot;).count().toPandas()<br>trips_by_month = trips_by_month.sort_values(by = &quot;pickup_month&quot;)<br>trips_by_month</pre><pre>#similar for other granularities of time</pre><figure><img alt="Distribution of trips per year" src="https://cdn-images-1.medium.com/max/781/1*LpKX_bHME2d0FWmVwtXHiw.png" /><figcaption>Trips by year. Source: Image by the author</figcaption></figure><figure><img alt="Distribution of trips per month" src="https://cdn-images-1.medium.com/max/722/1*mU75j2s8gIu3Mb6U1Eh0jQ.png" /><figcaption>Trips by month. Source: Image by the author</figcaption></figure><figure><img alt="Trips by day of week" src="https://cdn-images-1.medium.com/max/761/1*_BqLlkITvhbuThHuy99A0w.png" /><figcaption>Trips by day of week. Source: Image by the author</figcaption></figure><figure><img alt="Trips by hour" src="https://cdn-images-1.medium.com/max/756/1*MKQUNItPDmpoC6ny8Jhgxw.png" /><figcaption>Trips by hour. Source: Image by the author.</figcaption></figure><h3>Building a ML Pipeline</h3><p>First of all, we drop the columns with data type <em>date-time</em> because those will require time series concepts. We also encode the boroughs associated with each trip. <strong>StringIndexer </strong>is used to encode (convert from categorical to numerical) while <strong>OneHotEncoderEstimator </strong>is used to one-hot encode the subsequent numerical encodings of the boroughs.</p><pre>train_data_filtered = train_data_filtered.drop(&quot;pickup_datetime&quot;, &quot;pickup_date&quot;, &quot;key&quot;)</pre><pre># create object of StringIndexer class and specify input and output column<br>SI_pickup = StringIndexer(inputCol=&#39;pickup_borough&#39;,outputCol=&#39;pickup_borough_encoded&#39;)<br>SI_dropoff = StringIndexer(inputCol=&#39;dropoff_borough&#39;,outputCol=&#39;dropoff_borough_encoded&#39;)<br><br># transform the data<br>train_data_filtered = SI_pickup.fit(train_data_filtered).transform(train_data_filtered)<br>train_data_filtered = SI_dropoff.fit(train_data_filtered).transform(train_data_filtered)<br><br># create object and specify input and output column<br>OHE = OneHotEncoderEstimator(inputCols=[&#39;pickup_borough_encoded&#39;, &#39;dropoff_borough_encoded&#39;],outputCols=[&#39;pickup_borough_OHE&#39;, &#39;dropoff_borough_OHE&#39;])<br><br># transform the data<br>train_data_filtered = OHE.fit(train_data_filtered).transform(train_data_filtered)<br><br>train_data_filtered = train_data_filtered.drop(&quot;pickup_borough&quot;, &quot;dropoff_borough&quot;, &quot;pickup_borough_encoded&quot;, dropoff_borough_encoded&quot;)</pre><p>Next, <strong>VectorAssembler </strong>is used to combine all the features into a single frature vector that simplifies the processing and predicton of data for the machine learning algorithms.</p><pre>featureColumns = [&#39;pickup_longitude&#39;, &#39;pickup_latitude&#39;, &#39;dropoff_longitude&#39;, &#39;dropoff_latitude&#39;, &#39;passenger_count&#39;, &#39;pickup_day&#39;, &#39;pickup_hour&#39;, &#39;pickup_day_of_week&#39;, &#39;pickup_month&#39;, &#39;pickup_year&#39;, &#39;is_pickup_JFK&#39;, &#39;is_dropoff_JFK&#39;, &#39;is_pickup_EWR&#39;, &#39;is_dropoff_EWR&#39;, &#39;is_pickup_LaGuardia&#39;, &#39;is_dropoff_LaGuardia&#39;, &#39;trip_distance&#39;, &#39;is_pickup_in_lower_manhattan&#39;, &#39;is_drop_in_lower_manhattan&#39;, &#39;pickup_borough_OHE&#39;, &#39;dropoff_borough_OHE&#39;]<br><br>assembler = VectorAssembler(inputCols= featureColumns, outputCol=&quot;features&quot;)<br><br>full_set = assembler.transform(train_data_filtered)</pre><p>Lastly, we apply train-test split and perform model training using Decision Tree and Random Forest.</p><pre>train_set, test_set = full_set.randomSplit([0.9, 0.1], seed=0)</pre><pre>from pyspark.ml.regression import RandomForestRegressor<br>from pyspark.ml.evaluation import RegressionEvaluator<br><br>rf = RandomForestRegressor(labelCol=&quot;fare_amount&quot;, featuresCol= &quot;features&quot;)<br>model = rf.fit(train_set)<br><br>predictions = model.transform(test_set)</pre><pre>evaluator = RegressionEvaluator(predictionCol=&quot;prediction&quot;, labelCol=&quot;fare_amount&quot;,metricName=&quot;rmse&quot;)<br>print(&quot;RMSE Error on test set: &quot;, evaluator.evaluate(predictions)</pre><p>The accuracy for the Random Forest model is 4.4201.</p><pre>from pyspark.ml.regression import DecisionTreeRegressor<br>from pyspark.ml.evaluation import RegressionEvaluator</pre><pre>dt = DecisionTreeRegressor(labelCol=&quot;fare_amount&quot;, featuresCol= &quot;features&quot;)<br>model = dt.fit(train_set)<br><br>predictions = model.transform(test_set)</pre><pre>evaluator = RegressionEvaluator(predictionCol=&quot;prediction&quot;, labelCol=&quot;fare_amount&quot;,metricName=&quot;rmse&quot;)<br>print(&quot;RMSE Error on test set: &quot;, evaluator.evaluate(predictions))</pre><p>The best RMSE error we get is for the Decision Tree model<strong> — 4.2814. </strong>You can refer to the full code (including for visualizations) and output on <a href="https://github.com/kunjmehta/ny-taxi-prediction-pyspark-emr/blob/main/NY%20Taxi%20PySpark.ipynb">GitHub</a>.</p><p>I would love to connect with you on <a href="https://www.linkedin.com/in/kunjmehta">Linkedin</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de1866d641f5" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/introduction-to-pyspark-via-aws-emr-and-hands-on-eda-de1866d641f5">Introduction to PySpark via AWS EMR and Hands-on EDA</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fantasy Premier League x Data Analysis: Being Among the Top 2%]]></title>
            <link>https://medium.com/data-science/fantasy-premier-league-x-data-analysis-being-among-the-top-2-98a714a1d170?source=rss-ab5f9f992f70------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a714a1d170</guid>
            <category><![CDATA[football]]></category>
            <category><![CDATA[linear-programming]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[fantasy-football]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kunj Mehta]]></dc:creator>
            <pubDate>Sun, 14 Feb 2021 17:06:53 GMT</pubDate>
            <atom:updated>2023-08-10T19:33:07.288Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief overview of the application I built, in which I have employed data analysis to power my FPL team up the charts</h4><p><strong>Edit: </strong>App relaunched for the 2023–24 season <a href="https://fpl-teammaker.streamlit.app/">here</a>.</p><h3>Fantasy Premier League: A Phenomenon</h3><p>Non-football or non-sports fans will ask what exactly is Fantasy Premier League (FPL)? Well, let’s start with what FPL is and then see the rules of how the game is played before diving into the code of the data analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D4ggtQKTgfO0N0dT" /><figcaption>Photo by <a href="https://unsplash.com/@jaaack?utm_source=medium&amp;utm_medium=referral">Jack Monach</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Overview of the Game</h4><p>From <a href="https://en.wikipedia.org/wiki/Fantasy_football_(association)">Wikipedia</a>, fantasy football (and fantasy sports in general) is a game in which participants assemble an imaginary team of real life footballers (sportsmen) and score points based on those players’ actual statistical performance or their perceived contribution on the field of play. Usually, in a particular fantasy game, players are selected from one specific division in a particular country.</p><p>So, FPL is the fantasy football league for the English Premier League in England. The original version of what is now Fantasy Premier League was created in England by Bernie Donnelly on Saturday 14 August 1971. The author has been playing the current online version of the <a href="http://fantasy.premierleague.com/">FPL</a> for five years now with mixed results. However, the ‘results’ for the game itself have been all but mixed: from around 3.5 million players during the 2014/15 season to 8 million now, the game has been adding around three-quarters of a million players each year.</p><p>A very understandable question here would be: What makes this game so attractive and addictive? Well, first of all, it is the inherent allure of football, the English Premier League and the fantasy of managing your own team, all combined. Add to this, mini-leagues that you can play with your friends and the bragging rights that come if you can win these mini-leagues or the FPL itself (if you can manage it, that is). To top it all off, with the amount of money that revolves around the English Premier League, they decided they could afford to invite the winner of the game for a 3-day fully funded trip to England with the honours of watching a live match of their favourite team to go along with it. No wonder every mad English football fan plays it!</p><h4>Rules of the Game</h4><p>Now that we have established the significance of the game, let’s take a look at the rules. These will come in handy when we deep-dive into the code as the data analysis has been done keeping in mind the rules of the game.</p><p>The premise: the player is given a budget of 100 million to buy a squad of 15 players consisting of 2 goalkeepers, 5 defenders, 5 midfielders and 3 forwards with the added rule of being able to select a maximum of 3 players from any particular team. The cost of a player is predetermined by the game developers, based on the player’s popularity and performance in the last football season.</p><p>On top of this, after every round (called gameweek) of games, the user has the option to transfer one player out from his team and bring in another one of the same position if he so wishes, for free. Any additional transfers incur a 4 point penalty. For more nuances about the rules and the game’s scoring system, you can visit this <a href="https://fantasy.premierleague.com/help/rules">page</a>.</p><p>The objective of the game: To have the best-scoring team of players possible every week given the budget and other constraints so that in the long-term, you can accumulate the most points among other players.</p><h3>The Data</h3><p>The makers of the game maintain an API that powers their website. This API is publicly accessible <a href="https://fantasy.premierleague.com/api/bootstrap-static/">here</a>. It contains data about each Gameweek, each team, and statistics on each player in the league. This is why it is a gold mine for data analysis!</p><p>We performed some preliminary EDA on this data to test out some of the hypotheses. One of it was whether the position of a team in the league table has a bearing on the performance of the players in that team as far as FPL was concerned. Meaning that whether players belonging to teams in the top half of the table had more FPL points than from players belonging to bottom half teams. If this would have been the case, we would need the teams data from the API. However, the hypothesis turned out to be false. Though true on a very high level, there were some outliers that were too high-scoring to be ignored.</p><p>So, having established that team position has more or less no bearing on player performance in the FPL, we just decided to extract the player statistics data for the whole player roster. This included the following information:</p><pre>[&#39;id&#39;, &#39;code&#39;, &#39;first_name&#39;, &#39;second_name&#39;, &#39;web_name&#39;, &#39;team_code&#39;, &#39;player_type&#39;, &#39;status&#39;, &#39;form&#39;, &#39;total_points&#39;, &#39;points_per_game&#39;, &#39;minutes_played&#39;, &#39;goals_scored&#39;, &#39;assists&#39;, &#39;clean_sheets&#39;, &#39;goals_conceded&#39;, &#39;own_goals&#39;, &#39;penalties_saved&#39;, &#39;penalties_missed&#39;, &#39;yellow_cards&#39;,&#39;red_cards&#39;, &#39;saves&#39;, &#39;bonus&#39;, &#39;now_cost&#39;]</pre><p>Most of the attributes above are self-explanatory. web_name is the name of the player used on the website. player_type is whether the player is a forward, midfielder, defender or goalkeeper. status refers to the injury status of the player. form is an integer that represents the form of the player — the higher the better.</p><p>A side note here: Because at the start of the season, there is no data on player performances for that season (obviously!), we have used the previous season’s final week data to make decisions on players and build a team for Gameweeks that occurred before transfer deadline day. Once the teams were finalized and a suitable amount of current season data became available, we started using that to make the decisions as to who to include in the team.</p><h3>FPL-TeamMaker: The Application</h3><p>The application which can be found <a href="http://fpl-teammaker.herokuapp.com/">here</a> has two modes: the <strong>team-building </strong>mode and the <strong>transfer </strong>mode. The team-building mode allows the user to build a 15 player team with customizations on number of players per team and importance to be given on form and total points left upto the user. The transfer mode allows the user to transfer in a specified number of players into his already existing team, which he inputs. Let’s dive into the details below.</p><h4>Pandas and PuLP: The Analysis Backend</h4><blockquote>The intuition behind the analysis was simple: It is best to have (normally expensive) players who are top in the scoring charts but it is also good to have value players in best form at a given time to offset some bad performances by the top-scoring players.</blockquote><p>As per the intuition, the two most important attributes for data manipulation become total_points and form. First and foremost though, before performing the analysis and using it to prepare a 15 player team, we remove injured players from the player roster.</p><pre>injured_players_df = player_df[player_df[&#39;status&#39;] != &#39;a&#39;]</pre><p>Next, based on the intuition to have the top scoring players, we compulsorily try to put in the top scorer for each position first. Then we go onto fill the rest of the 11 players.</p><pre>top_players_positions_to_be_filled = {&#39;GKP&#39;:1, &#39;DEF&#39;:1, &#39;MID&#39;: 1, &#39;FWD&#39;: 1}<br>top_players_positions_filled = {&#39;GKP&#39;:0, &#39;DEF&#39;:0, &#39;MID&#39;: 0, &#39;FWD&#39;: 0}<br> i = 0<br>while top_players_positions_filled != top_players_positions_to_be_filled and i &lt; len(top_players_point_sort):<br>        if teams_filled[top_players_point_sort.iloc[i][&#39;team_code&#39;]] &gt; 0 and top_players_positions_filled[top_players_point_sort.iloc[i][&#39;player_type&#39;]] &lt; 1:<br>    team_cost += top_players_point_sort.iloc[i][&#39;now_cost&#39;]<br>    team_points += top_players_point_sort.iloc[i][&#39;total_points&#39;]<br>    positions_filled[top_players_point_sort.iloc[i][&#39;player_type&#39;]] -= 1<br>    top_players_positions_filled[top_players_point_sort.iloc[i][&#39;player_type&#39;]] += 1<br>    teams_filled[top_players_point_sort.iloc[i][&#39;team_code&#39;]] -= 1</pre><pre>    players_in_team.append(top_players_point_sort.iloc[i] [&#39;second_name&#39;])<br>    i += 1</pre><p>We fill in the remaining 11 players using linear programming leveraging the Python library PuLP . The LP problem that is solved is maximizing a metric (based on past data) while keeping a constraint on the budget, maximum number of players to be filled in each position and maximum number of players allowed from a team (the last of which is an user-customizable input). The metric that is calculated for each player is a combination of player form and total points and the importance of each is again decided by the user.</p><pre>def add_players_using_lp(metric, costs, player_type, team, budget, team_counts,positions_filled):<br>    <br>    num_players = len(metric)<br>    model = pulp.LpProblem(&quot;Constrained value maximisation&quot;, pulp.LpMaximize)<br>    decisions = [<br>        pulp.LpVariable(&quot;x{}&quot;.format(i), lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>        for i in range(num_players)<br>    ]<br>    <br>    # objective function:<br>    model += sum(decisions[i] * metric[i] for i in range(num_players)), &quot;Objective&quot;</pre><pre>    # cost constraint<br>    model += sum(decisions[i] * costs[i] for i in range(num_players)) &lt;= budget</pre><pre>    # position constraints<br>    model += sum(decisions[i] for i in range(num_players) if player_type[i] == &#39;GKP&#39;) == positions_filled[&#39;GKP&#39;]<br>    model += sum(decisions[i] for i in range(num_players) if player_type[i] == &#39;DEF&#39;) == positions_filled[&#39;DEF&#39;]<br>    model += sum(decisions[i] for i in range(num_players) if player_type[i] == &#39;MID&#39;) == positions_filled[&#39;MID&#39;]<br>    model += sum(decisions[i] for i in range(num_players) if player_type[i] == &#39;FWD&#39;) == positions_filled[&#39;FWD&#39;]</pre><pre>    # club constraint<br>    for team_code in np.unique(team):<br>        model += sum(decisions[i] for i in range(num_players) if team[i] == team_code) &lt;= \<br>        team_counts[team_code]</pre><pre>    model += sum(decisions) == 11  # total team size</pre><pre>    try:<br>        model.solve()<br>    except:<br>     st.info(&#39;Player roster has not been updated yet. Please be patient&#39;)</pre><pre>return decisions</pre><p>We follow a similar logic for the <strong>transfers </strong>mode of the FPL-TeamMaker. The only difference here is that we take in the existing team of the user. We prioritize transferring out injured players. If there are no injured players in the existing team, we calculate the aforementioned metric and transfer out the player(s) that return the least value of the above metric. In place of the removed players, we try to transfer in the top scorer for that position and if that is not possible due to budget constraints, we use LP to find the best value player; the latter part being identical to the <strong>team-building </strong>mode.</p><h4>Streamlit: The Frontend</h4><p>We have used streamlit which is a Python library that provides functionality to create small front-end applications using pure Python. This makes it pretty simple and fast to build a proof-of-concept website, hostable on Heroku via GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*fwW3TOivOz3mg_LoSJVN0A.png" /><figcaption>Application Homepage (Image by Author)</figcaption></figure><p>As you will see when you visit the page, the first question is the Gameweek for which the team has to be changed. This is to take into consideration the two different datasets being used as mentioned before. Then the user will be asked to select the mode, input the leftover budget, importance to be given to form and total points and maximum players from each team for <strong>team building</strong>; or number of transfers for <strong>transfers </strong>mode.</p><h3>The Results</h3><p>FPL-TeamMaker was built before the 2020/21 season started and the author has been using it every week since to build the team or transfer players. Judgment of the results as good or bad is left to the reader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*zIaGR01QgRvBMFkhSzl-eQ.png" /><figcaption>Progress of Team Points vs Average Points on a Weekly Basis (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*AcDIbzxvJAOuBdo1PFDcJg.png" /><figcaption>Team Points vs Average Points per Week. There are only 3 weeks where team points are less than average points (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*VKpF1ZahzzKX85RjUzlCUg.png" /><figcaption>Overall Rank and Gameweek Rank of my Team over the Weeks (Image by Author)</figcaption></figure><p>As you can see from the above images, (i) the team using the FPL-TeamMaker has consistently outperformed the average from the start; (ii) there were only three Gameweeks where the team’s points were less than the average points; (iii) The team has managed to stay in and around the top 2% of players for 10 weeks now and that too, after a disastrous last week; and (iv) 5 / 15 players currently in the team make the cut for the overall Dream Team.</p><h3>Conclusion</h3><p>You can use the FPL-TeamMaker for the benefit of your own team. The author will be regularly updating the point progress of his team via the graphs on the page</p><p><strong>A bonus tip about FPL-TeamMaker</strong>: Use the <strong>team-building </strong>mode when you use your wildcards.</p><p>You can find the code for FPL-TeamMaker <a href="https://github.com/kunjmehta/Medium-Article-Codes">here</a> and view the points of the FPL-TeamMaker team on FPL <a href="https://fantasy.premierleague.com/entry/2912524/event/24/">here</a>. The team sits at the ranking of 1,34,956 at the time of writing this.</p><p>I would love to connect with you on <a href="https://www.linkedin.com/in/kunjmehta">Linkedin</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a714a1d170" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/fantasy-premier-league-x-data-analysis-being-among-the-top-2-98a714a1d170">Fantasy Premier League x Data Analysis: Being Among the Top 2%</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>