<?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 Alexandra Deis on Medium]]></title>
        <description><![CDATA[Stories by Alexandra Deis on Medium]]></description>
        <link>https://medium.com/@astakhova.aleksandra?source=rss-9f0981e41a86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*twbjNpgB20kWRpmgMO86-g.jpeg</url>
            <title>Stories by Alexandra Deis on Medium</title>
            <link>https://medium.com/@astakhova.aleksandra?source=rss-9f0981e41a86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:12:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@astakhova.aleksandra/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[Generating Titles for Kaggle Kernels with LSTM]]></title>
            <link>https://medium.com/data-science/generating-titles-for-kaggle-kernels-with-lstm-957541aff48f?source=rss-9f0981e41a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/957541aff48f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[sequence-model]]></category>
            <dc:creator><![CDATA[Alexandra Deis]]></dc:creator>
            <pubDate>Sat, 31 Aug 2019 23:45:57 GMT</pubDate>
            <atom:updated>2019-08-31T23:45:57.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UdtXe0Mln5dBYKFLqcfKA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@donatello-trisolino-572447?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Donatello Trisolino </a>from <a href="https://www.pexels.com/photo/person-typing-1375261/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h4>Small Deep Learning Project with PyTorch</h4><h3>Introduction</h3><p>When I first found out about <a href="https://medium.com/machine-learning-bites/deeplearning-series-sequence-models-7855babeb586">sequence models</a>, I was amazed by how easily we can apply them to a wide range of problems: text classification, text generation, music generation, machine translation, and others. In this article, I would like to focus on the step-by-step process of creating a model and won’t cover sequence models and LSTMs theory.</p><p>I got an idea to use <a href="https://www.kaggle.com/kaggle/meta-kaggle">Meta Kaggle</a> dataset to train a model to generate new kernel titles for Kaggle. Kernels are the notebooks in R or Python published on Kaggle by the users. Kaggle users can upvote kernels. Depending on the number of the upvotes, kernels receive medals. Model, which generates kernel titles, can help to capture trends for Kaggle kernels and serve as an inspiration for writing new kernels and get medals. In this article:</p><ul><li>I describe how to load and preprocess kernels data from <a href="https://www.kaggle.com/kaggle/meta-kaggle">Meta Kaggle</a> dataset.</li><li>I demonstrate how to train a PyTorch LSTM model to generate new Kaggle titles and show the results.</li></ul><p>The full code for this small project is available on <a href="https://github.com/Lexie88rus/sequence-models/blob/master/lstm-for-kernel-title-generation-with-pytorch.ipynb">GitHub</a>, or you can play with the code <a href="https://www.kaggle.com/aleksandradeis/lstm-for-kernel-title-generation-with-pytorch">on Kaggle</a>.</p><h3>Load Data</h3><p>At first, I need to load the data. I am loading Kernels and KernelVersions tables, which contain information on all kernels, the total number of votes per kernel (later I explain why we need this) and kernel titles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eee0a78e2d4f7b6c628810f51399354/href">https://medium.com/media/6eee0a78e2d4f7b6c628810f51399354/href</a></iframe><h3>Make a List of Popular Kernel Titles</h3><p>Next step is to make a list of most popular kernel titles, which should be then converted into word sequences and passed to the model. It comes out that kernel titles are <strong>extremely untidy</strong>: misspelled words, foreign words, special symbols or have poor names like `kernel678hggy`.</p><p>That is why:</p><ul><li><strong>I drop kernels without votes from the analysis</strong>. I assume that upvoted kernels should be of better quality and have more meaningful titles.</li><li>I sort kernels by the total number of votes and <strong>take only the most voted ones</strong>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc62daabff80c9219f894ad6300f6c02/href">https://medium.com/media/bc62daabff80c9219f894ad6300f6c02/href</a></iframe><h3>Preprocess Kernel Titles and Create a Vocabulary</h3><p>I decided to try a <strong>word-based model</strong>. That’s why, in the next step, I need to <strong>create a vocabulary</strong>, which should be used to encode word sequences.</p><p>To create the vocabulary, I have to do the following steps:</p><ul><li><strong>Clean each title</strong> to remove punctuation and lowercase all the words.</li><li><strong>Split each title to words</strong> and add each word to the vocabulary.</li><li><strong>Introduce a symbol, which denotes the end of the title</strong> (I chose `.`, but it can be changed), and add it to the vocabulary.</li></ul><p>Let’s introduce a simple function to clean kernel titles:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c1d772584300698c9cff408afe23c6a/href">https://medium.com/media/1c1d772584300698c9cff408afe23c6a/href</a></iframe><p>Now let’s introduce a symbol for the end of title and a word extraction function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b01872f87125283867921847d0455d8/href">https://medium.com/media/9b01872f87125283867921847d0455d8/href</a></iframe><p>The next step is to make a vocabulary consisting of extracted words:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f93f924c5ae6b489d1029bbd3eea77e/href">https://medium.com/media/7f93f924c5ae6b489d1029bbd3eea77e/href</a></iframe><h3>Prepare the Training Set</h3><p>In this section, I create a training set for our future model:</p><ul><li><strong>Introduce functions which encode each word into tensor</strong> using the vocabulary created above. I use the one-hot encoding of words: each word is represented as a tensor with zeros and ones with all zeros and one in the position which respects to the index of the word in the vocabulary. Using word embeddings instead of one-hot encoding is undoubtedly an improvement to my approach.</li><li><strong>Generate sequences out of kernel titles.</strong> The length of the sequence is a hyperparameter. I chose the sequence length equal to 3. So we give the model a tensor containing encoding for 3 words and a prediction target, which contains the index of the 4th following word.</li></ul><p>Following functions encode words into tensors:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7b881456348dafff2b64210d3f4f818/href">https://medium.com/media/f7b881456348dafff2b64210d3f4f818/href</a></iframe><p>Now let’s generate word sequences out of titles of the most popular kernels:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d718b3dc77ab6f676ae647306a5ab509/href">https://medium.com/media/d718b3dc77ab6f676ae647306a5ab509/href</a></iframe><h3>Build the Sequence Model</h3><p>The next step is building a simple <strong>LSTM model</strong>:</p><ul><li><strong>Input and output sizes</strong> of the model should be equal to the size of the vocabulary because we are trying to predict the next word for a sequence;</li><li><strong>LSTM block</strong> with 128 hidden units;</li><li>One <strong>linear layer</strong> to translate from hidden size into the output size;</li><li>Using<strong> Softmax activation</strong>.</li></ul><p>So let’s define and initialize a model with PyTorch:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb4fbbaf04c456dcd579158b1fac3c47/href">https://medium.com/media/cb4fbbaf04c456dcd579158b1fac3c47/href</a></iframe><p>Also I will need a utility function to convert the output of the model into a word:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea4e7df435e6221eec6fb9068547ed27/href">https://medium.com/media/ea4e7df435e6221eec6fb9068547ed27/href</a></iframe><h3>Train the Model</h3><p>Now the dataset and the model are ready for training. One more thing I need to do before the training is to introduce a function, which translates an index of the word in the vocabulary into tensor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aef113a88315d4c5bf38b89b7ab6302/href">https://medium.com/media/1aef113a88315d4c5bf38b89b7ab6302/href</a></iframe><p>The next step is to set up hyperparameters and the device (CPU or GPU if available):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d21b6d3ffbdcff3c6a14b1cbea4b3c0/href">https://medium.com/media/0d21b6d3ffbdcff3c6a14b1cbea4b3c0/href</a></iframe><p>Define the model training procedure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76eed0c9a52a7513c4a497be0b8343c3/href">https://medium.com/media/76eed0c9a52a7513c4a497be0b8343c3/href</a></iframe><p>Now everything is ready for the training itself:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2604e3a8b35ab84a6c185b41ddecf1bb/href">https://medium.com/media/2604e3a8b35ab84a6c185b41ddecf1bb/href</a></iframe><p>As a result of the training, we should see how the loss is decreasing over the number of epochs like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*qQ9jbzIjziAlcR_fZyYavA.png" /><figcaption>Training loss decreases over the number of epochs</figcaption></figure><h3>Sample Kernel Titles from the Model</h3><p>Here comes the most exciting part. Now we can use our trained model to generate new kernel titles! All we need to do is to write a simple sampling procedure:</p><ol><li>Introduce the <strong>maximum number of words</strong> in the title (10 for example);</li><li>Pass zero tensors to the model as the <strong>initial word and hidden state</strong>;</li><li>Repeat following steps until the end of the title symbol is sampled or the number of maximum words in title exceeded:</li></ol><ul><li>Use the probabilities from the output of the model to <strong>get the next word for a sequence</strong>;</li><li><strong>Pass sampled word as a next input</strong> for the model.</li></ul><p>So let’s define the sampling function and sample some titles from the model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7aa22e68f0840462d601873ce604991c/href">https://medium.com/media/7aa22e68f0840462d601873ce604991c/href</a></iframe><h3>Conclusion</h3><p>In this small project:</p><ul><li>I loaded and preprocessed real text data.</li><li>I created a word-based sequence model, which can be used to generate new kernel titles.</li></ul><p>You can see that the model doesn’t generate something that makes sense, but there are still some funny results like these:</p><ul><li>wealth bowl datamining</li><li>supplement approved databases</li><li>plane ignore population competition</li><li>projecting superfood prescribing survey</li><li>dinner lesson web screening</li><li>elasticnet playground</li></ul><p>Such things happen when models crush into <strong>real-life data</strong>. They contain abbreviations, nicknames, words in different languages, misspelled words, and a lot more. Of course, you can improve these results by <strong>better data preprocessing</strong>. I described actions to improve the results below.</p><h3>Further Improvement</h3><p>Though I managed to get some exciting results, there is a lot what I could do to improve:</p><ul><li><strong>Better data cleaning</strong>: many titles should be removed from the analysis as they are not in English or they’re just can’t be used (for example ‘kernel123’).</li><li><strong>Auto-correction of misspelled words</strong>: titles can be preprocessed with automatic correction of misspelled words (for example, consider <a href="https://facelessuser.github.io/pyspelling/">PySpell package</a>). This procedure takes ages to run. However, this is still an option since data preprocessing happens just one time before training.</li><li><strong>Hyperparameter tuning</strong>: I suppose that learning rate and sequence length can be tuned to achieve even better results.</li><li><strong>Use </strong><a href="https://hackernoon.com/word-embeddings-in-nlp-and-its-applications-fab15eaf7430"><strong>word embeddings</strong></a><strong> instead of one-hot encoding</strong> for words.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=957541aff48f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/generating-titles-for-kaggle-kernels-with-lstm-957541aff48f">Generating Titles for Kaggle Kernels with LSTM</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[Data Augmentation for Deep Learning]]></title>
            <link>https://medium.com/data-science/data-augmentation-for-deep-learning-4fe21d1a4eb9?source=rss-9f0981e41a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fe21d1a4eb9</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-augmentation]]></category>
            <dc:creator><![CDATA[Alexandra Deis]]></dc:creator>
            <pubDate>Sat, 10 Aug 2019 17:34:34 GMT</pubDate>
            <atom:updated>2019-08-10T17:34:34.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3oYqVUENu3l24_QeplUWQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@rawpixel?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">rawpixel.com</a> from <a href="https://www.pexels.com/photo/assorted-plastic-figures-1619844/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h4>Overview of popular augmentation packages and PyTorch examples</h4><p>Having a large dataset is crucial for the performance of the deep learning model. However, we can improve the performance of the model by <a href="https://bair.berkeley.edu/blog/2019/06/07/data_aug/">augmenting the data we already have</a>. Deep learning frameworks usually have built-in data augmentation utilities, but those can be inefficient or lacking some required functionality.</p><p>In this article, I would like to make an overview of most popular image augmentation packages, designed specifically for machine learning, and demonstrate how to use these packages with <a href="https://pytorch.org/">PyTorch</a> framework.</p><p>For each image augmentation package, I cover transforming images with binary masks and bounding boxes, pipelining transformations and making transformations work with PyTorch. I am using the following demo image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yr_-0TInLDGJq7oDuy_iPQ.png" /><figcaption>Demo image</figcaption></figure><p>The full code for this article is provided <a href="https://github.com/Lexie88rus/augmentation-packages-overview/blob/master/data-augmentation-packages-overview.ipynb">in this Jupyter notebook</a>.</p><h3>imgaug package</h3><p><a href="https://github.com/aleju/imgaug"><strong>imgaug</strong></a> is a powerful package for image augmentation. It contains:</p><ul><li>Over 60 image augmenters and augmentation techniques (affine transformations, perspective transformations, contrast changes, gaussian noise, dropout of regions, hue/saturation changes, cropping/padding, blurring);</li><li>Functionality to augment images with segmentation masks, bounding boxes, key points, and heatmaps. This functionality makes it very easy to apply the package to the dataset containing images for segmentation and object detection problems;</li><li>Complex augmentation pipelines;</li><li>Many helper functions for augmentation visualization, conversion, and more.</li></ul><p>The full documentation for <strong>imgaug </strong>package is provided<strong> </strong><a href="https://imgaug.readthedocs.io/en/latest/index.html">here</a>.</p><h4>Simple Augmentations</h4><p>Augmenting an image with <strong>imgaug</strong> package is as simple as this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72aedc613617f265f0b7563b09b1843b/href">https://medium.com/media/72aedc613617f265f0b7563b09b1843b/href</a></iframe><p>These are several examples of images augmented with imgaug package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7udw5GZHwVo6u-V0lzglvQ.png" /><figcaption>Demonstration of sample augmentations: rotation, gaussian noise, crop, hue and saturation adjustment, elastic transform, coarse dropout</figcaption></figure><p>Imgaug helps to deal with <strong>images with segmentation masks</strong>. To train a deep learning model we have to augment the image and the mask in the same manner. Here is an example of transforming an image with binary segmentation mask:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70b1acc80bf8e7791abc0516c4a73a0e/href">https://medium.com/media/70b1acc80bf8e7791abc0516c4a73a0e/href</a></iframe><p>The following code helps to visualize the augmented image and augmented mask:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36cba1beef3075d16efe60fd9e94c89e/href">https://medium.com/media/36cba1beef3075d16efe60fd9e94c89e/href</a></iframe><p>The image below is an example of an augmented image with binary segmentation mask:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYcg89p1V6JYRTlM3H-Oeg.png" /><figcaption>The result of augmentation of an image with a mask</figcaption></figure><p>Imgaug package is also helpful when applying transformations to images with bounding boxes. The sample code for augmenting an image with bounding box:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b13b5662468e6e5b47ec0f5db651fb87/href">https://medium.com/media/b13b5662468e6e5b47ec0f5db651fb87/href</a></iframe><p>The following code sample may be used to visualize the result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9990937859e5c3f424e338fba7998bd/href">https://medium.com/media/e9990937859e5c3f424e338fba7998bd/href</a></iframe><p>The image below demonstrates how the augmented image and bounding box look like compared to the original ones:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3r1OLTcKNhbUthT7RWPvlw.png" /><figcaption>The result of augmentation of an image with a bounding box</figcaption></figure><p>The augmented bounding box from the example looks nice, but in some cases, augmentation of bounding boxes doesn’t work with rotated images. Here is an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ek9ziemYjxTh7PsPcv4s4Q.png" /><figcaption>The example of augmented bounding box for rotated image</figcaption></figure><h4>Pipelining Augmentations</h4><p>With the <strong>imgaug</strong> package, we can compose a complex pipeline of image augmentations. Augmentations from the pipeline are applied to each image sequentially, but we can set up:</p><ol><li>The probability the augmentation is applied to an image. We can use this to apply, for example, horizontal flip to just 50% of the images.</li><li>Apply only a subset of augmenters to an image. For example, apply 0 to 5 of augmenters from the list. This functionality helps to speed up data generation.</li><li>Apply augmentations in random order.</li></ol><p>Let’s see an example of a complex augmentation pipeline:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96675aa8c64c8f1d998478d23e97ca5c/href">https://medium.com/media/96675aa8c64c8f1d998478d23e97ca5c/href</a></iframe><p>The following images are sampled from the pipeline defined above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FCFul_aPqWGPuoGkOJOwsA.png" /><figcaption>Examples of images sampled from the augmentation pipeline</figcaption></figure><h4>Using imgaug with PyTorch</h4><p>The following code sample demonstrates how <strong>imgaug</strong> augmentations can be used in PyTorch dataset for generation of new augmented images:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e721ecd395f6badf97b30a402e2d3f4a/href">https://medium.com/media/e721ecd395f6badf97b30a402e2d3f4a/href</a></iframe><h3>Albumentations package</h3><p><a href="https://github.com/albu/albumentations"><strong>Albumentations</strong></a> package is written based on numpy, OpenCV, and imgaug. It is a very popular package written by Kaggle masters and used widely in Kaggle competitions. Moreover, this package is very efficient. You may find the benchmarking results <a href="https://github.com/albu/albumentations#benchmarking-results">here</a> and the full documentation for this package <a href="https://albumentations.readthedocs.io/en/latest/">here</a>.</p><p>Albumetations package is capable of:</p><ul><li>Over 60 pixel-level and spatial-level transformations;</li><li>Transforming images with masks, bounding boxes, and keypoints;</li><li>Organizing augmentations into pipelines;</li><li>PyTorch integration.</li></ul><h4>Simple Augmentations</h4><p>Augmentations from the <strong>Albumentations</strong> package are applied to the images as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7027287c036a6a1b077f765909c655e5/href">https://medium.com/media/7027287c036a6a1b077f765909c655e5/href</a></iframe><p>Several examples of images produced by augmenters from <strong>Albumentations</strong> package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1c3jOYHYg-_D0PeqaARFw.png" /><figcaption>Demonstration of sample augmentations: gaussian noise, elastic transform, random brightness and contrast, random gamma, <a href="https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE">CLAHE</a>, blur</figcaption></figure><p><strong>Albumentations</strong> package can as well be applied to images with masks. Here is an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84f1b52b60b1cb83535b711ea64a7c5f/href">https://medium.com/media/84f1b52b60b1cb83535b711ea64a7c5f/href</a></iframe><p>The image below shows the augmented image with binary segmentation mask:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49uqFAbOdTvkMexMXtEhkw.png" /><figcaption>The result of augmentation of an image with a mask</figcaption></figure><p><strong>Albumentations</strong> package also provides the functionality to transform images with bounding boxes. Here is a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3891284857bef6766e793428639c4ad/href">https://medium.com/media/a3891284857bef6766e793428639c4ad/href</a></iframe><p>The following code sample demonstrates how to visualize the result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/652954d68ae0601f2cab05a41650a5d5/href">https://medium.com/media/652954d68ae0601f2cab05a41650a5d5/href</a></iframe><p>This is an example of an augmented image with bounding box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CaO5qfuKjJEIv3OyKkYXAA.png" /><figcaption>The result of augmentation of an image with a bounding box</figcaption></figure><h4>Pipelining Augmentations</h4><p>Albumentations package takes the best from numpy, OpenCV, and imgaug. That is why pipelining in <strong>Albumentations</strong> package is similar to pipelining in imgaug. Here is an example of a pipeline inspired by <a href="https://www.kaggle.com/meaninglesslives/unet-plus-plus-with-efficientnet-encoder">this Kaggle kernel</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa87e487998bac64dafdd9b54b7341ac/href">https://medium.com/media/fa87e487998bac64dafdd9b54b7341ac/href</a></iframe><p>The following images are sampled from the pipeline defined above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4dt5CnI7jGsiabowriRBw.png" /><figcaption>Examples of images sampled from the augmentation pipeline</figcaption></figure><h4>PyTorch Integration</h4><p>When using PyTorch you can effortlessly migrate from <a href="https://pytorch.org/docs/stable/torchvision/index.html">torchvision</a> to <strong>Albumentations</strong>, because this package provides specialized utilities to use with PyTorch. Migrating to <strong>Albumentations </strong>helps to speed up the data generation part and train deep learning models faster. See a detailed tutorial on migration from torchvision to <strong>Albumentations </strong><a href="https://github.com/albu/albumentations/blob/master/notebooks/migrating_from_torchvision_to_albumentations.ipynb">here</a>.</p><p>PyTorch integration example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5ca36c4657118143da01acab4959008/href">https://medium.com/media/f5ca36c4657118143da01acab4959008/href</a></iframe><h3>Augmentor</h3><p><a href="https://github.com/mdbloice/Augmentor"><strong>Augmentor</strong></a><strong> </strong>package contains less possible augmentations than previous packages described in this article, but it has its outstanding features like <a href="https://github.com/mdbloice/Augmentor#size-preserving-rotations">size-preserving rotations</a>, <a href="https://github.com/mdbloice/Augmentor#size-preserving-shearing">size-preserving shearing</a>, and <a href="https://github.com/mdbloice/Augmentor#cropping">cropping</a>, which is more suitable for machine learning.</p><p><strong>Augmentor </strong>package also allows to compose augmentation pipelines and use them with PyTorch. You can find the full documentation for <strong>Augmentor </strong>package <a href="https://augmentor.readthedocs.io/en/master/">here</a>.</p><h4>Simple Augmentations</h4><p>The following example combines a simple <strong>Augmentor</strong> pipeline applied to an image with mask:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88120fadbc70795dd61b8143bf70274b/href">https://medium.com/media/88120fadbc70795dd61b8143bf70274b/href</a></iframe><p>These images are produced with the help of the code above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ECWqfS56tk_EnLAvo604g.png" /><figcaption>The result of augmentation of an image with a mask</figcaption></figure><h4>Using Augmentor with PyTorch</h4><p>There are some <a href="https://github.com/mdbloice/Augmentor/issues/109">known issues</a> with <strong>Augmentor</strong> and PyTorch, but we can still use these libraries together.</p><p>Here is an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/495976319b0745bba91cc321f0811a5f/href">https://medium.com/media/495976319b0745bba91cc321f0811a5f/href</a></iframe><h3>Conclusion</h3><p>In this article, I covered the functionality of the most popular image augmentation packages designed specifically for machine learning. Various code samples provided in this article help to start using these packages for classification, segmentation, and object detection tasks in machine learning projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fe21d1a4eb9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-augmentation-for-deep-learning-4fe21d1a4eb9">Data Augmentation for Deep Learning</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[In-place Operations in PyTorch]]></title>
            <link>https://medium.com/data-science/in-place-operations-in-pytorch-f91d493e970e?source=rss-9f0981e41a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/f91d493e970e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Alexandra Deis]]></dc:creator>
            <pubDate>Wed, 10 Jul 2019 14:48:47 GMT</pubDate>
            <atom:updated>2019-07-10T14:48:47.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lv48q7cD2RSG3c9C5J0Xwg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@fancycrave?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Fancycrave.com </a>from <a href="https://www.pexels.com/photo/green-ram-card-collection-825262/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h4>What are they and why avoid them</h4><p>Today’s advanced deep neural networks have millions of trainable parameters (for example, see the comparison in <a href="https://arxiv.org/pdf/1905.11946.pdf">this paper</a>) and trying to train them on free GPU’s like Kaggle or Google Colab often leads to running out of memory on GPU. There are several simple ways to reduce the GPU memory occupied by the model, for example:</p><ul><li>Consider changing the architecture of the model or using the type of model with fewer trainable parameters (for example, choose <a href="https://arxiv.org/pdf/1608.06993.pdf">DenseNet-121 over DenseNet-169</a>). This approach can affect the model’s performance metrics.</li><li>Reduce the batch size or manually set the number of data loader workers. In this case, it takes longer for the model to train.</li></ul><p>Using in-place operations in neural networks may help to avoid the downsides of approaches mentioned above while saving some GPU memory. However, it is not recommended to use in-place operations for several reasons.</p><p>In this article I would like to:</p><ul><li>Describe what are the in-place operations and demonstrate how they might help to save the GPU memory.</li><li>Tell why we should avoid the in-place operations or use them with great caution.</li></ul><h3>In-place Operations</h3><blockquote>“In-place operation is an operation that directly changes the content of a given linear algebra, vector, matrices (Tensor) without making a copy.” — The definition is taken from <a href="https://www.tutorialspoint.com/inplace-operator-in-python">this Python tutorial</a>.</blockquote><p>According to the definition, in-place operations don’t make a copy of the input. That is why they can help to reduce memory usage when operating with high-dimensional data.</p><p>I want to demonstrate how in-place operations help to consume less GPU memory. To do this, I am going to measure allocated memory for both <a href="https://pytorch.org/docs/stable/nn.html#relu">out-of-place ReLU and in-place ReLU from PyTorch</a>, with this simple function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5510b1f84619b9fc59f716ebf603c112/href">https://medium.com/media/5510b1f84619b9fc59f716ebf603c112/href</a></iframe><p>Call the function to measure the allocated memory for the out-of-place ReLU:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a6000c4a0b54ecbdb0bb83b3c29a3f2/href">https://medium.com/media/7a6000c4a0b54ecbdb0bb83b3c29a3f2/href</a></iframe><p>I receive the output like this:</p><pre>Allocated memory: 382.0<br>Allocated max memory: 382.0</pre><p>Then call the in-place ReLU as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c1cf09ac6185b08d1abe1b151d6e42b/href">https://medium.com/media/2c1cf09ac6185b08d1abe1b151d6e42b/href</a></iframe><p>The output I receive is like:</p><pre>Allocated memory: 0.0<br>Allocated max memory: 0.0</pre><p>Looks like using in-place operations helps us to save some GPU memory. <strong>However, we should be extremely cautious when using in-place operations and check twice.</strong> In the next section, I am going to tell you why.</p><h3>Downsides of In-place Operations</h3><p>The major downside of in-place operations is the fact that <strong>they might overwrite values required to compute gradients,</strong> which means breaking the training procedure of the model. That is what <a href="https://pytorch.org/docs/stable/notes/autograd.html#in-place-operations-with-autograd">the official PyTorch autograd documentation</a> says:</p><blockquote>Supporting in-place operations in autograd is a hard matter, and<strong> we discourage their use in most cases</strong>. Autograd’s aggressive buffer freeing and reuse makes it very efficient and there are very few occasions when in-place operations actually lower memory usage by any significant amount. Unless you’re operating under heavy memory pressure, you might never need to use them.</blockquote><blockquote>There are two main reasons that limit the applicability of in-place operations:</blockquote><blockquote>1. In-place operations can potentially overwrite values required to compute gradients.</blockquote><blockquote>2. Every in-place operation actually requires the implementation to rewrite the computational graph. Out-of-place versions simply allocate new objects and keep references to the old graph, while in-place operations, require changing the creator of all inputs to the Function representing this operation.</blockquote><p>The other reason for being careful with in-place operations is that their implementation is exceptionally tricky. That is why I would recommend using PyTorch standard in-place operations (like in-place ReLU above) instead of implementing one manually.</p><p>Let’s see an example of <a href="https://arxiv.org/pdf/1606.08415.pdf">SiLU</a> (or Swish-1) activation function. This is the out-of-place implementation of SiLU:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59ebe406b0254346938a3edd25b3747d/href">https://medium.com/media/59ebe406b0254346938a3edd25b3747d/href</a></iframe><p>Let’s try to implement in-place SiLU using torch.<a href="https://en.wikipedia.org/wiki/Sigmoid_function">sigmoid</a>_ in-place function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/094eacf457289cecb96f5e3b7ff67a21/href">https://medium.com/media/094eacf457289cecb96f5e3b7ff67a21/href</a></iframe><p>The code above <strong>incorrectly implements</strong> the in-place SiLU. We can make sure of that bu merely comparing the values returned by both functions. Actually, the function silu_inplace_1 returns sigmoid(input) * sigmoid(input)! The working example of the in-place implementation of SiLU using torch.sigmoid_ would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/684d0cf2f7d8804ca324d1e2f997c488/href">https://medium.com/media/684d0cf2f7d8804ca324d1e2f997c488/href</a></iframe><p>This small example demonstrates why we should be cautious and check twice when using in-place operations.</p><h3>Conclusion</h3><p>In this article:</p><ul><li>I described the in-place operations and their purpose. Demonstrated how in-place operations help to consume less GPU memory.</li><li>I described the <strong>significant downsides of in-place operations</strong>. One should be very careful about using them and check the result twice.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f91d493e970e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/in-place-operations-in-pytorch-f91d493e970e">In-place Operations in PyTorch</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[Extending PyTorch with Custom Activation Functions]]></title>
            <link>https://medium.com/data-science/extending-pytorch-with-custom-activation-functions-2d8b065ef2fa?source=rss-9f0981e41a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d8b065ef2fa</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alexandra Deis]]></dc:creator>
            <pubDate>Thu, 27 Jun 2019 23:11:54 GMT</pubDate>
            <atom:updated>2019-06-27T23:11:54.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zl4Isa-_9bzh476T-YwmLQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@chivozol-43727?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">chivozol </a>from <a href="https://www.pexels.com/photo/close-up-photography-of-spider-web-167259/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h4>A Tutorial for PyTorch and Deep Learning Beginners</h4><h3>Introduction</h3><p>Today deep learning is going viral and is applied to a variety of machine learning problems such as image recognition, speech recognition, machine translation, and others. There is a wide range of highly customizable neural network architectures, which can suit almost any problem when given enough data. Each neural network should be elaborated to suit the given problem well enough. You have to fine tune the hyperparameters of the network (the learning rate, dropout coefficients, weight decay, and many others) as well as the number of hidden layers, and the number of units in each layer. <strong>Choosing the right activation function for each layer is also crucial and may have a significant impact on metric scores and the training speed of the model</strong>.</p><h3>Activation Functions</h3><p><a href="https://en.wikipedia.org/wiki/Activation_function">The activation function</a> is an essential building block for every neural network. We can choose from a huge list of popular activation functions from popular Deep Learning frameworks, like <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)">ReLU</a>, <a href="https://en.wikipedia.org/wiki/Sigmoid_function">Sigmoid</a>, <a href="https://en.wikipedia.org/wiki/Hyperbolic_function">Tanh</a>, and many others.</p><p>However, to create a state of the art model, customized particularly for your task, you may need to use a custom activation function, which is absent in Deep Learning framework you are using. Activation functions can be roughly classified into the following groups by complexity:</p><ol><li><strong>Simple activation functions</strong> like <a href="https://arxiv.org/pdf/1710.09967.pdf">SiLU</a>, <a href="https://arxiv.org/pdf/1710.09967.pdf">Inverse Square Root Unit (ISRU)</a>. You can quickly implement these functions using any Deep Learning framework.</li><li><strong>Activation functions with trainable parameters</strong> like <a href="https://arxiv.org/pdf/1602.01321.pdf">Soft Exponential</a> activation or <a href="https://arxiv.org/pdf/1512.07030.pdf">S-shaped Rectified Linear Unit (SReLU)</a>.</li><li><strong>Activation functions, which are not differentiable at some points</strong> and require the custom implementation of the backward step, for example, <a href="https://arxiv.org/pdf/1709.04054.pdf">Bipolar Rectified Linear Unit (BReLU)</a>.</li></ol><p>In this tutorial, I cover the implementation and demo examples for all of these types of functions with <a href="https://pytorch.org/">PyTorch</a> framework. You can find all the code for this article <a href="https://github.com/Lexie88rus/Activation-functions-examples-pytorch/blob/master/custom_activations_example.py">on GitHub</a>.</p><h3>Setting Up</h3><p>To go through the examples of the implementation of activation functions, you would require:</p><ul><li>To install <a href="https://pytorch.org/get-started/locally/">PyTorch</a>,</li><li>To add the necessary imports to your script,</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70a2c8741f53441da2bea78c0f559f05/href">https://medium.com/media/70a2c8741f53441da2bea78c0f559f05/href</a></iframe><ul><li>To prepare a dataset for the demonstration. We will use the well known <a href="https://www.kaggle.com/zalando-research/fashionmnist">Fashion MNIST dataset</a>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa368b5877dfe47d0ce370141d77f6fe/href">https://medium.com/media/aa368b5877dfe47d0ce370141d77f6fe/href</a></iframe><p>The last thing is to set up a sample function, which runs the model training process and prints out the training loss for each epoch:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b34aaaf2d1f6379d507cb432bca22cd/href">https://medium.com/media/9b34aaaf2d1f6379d507cb432bca22cd/href</a></iframe><p>Now everything is ready for the creation of models with custom activation functions.</p><h3>Implementing Simple Activation Functions</h3><p>The most simple common activation functions</p><ul><li><strong>are differentiable</strong> and don’t need the manual implementation of the backward step,</li><li><strong>don’t have any trainable parameters</strong>. All their parameters should be set in advance.</li></ul><p>One of the examples of such simple functions is <a href="https://arxiv.org/pdf/1606.08415.pdf">Sigmoid Linear Unit or just SiLU</a>, also known as Swish-1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnhq9rjk10wnZIVLlWYQqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTyFlvabpQFqe-rASHc1Qg.png" /><figcaption>SiLU</figcaption></figure><p>Such a simple activation function can be implemented just as easy as a Python function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9188078445ff9b24322e639e71cf5b73/href">https://medium.com/media/9188078445ff9b24322e639e71cf5b73/href</a></iframe><p>So now SiLU can be used in models created with nn.Sequential:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/426a7dd6fbd2bba17b74d51845ffbeee/href">https://medium.com/media/426a7dd6fbd2bba17b74d51845ffbeee/href</a></iframe><p>Or in a simple model, which extends nn.Module class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3addde6f4ff960def4065ed27e5a3990/href">https://medium.com/media/3addde6f4ff960def4065ed27e5a3990/href</a></iframe><h3>Implementing Activation Function with Trainable Parameters</h3><p>There are lots of activation functions with parameters, which can be trained with gradient descent while training the model. A great example for one of these is <a href="https://arxiv.org/pdf/1602.01321.pdf">Soft Exponential</a> function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViIYhQB334EMHeUThAhhLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBntY9vMO6NzGVtcqfsvnQ.png" /><figcaption>Soft Exponential</figcaption></figure><p>To implement an activation function with trainable parameters we have to:</p><ul><li>derive a class from nn.Module and make the parameter one of its members,</li><li>wrap the parameter as a PyTorch Parameter and set requiresGrad attribute to True.</li></ul><p>Here is an example for Soft Exponential:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e98340caf2b8cca7c0384a33725bcba2/href">https://medium.com/media/e98340caf2b8cca7c0384a33725bcba2/href</a></iframe><p>And now we can use Soft Exponential in our models as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cb47833cf01ab62fbc98adcfa3a3365/href">https://medium.com/media/2cb47833cf01ab62fbc98adcfa3a3365/href</a></iframe><h3>Implementing Activation Function with Custom Backward Step</h3><p>The perfect example of an activation function, which needs implementation of a custom backward step is <a href="https://arxiv.org/pdf/1709.04054.pdf">BReLU</a> (Bipolar Rectified Linear Unit):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3SrcvFCi_VjIz3nFahrFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_7dBSNKS92XzwBBfFVztQ.png" /><figcaption>BReLU</figcaption></figure><p>This function is not differentiable at 0, so automatic gradient computation might fail. That’s why we should provide a custom backward step to ensure stable computation.</p><p>To impement custom activation function with backward step we should:</p><ul><li>create a class which, inherits Function from torch.autograd,</li><li>override static forward and backward methods. Forward method just applies the function to the input. Backward method computes the gradient of the loss function with respect to the input given the gradient of the loss function with respect to the output.</li></ul><p>Let’s see an example for BReLU:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ccdd419febe5ece95fa028dd46f73a6/href">https://medium.com/media/3ccdd419febe5ece95fa028dd46f73a6/href</a></iframe><p>We can now use BReLU in our models as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9503452c46418b9f8ad49d07e38b51a5/href">https://medium.com/media/9503452c46418b9f8ad49d07e38b51a5/href</a></iframe><h3>Conclusion</h3><p>In this tutorial I covered:</p><ul><li>How to create a <strong>simple custom activation function</strong> with PyTorch,</li><li>How to create an<strong> activation function with trainable parameters</strong>, which can be trained using gradient descent,</li><li>How to create an <strong>activation function with a custom backward step</strong>.</li></ul><p>All code from this tutorial is available on <a href="https://github.com/Lexie88rus/Activation-functions-examples-pytorch/blob/master/custom_activations_example.py">GitHub</a>. Other examples of implemented custom activation functions for <a href="https://pytorch.org/">PyTorch</a> and <a href="https://keras.io/">Keras</a> you can find in <a href="https://github.com/digantamisra98/Echo/tree/Dev-adeis">this GitHub repository</a>.</p><h3>Improvement</h3><p>While building many custom activation functions, I noticed that they often consume much more GPU memory. Creation of <strong>in place implementations</strong> of custom activations using PyTorch in place methods improves this situation.</p><h3>Additional References</h3><p>Here are some links to the additional resources and further reading:</p><ol><li><a href="https://en.wikipedia.org/wiki/Activation_function">Activation functions wiki page</a></li><li><a href="https://pytorch.org/docs/master/notes/extending.html">Tutorial on extending PyTorch</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d8b065ef2fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/extending-pytorch-with-custom-activation-functions-2d8b065ef2fa">Extending PyTorch with Custom Activation Functions</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[Music Service Data Analysis with Spark]]></title>
            <link>https://medium.com/@astakhova.aleksandra/music-service-data-analysis-with-spark-a697bdcd79c?source=rss-9f0981e41a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/a697bdcd79c</guid>
            <category><![CDATA[data-sceince]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-exploration]]></category>
            <dc:creator><![CDATA[Alexandra Deis]]></dc:creator>
            <pubDate>Mon, 22 Apr 2019 06:33:39 GMT</pubDate>
            <atom:updated>2019-04-22T06:33:39.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-K4bpH1IXEua6hcshfESw.jpeg" /><figcaption>Photoby <a href="https://unsplash.com/photos/hpjSkU2UYSU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Carlos Muza</a> on <a href="https://unsplash.com/search/photos/big-data?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Data Science Project Walkthrough</h4><p>Every completed data science project needs to be wrapped up in a report or a blog post. I tried to make an example of a report on a project about music service data analysis so it can be used by others as an example. I provided all the code and other resources for this article in <a href="https://github.com/Lexie88rus/Udacity-DSND-Capstone-Data-Analysis-with-Spark">my GitHub</a>.</p><h3>Definition</h3><h4>Project Overview</h4><p>Predicting churn rates is a challenging and common problem that data scientists and analysts regularly encounter in any customer-facing business. It is crucial for businesses to identify customers who are about to churn and take action to retain them before it happens.</p><p>The goal of this project was to help Sparkify music service retain their customers. In this project, I analyzed Sparkify data, built a machine learning model to predict churn and developed a web application to demonstrate the results.</p><h4>Problem Statement</h4><p>As the goal of the project is to help to retain the customers, the main task of the project is to make a prediction, whether the customer is about to churn. Such a prediction can be made for each customer by a binary classifier model. The following tasks should be completed to create the model:</p><ul><li>Analyze and preprocess the data to extract features for each customer;</li><li>Train classifier to predict customer churn;</li><li>Evaluate the classifier concerning the chosen metric;</li><li>Build a web application to demonstrate the results.</li></ul><h4>Metrics</h4><p>The initial dataset analysis shows us that the dataset is imbalanced (see section Input Data): there are more than 3 times fewer users, who churned, than other users. That is why I can’t use accuracy (which is the number of correct predictions divided by the total number of predictions) as a metric to evaluate the resulting model.</p><p>In our case, we should care about both types of errors: false negatives and false positives because in case of false negative we can miss the customer who is going to churn and lose the customer and in case of false positive we can have unnecessary costs on retaining the customer who was not going to churn. That is why as a metric to evaluate the model I chose F1 score because it equally considers both the precision and the recall.</p><h3>Analysis</h3><h4>Input Data</h4><p>Input dataset contains the following information on Sparkify service events:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9eWDFIrU_5L8TwSZTtSINA.png" /><figcaption>Schema of the Input Data</figcaption></figure><p>For data exploration I will use a small subset of the full dataset.</p><h4>Data Exploration</h4><p>First of all, I analyzed the number of missing values in each column of the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exu33a_lzPBSBTL3G2qCXQ.png" /><figcaption><em>The number of missing values per column</em></figcaption></figure><p>The figure above shows the number of empty values per column. We see that there are equal numbers of missing values for different sets of columns. Looking closer at the rows of the dataset we also see that:</p><ul><li>There are 8346 rows where userId is an empty string. In these rows other columns are also missing. These events correspond to the activity of the users, who are not logged in. These records can’t help us to predict customer churn, because we can’t identify the customer, that is why we should remove these rows from the analysis.</li><li>Columns song, artist and length aren’t missing only for rows where page value is “NextSong”.</li></ul><p>Further analysis demonstrates that only column userId has empty string values. As mentioned above rows with empty userId should be removed during data cleaning stage.</p><p>In all further exploration I assume that rows with empty userId are already removed from the analysis.</p><p>The figure below shows the values of categorical columns auth, gender, level, method, and page for events on the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rerhHFcW15L4RB5H0BzDjA.png" /><figcaption>Statistics for the number of events for categorical columns</figcaption></figure><ol><li>The number of events for female users is slightly higher than for male users. However, this may be true only for our small dataset which is the subset of the full dataset.</li><li>The number of events for paid level accounts is approximately 4 times greater than the number of events for free level accounts.</li><li>The most frequent action is ‘NextSong’ which is not surprising for a music streaming service.</li></ol><p>The figure below illustrates the number of female and male users, paid and free accounts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*_5s3i7kK9fvFsrbWnLgSLQ.png" /><figcaption>Statistics for users’ level and gender</figcaption></figure><ol><li>There are slightly more male users in the mini dataset. However, comparing with the previous plot where we saw more events for female users, so female users more actively use the service than male users.</li><li>There are slightly more free accounts in the mini dataset, but there are more events for paid users. We can conclude that users with paid accounts are more active using the service.</li></ol><h4>Definition of Churn</h4><p>The next step is to define churn given the data from the input dataset. Among the values in the page column, there is “Cancellation Confirmation”, which means that the user has confirmed cancellation of his subscription. This event marks that the user churned.</p><p>To complete the data exploration and to analyze the behavior of different types of users the data is processed in the following way:</p><ol><li>Created new column “churn”;</li><li>“churn” value is set to 1 for rows where “page” value is “Cancellation Confirmation,” otherwise set “churn” to 0;</li><li>“churn” value is set to 1 for all rows for a user, who has rows where “churn” is equal to 1. As a result, “churn” value is equal to 1 for all events of all users who canceled their subscription.</li></ol><p>After the churn is defined, it is possible to analyze the behavior of the users who churned versus the users who didn’t cancel their subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q91_C6EJ-EbjjTo6xFTp1Q.png" /><figcaption>Number of events for users who churned vs other users</figcaption></figure><p>The figure above shows the number of events for users who churned versus other users concerning different categorical columns. We can make the following conclusions:</p><ul><li>Even though there are more events for female than male users, the number of events for churned male users is higher than for churned female users. That is why we can suppose that females who churned are less active service users than those who stay with their subscription.</li><li>For all other categorical features, we see that there are more events for specific value there are in the dataset, the more events for this specific value correspond to churned users. So, we can’t make any conclusion out of that regarding the behavior of churned users.</li></ul><p>Figure below contains an exploration of the number of male and female users, and the number of paid and free accounts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*dDv51mwkrtDOXEb_k3hMSw.png" /></figure><ul><li>There are fewer female users than male users and also a fewer number of female users who churned.</li><li>Percentage of male users who churned is higher than the percentage of female users, who churned.</li><li>Percentage of paid accounts related to users who churned is almost the same as the percentage of free accounts related to users who churned.</li></ul><p>Data exploration conclusions are as follows:</p><ul><li>From the exploratory analysis above we learn that the behavior of female users is different compared to the behavior of male users. Female users are more active because there are fewer female users, but there are more events related to female users. Percentage of male users who churned is higher than the percentage of female users, who churned, so male users may be more likely to churn.</li><li>Female users who churned have different behavior rather than other female users: female users who churned are less active.</li></ul><h3>Data Preprocessing</h3><p>Before the implementation of machine learning methods, the initial dataset requires preprocessing:</p><ul><li>Remove the rows with empty userId values,</li><li>Define churn,</li><li>Create a new dataset, which contains features extracted for each user labeled with churn values.</li></ul><p>To predict whether the user is going to churn for each user the following features should be extracted for each user:</p><ul><li><strong>gender</strong>, because data exploration showed that male and female users may have different behavior;</li><li><strong>last level </strong>(paid or free), because data exploration showed that paid level users are more active and also may have different behavior;</li><li><strong>average events per day </strong>to see how active the user is in general;</li><li><strong>average songs per day </strong>to see how active the user is in listening to the music;</li><li><strong>number of thumbs up</strong>to see how satisfied the user is with the content of the service;</li><li><strong>a number of thumbs down </strong>to see how satisfied the user is with the content of the service;</li><li><strong>days since the date of the first event </strong>to see how long the user has already been using the service;</li><li><strong>last location </strong>(postal abbreviation of the state): the popularity of the service may vary depending on advertising in different regions;</li><li><strong>number of add friend events</strong>: perhaps the user is less likely to churn if his friends also subscribe to the service.</li></ul><p>The preprocessing was done by PySpark. There is a difference in the distributions of the new features between customers who churned and the others (see the figure below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ilxJ9a8vu0ttPZFu6EAqg.png" /><figcaption>Distribution of new features (1 — users who churned, 2 — users who stayed)</figcaption></figure><ul><li>The mean values of the average number of events and songs per day are lower for the customers who churned.</li><li>The mean values of thumbs up, thumbs down and add friend events are lower for the customers who churned.</li></ul><p>It may mean that customers who churned are less active users of the service.</p><h3>Implementation</h3><p>The input datasets contain massive amounts of data, which can’t be processed on a single machine. That is why I will use Spark clusters to analyze data and predict customer churn. I will use PySpark and SparkML libraries to implement the solution.</p><p>The implementation of the project consists of two parts:</p><ul><li>Application of machine learning methods to predict churn. This part involves creation of machine learning pipelines, evaluation and tuning of the approach.</li><li>Development of a web application to demonstrate the resulting model.</li></ul><h4>Machine Learning Pipelines</h4><p>Construction of a pipeline is required to apply machine learning methods for churn prediction. SparkML library was used to apply machine learning. Machine learning pipeline for our task consists of the following steps (see the figure below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*KhptKYSFJW2pFmxPYw2Y0Q.png" /><figcaption>Machine learning pipeline steps</figcaption></figure><ol><li>Split dataset into train, test, and validation.</li><li>Create dummy columns out of categorical columns ‘gender’, ‘last_level’, and ‘last_state’. When using pyspark machine learning library sparkml, this step actually consists of two parts: indexing categorical column and encoding it.</li><li>Create a feature vector.</li><li>Train the classifier.</li></ol><p>There are several classification algorithms from SparkML, which I tried to use for the customer churn prediction:</p><ul><li>Random Forest Classifier;</li><li>Logistic Regression Classifier;</li><li>Gradient-Boosted Tree Classifier;</li><li>Naïve Bayes Classifier.</li></ul><p>See the evaluation of metrics of models based on those algorithms in the Refinement section.</p><h4>Web Application</h4><p>The goal of the web application is to demonstrate the prediction of customer churn. The web application allows the user to enter the information about the customer and then tells whether the customer is about to churn based on this information. The web application is implemented with:</p><ul><li>Flask running the back-end,</li><li>Bootstrap controls of front-end.</li></ul><p>The web application consists of the following parts:</p><ul><li>Python script which builds the machine learning model. This script accepts the path to the dataset and the path where the resulting model should be saved as parameters.</li><li>The machine learning model. The application loads the model and uses it to make predictions.</li><li>Python script, which uses Flask and runs the logic of the application and renders web pages. The script loads the model on start and applies it to make predictions out of the data provided by the user on the web page.</li><li>Web page of application web pages. Pages use bootstrap controls.</li></ul><h4>Refinement</h4><p>The F1 score of pipelines for the initial approach is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*59Hv_NtjEQ73ujjZZvsjrQ.png" /><figcaption>The F1 score for the initial approach</figcaption></figure><p>To increase those scores, we can take the following refinement measures:</p><ul><li>Add preprocessing to the pipeline: add scaling or normalization to preprocess numeric features.</li><li>Refine column values with the location of the user (last state): introduce categorical value ‘other’ for rare states.</li></ul><p>The table below shows that preprocessing increases slightly F1 scores of Random Forest and Gradient-boosted Tree algorithms and dramatically increases scores of Naïve Bayes algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEcIEexxalCt-D_rH9t0bg.png" /><figcaption>The F1 score with preprocessing</figcaption></figure><p>There are over 45 distinct values for the state in the initial dataset. Over 30 distinct values for last_state column remain after the preprocessing. That is why it is a common situation that the model has to predict for the unseen last_state value. In this case, the model won’t perform well unless we introduce a new value ‘OTHER’ instead of rare states. After that, the model won’t have to make predictions on unseen data anymore.</p><p>The table below shows F1 scores after refining the location feature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n13eulHbrXakXv_vHoQhBQ.png" /><figcaption>The F1 score after location refinement</figcaption></figure><p>The table below shows F1 scores after applying combination of refining approaches (normalization of features and refining of location values):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4iYsYh_A6ZAR-w8uusaYQ.png" /><figcaption>The F1 score of combined approach</figcaption></figure><p>As we see above the most effective measures for model refinement are normalization of numeric features and the additional preprocessing of location feature.</p><p>In conclusion I can say that the combination of the refinement measures taken above helped to <strong>improve the final scores by 2–3%.</strong></p><h3>Model Evaluation</h3><p>To predict customer churn there was built a machine learning pipeline which consists of:</p><ul><li>the indexers and an encoder for categorical features,</li><li>the feature assembler,</li><li>the normalizer for numeric features,</li><li>the Random Forest Classifier.</li></ul><p>The Random Forest Classifier was chosen from the set of other models because it demonstrated the best performance in terms of the F1 score (81%).</p><p>To tune parameters for the Random Forest algorithm I applied cross validation and grid search. Top F1 scores for different parameter sets are demonstrated in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYk82zgH9UrqJz27ct0NNg.png" /><figcaption>Top F1 scores for the different parameter sets for the Random Forest classifier</figcaption></figure><p>For the final model, the best hyperparameters for the Random Forest Classifier were chosen using the cross-validation approach. The best model’s scores are:</p><ul><li>82% F1 score on train dataset,</li><li>78% F1 score on the test dataset,</li><li>and 81% F1 score on the validation dataset.</li></ul><p>I can say that the resulting solution is robust because the model generalizes well to the new validation dataset. The difference between train and validation scores is about 1%.</p><h4>Justification</h4><p>The summary of the final solution:</p><ul><li>Spark (PySpark and SparkML libraries) was used to analyze data and make predictions.</li><li>The solution is based on dataset, which contains the following extracted features for each user: gender, last user level , the number of days since registration, last location, the average number of events and songs listened per day, the number of thumbs up events, the number of thumbs down events, the number of add friend action events.</li><li>Categorical features (last level, last location, gender) are transformed into dummy variables.</li><li>Numerical features are normalized. Normalization improved scores Gradient-boosted Tree Classifier because without normalization some weights update much faster than others in case of using gradient descent/ascent-based optimization. Normalization also improved scores of Naive Bayes, because this algorithm is sensitive to distances between points.</li><li>In the final model Random Forest Classifier was used to predict churn. This classifier performs best in our case because this method is good at handling categorical variables and is resistant to overfitting. The final model has about 81% F1 score on the validation dataset.</li><li>The flask web application was built to demonstrate the working model. Flask was chosen because it allows building a rapid solution in Python.</li></ul><h3>Conclusion</h3><h4>Results Summary</h4><p>The goal of the project is to help the Sparkify service to retain the customers. The solution which I proposed to reach this goal is as follows:</p><ul><li>A large part of the solution is the preprocessing of the initial data. The initial data was in terms of music service events. I transformed it into records in terms of each Sparkify customer. Feature engineering and preprocessing were required to obtain the dataset which is ready for machine learning.</li><li>The second large part of the solution is the machine learning pipeline, which predicts customer churn. I tried several classifiers and compared their F1 scores to choose the best performing solution. I also tuned the hyperparameters with the help of a grid search and cross-validation for the chosen classifier. The final F1 score of the solution is 81%.</li><li>The last part of the solution is the web application which demonstrates the churn prediction. The web application allows the user to enter the information about the customer and then identifies whether this customer is about to churn.</li><li>All parts of the solution are built in Python using Spark.</li></ul><p>The most challenging parts of this journey were the feature engineering and the refinement of the model. In feature engineering it is challenging to propose features, which on one hand will help to predict churn and will not overfit the model on the other. Trying to refine the model I tried out several techniques, but not all of them worked (for example, bucketing of continuous numerical features).</p><h4>Improvement</h4><p>It was quite a journey, but still, a lot can be done to improve the proposed solution:</p><ul><li>Introduce the different approach for the customer churn prediction. We can try to predict the churn event depending on the sequence of preceding events.</li><li>Use larger dataset for machine learning. Having more data could raise the robustness of the model.</li><li>Try model stacking to raise the accuracy of the prediction. The ensemble of different classifiers often makes a more accurate resulting model.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a697bdcd79c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get upvotes for a kernel on Kaggle?]]></title>
            <link>https://medium.com/@astakhova.aleksandra/how-to-get-upvotes-for-a-kernel-on-kaggle-2e7de8722d9d?source=rss-9f0981e41a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e7de8722d9d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Alexandra Deis]]></dc:creator>
            <pubDate>Fri, 15 Feb 2019 17:32:03 GMT</pubDate>
            <atom:updated>2019-02-15T17:32:03.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3fDiy_86uvPcoAfMIbgNQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/2xEQDxB0ss4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dlanor S</a> on <a href="https://unsplash.com/search/photos/code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>An analysis of Kaggle’s public data</h4><p>I have recently joined Kaggle and started to create public kernels. My kernels have a lot of views, but no upvotes. Fortunately, there is <a href="https://www.kaggle.com/kaggle/meta-kaggle">Meta Kaggle dataset</a>, which contains various data on competitions, users, submissions, and kernels. We can use this dataset to find out:</p><ul><li>Statistics for the number of kernels, which have votes;</li><li>How different factors affect the number of votes (for example, characteristics of the author, source dataset etc.)?</li><li>And finally, make the recommendations on how to make the kernel useful so other Kaggle users would cast upvotes.</li></ul><p>In this article, I will just share my findings, the full code for the analysis you can find on <a href="https://github.com/Lexie88rus/kaggle_kernel_votes_analysis">GitHub</a> or in <a href="https://www.kaggle.com/aleksandradeis/how-to-get-upvotes-for-a-kernel-on-kaggle">Kaggle kernel</a>.</p><h4>Explore statistics for the number of kernels</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96lc1lBOR-itGHQU-aUtpQ.png" /><figcaption>Plot 1. Kernel statistics pie chart</figcaption></figure><p>If we just count the total number of kernels and compare it to the number of ones which have upvotes, we can see that writing a popular kernel is not an easy task.</p><p>There are more than 220 thousand kernels on Kaggle in total, only 20% of them were upvoted by Kaggle users, and only 4% are awarded, which means has more than 5 upvotes (see Plot 1).</p><h4>How does the number of views and number of comments affect the number of votes?</h4><p>My idea is that the more people view or discuss the kernel, the more votes it gets. To prove this assumption let’s first look at the correlation between the number of votes and the number of views and comments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*SbEpBpSGFAAiDii34BdtBQ.png" /><figcaption>Plot 2. Correlation between the number of votes and the number of views and comments</figcaption></figure><p>We really see that these numbers are highly correlated. We can also plot the number of votes versus the number of views and comments and add to the plot the linear line, which shows the dependency between them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uE2lfj9EoSa8x416uowmfw.png" /><figcaption>Plot 3. The number of votes per number of views</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxtzklSg82ulX0aAjYUfEg.png" /><figcaption>Plot 4. The number of votes per number of comments</figcaption></figure><p>Looking at the plots it really seems that my idea was right. To gain upvotes from the users, the kernel needs to be shared with others, seen and discussed.</p><h4>How does the status of the author affect the number of votes per kernel?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*kABGuPKS3irxPuwOuwsFnw.png" /><figcaption>Plot 5. The average number of votes depending on user performance tier</figcaption></figure><p>Kaggle has its own progression system, there are performance tiers depending on the proficiency and the contribution of the users.</p><p>Indeed, we can see on the plot 5 that kernels created by more proficient authors gain more votes on average.</p><h4>How does dataset related to kernel affects the number of votes?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*_Eye7WoiDYnuiVKhpT7oOw.png" /><figcaption>Plot 6. The average number of kernel votes per number of dataset downloads</figcaption></figure><p>Kernels on Kaggle use as data sources datasets released on Kaggle. Datasets on Kaggle also gain votes from users. Let’s try to find out how the popularity of a dataset affects the number of votes for the related kernels?</p><p>I tried to plot the average number of kernel votes depending on the number of votes and downloads for the dataset,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*BzGsZQ9Fi8MrwpBj6THHEg.png" /><figcaption>Plot 7. The average number of kernel votes per number of votes for a related dataset</figcaption></figure><p>which was used as the data source (see plot 6 and plot 7).</p><p>It looks like there is no dependency between the number of votes for s kernel and the number of votes or downloads for the dataset used as a data source. I suppose that we can create a really helpful and popular kernel for an unpopular dataset and vice versa.</p><h4>How does kernel language affect the number of votes?</h4><p>Kernels on Kaggle can have different language types, for example, Python scripts, Python notebooks, R scripts etc. The plot below shows the average number of votes for each language type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*zS65dkU26eWLE-QhD26Z8w.png" /><figcaption>Plot 8. The average number of votes per kernel language</figcaption></figure><p>It looks like descriptive kernels which use markdown are more appreciated with Kaggle users and gain more votes on average.</p><h4>How do kernel tags affect the number of votes?</h4><p>Authors can add tags to their kernels. We can plot the average number of kernel votes for each of top-20 most popular tags on Kaggle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*Qw1zhFLHD-Nfg8E_iyK0PA.png" /><figcaption>Plot 9. Average number of kernel votes per top-20 most popular tags</figcaption></figure><p>It is also interesting to find out which tags have the greatest average number of votes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*AgzTh7U5ssFiMLC-EIj8RQ.png" /><figcaption>Plot 10. Tags with the highest average number of kernel votes</figcaption></figure><p>According to the plots, the most kernels tagged with the most popular tags on Kaggle do not score the greatest number of votes.</p><h3>Conclusion</h3><p>In conclusion, I would like to summarize all the findings and recommendations from this analysis:</p><ol><li><strong>It is hard to create a really helpful kernel, which will be appreciated and upvoted by Kagglers</strong>: only 20% of kernels have upvotes and only 4% of kernels have awards (have more than 5 upvotes).</li><li><strong>Views and comments bring upvotes</strong>: consider adding a captivating title to the kernel and sharing the link to the kernel with others, the more people will view the kernel — the more people will find it useful.</li><li><strong>Active authors have more votes</strong>: try to be an active author and gain visibility, experience in writing kernels and feedback from the others will eventually help to get votes.</li><li><strong>It doesn’t really matter what topic the kernel is related to, but it matters how the kernel material is presented</strong>: notebooks tend to be more appreciated by Kagglers.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e7de8722d9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketing Data Analysis Portfolio of a Data Scientist]]></title>
            <link>https://medium.com/@astakhova.aleksandra/marketing-data-analysis-portfolio-of-a-data-scientist-698d8b65dfb9?source=rss-9f0981e41a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/698d8b65dfb9</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alexandra Deis]]></dc:creator>
            <pubDate>Fri, 08 Feb 2019 12:17:38 GMT</pubDate>
            <atom:updated>2019-02-08T12:19:13.657Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2qpXPwucNOtzlatMipCFg.jpeg" /><figcaption>Photo by rawpixel on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>Marketing Data Analysis for a Data Scientist Portfolio</h3><h4>An example of marketing data analysis</h4><h3>Introduction</h3><p>Today organizations, which hire data scientists are especially interested in the job candidate’s portfolio. Analysis of the organization’s marketing data is one of the most typical applications of data science and machine learning. Such an analysis will definitely be a nice contribution to the portfolio. That’s why I decided to write this article, which contains a walkthrough on how to make such an analysis.</p><p>In this article, I used a <a href="https://www.kaggle.com/janiobachmann/bank-marketing-dataset">dataset on Kaggle</a> which contains bank marketing data. We can use this dataset for the prediction of the results of the marketing campaign for each customer and for finding out the recommendation on how to make marketing campaigns more efficient.The detailed description of the dataset’s content is described in <a href="https://www.kaggle.com/janiobachmann/marketing-in-banking-opening-term-deposits">this Kaggle kernel</a>.</p><h3>Analysis Approach</h3><p>In order to optimize marketing campaigns with the help of the dataset, we will have to take the following steps:</p><ol><li><strong>Import data from the dataset and perform initial high-level analysis</strong>: look at the number of rows, look at the missing values, look at dataset columns and their values respective to the campaign outcome.</li><li><strong>Clean the data</strong>: remove irrelevant columns, deal with missing and incorrect values, turn categorical columns into dummy variables.</li><li><strong>Use machine learning techniques</strong> to predict the marketing campaign outcome and to find out factors, which affect the success of the campaign.</li><li><strong>Finalize recommendations</strong> to improve the outcome of the next marketing campaigns.</li></ol><p>In this article I won’t stop on technical tasks like data cleaning, you can find all code on <a href="https://github.com/Lexie88rus/bank-marketing-analysis">my GitHub</a>. Instead, I would like to concentrate on the analysis itself and on its outcomes.</p><h3>High-level Analysis</h3><p><strong>The first</strong> thing we should do is to analyze what data is missing. Luckily, in our dataset, there are no missing values.</p><p><strong>The second</strong> step is to look at the values in dataset’s columns. We can plot bar charts for categorical columns (see plot 1) and histograms for numerical columns (see plot 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zLqx-2OQtvwGRyPdLifKag.png" /><figcaption>Plot 1. Categorical columns</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*7un4bUn3NTzTun1WGbrZpQ.png" /><figcaption>Plot 2. Numerical columns</figcaption></figure><p>The major outcome of this step is that numerical columns such as the number of contacts during current campaign (‘campaign’) and previous campaign (‘previous’) certainly contain incorrect values, which should be handled during data cleaning phase.</p><p><strong>The last step</strong> would be to compare values in dataset’s columns with the result of the campaign. In this article I would like to discuss only couple examples, you may find the full analysis <a href="https://github.com/Lexie88rus/bank-marketing-analysis">on GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*r46Ru_vNxJ5ZdAoPNZJN4w.png" /><figcaption>Plot 3. Term deposit subscriptions and marital status</figcaption></figure><p>For example, if we compare the marital status of the customer and the result of the campaign (see plot 3), we may see that married customers are more likely to decline the offer for term deposit subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*JZZVERLvke7ikqB-zRYqpA.png" /><figcaption>Plot 4. Statistics for the age of the customers who did subscribe and didn’t subscribe for the term deposit</figcaption></figure><p>Let’s also look at the average, minimum and maximum values of the age of the customers who did subscribe and didn’t subscribe for the term deposit (see plot 4). From this plot, we can conclude that people who subscribed for the term deposit tend to have greater age values.</p><h3>Data Cleaning</h3><p>After we explored the columns in the dataset it is time to prepare the data for machine learning. In our case, we are lucky having no missing data, but we still have to deal with incorrect values discovered in the previous part of the analysis and to convert categorical columns into dummy variables. For the incorrect numerical values, I suggest replacing those with the average values for the column. You can find all the code for data cleaning <a href="https://github.com/Lexie88rus/bank-marketing-analysis">on GitHub</a>.</p><h3>Apply Machine Learning</h3><p>Now the data is ready for the machine learning. We can use classification models to predict whether the customer will accept the offer for the term deposit. There is a wide range of classification models, I chose a model which uses <a href="https://en.wikipedia.org/wiki/Gradient_boosting">gradient boosting</a> implemented in <a href="https://xgboost.readthedocs.io/en/latest/">XGBoost library</a>. The main advantages of this approach are that such models are better in handling incorrect data and less likely to overfit.</p><p>As a result, we get the model which can predict the outcome of the campaign with 85% accuracy and the importance of each variable for the prediction (see plot 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*SmqJHiasr2WmS6tMTHtrxA.png" /><figcaption>Plot 5. Importance of each feature for the prediction</figcaption></figure><p>As we can see, the most important features are:</p><ul><li>Customer’s account balance,</li><li>Customer’s age,</li><li>The number of contacts performed during this campaign and contact duration,</li><li>The number of contacts performed before this campaign.</li></ul><h3>Finalize Recommendations</h3><p>Our findings collected so far are not specific and cannot be used for optimization of the next marketing campaign. As a result of the analysis, we should give way more specific recommendations.</p><p>In order to do this, for example, let’s take the age values, split them into buckets and look at average term deposit subscription versus age bucket (plot 6).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*RZwqrbg0FXqmizcgrfk7Nw.png" /><figcaption>Plot 6. Average term deposit subscription versus age bucket</figcaption></figure><p>We see that greater term deposit subscription rates relate to the younger and the elder customer groups. So we finally will recommend the future campaign to concentrate on customers from age categories below 30 years old and above 50 years old.</p><p>The same analysis should be carried out for the customer’s account balance and the number of contacts with the customer during the campaign. You may find it <a href="https://github.com/Lexie88rus/bank-marketing-analysis">on GitHub</a>.</p><h3>Conclusion</h3><p>In this article, I showed an example of a case study in one of the most typical areas where data science is applied. The article covered all parts of the analysis: initial data exploration, general data cleaning aspects, modeling, and preparation of final results.</p><p>So now you should be ready to make your own case studies, which will certainly contribute to your portfolio. Good luck and have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=698d8b65dfb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AirBnB Seattle Reservation Prices Analysis]]></title>
            <link>https://medium.com/@astakhova.aleksandra/airbnb-seattle-reservation-prices-analysis-e733a0b8dbfe?source=rss-9f0981e41a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/e733a0b8dbfe</guid>
            <category><![CDATA[airbnb]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Alexandra Deis]]></dc:creator>
            <pubDate>Wed, 30 Jan 2019 08:00:09 GMT</pubDate>
            <atom:updated>2019-01-30T08:00:09.173Z</atom:updated>
            <content:encoded><![CDATA[<h4>What affects reservation prices in Seattle and how can we save money on the reservation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xnm1_7XDyo3SdrCZO36suQ.jpeg" /><figcaption><em>Photo by Timothy Eberly on Unsplash</em></figcaption></figure><h3>Introduction</h3><p>Finding an accommodation is the most typical problem to be solved, when traveling to another city or country. And one of the most important things in choosing an accommodation is the reservation price. What are the main factors, which affect the reservation prices? Does the time of the year influence prices and what are the busiest times of the year to visit a particular city? How can we save money on the reservation?</p><p>Fortunately, we can try to answer these questions by analyzing publicly accessible <a href="https://www.airbnb.com/"><strong>AirBnB</strong></a> data, available on <a href="http://insideairbnb.com/get-the-data.html"><strong>Inside AirBnB</strong></a> and on <a href="https://www.kaggle.com/airbnb/seattle"><strong>Kaggle</strong></a>.</p><h3>Initial Insights</h3><p>Before diving deep into data, let’s find out some general information on how the reservation price is determined and search for some useful facts for the future analysis.</p><p>AirBnB reservation price is based on the following costs (according to <a href="https://www.airbnb.com/help/article/125/how-is-the-price-determined-for-my-reservation?locale=en"><strong>AirBnB official website information</strong></a>):</p><ol><li>Costs determined by the host:</li></ol><ul><li>Nightly price: Nightly rate decided by the host;</li><li>Cleaning fee: One-time fee charged by some hosts to cover the cost of cleaning their space;</li><li>Extra guest fees: One-time fee charged by some hosts to cover other costs related to using their space;</li></ul><p>2. Costs determined by Airbnb: Airbnb service fee;</p><p>3. Other costs that may be included: currency exchange fees, VAT, other local taxes etc.</p><p>In our analysis, we will concentrate on the factors, which influence the nightly price, determined by the host. Actually, AirBnB already has an algorithm, which suggests hosts the price. The approach for the algorithm and challenges are described <a href="https://www.vrmintel.com/inside-airbnbs-algorithm/"><strong>here</strong></a>. We can also use the information from this article in our analysis:</p><ul><li>Time of the year, when reservation is made, affects the price;</li><li>It is better to use neighborhood information rather then exact coordinates to describe the location of the place because sometimes even close locations might have a huge difference in listing prices, if they belong to different neighborhoods or are located different sides of the river.</li></ul><h3>Analysis Approach</h3><p>First of all, I chose Seattle dataset, and it will take me the following steps to come into conclusions about factors, affecting reservation prices:</p><ol><li><strong>First look at the data</strong>: general facts on information we have;</li><li><strong>Data preparation</strong>: remove the irrelevant information; clean data and deal with missing values; in this article, we won’t stop at this step, detailed description and code for data preparation is available on <a href="https://github.com/Lexie88rus/AirBnB-Prices-Analysis"><strong>GitHub</strong></a>;</li><li><strong>High-level analysis</strong>: find out first takeaways looking at high-level trends and correlations;</li><li><strong>Apply machine learning</strong> techniques for further analysis.</li></ol><h3>First Look at the Data</h3><p>Before we start discussing diagrams created based on the data, let’s have a quick overview of the data we use:</p><ul><li>Dataset contains information on <strong>3,818</strong> listings available for reservation in Seattle, provided by <strong>2,751</strong> hosts.</li><li>For each listing we can find out its number of bedrooms, bathrooms, location information, host information, review scores.</li><li>Reservation prices for each listing in 2016.</li></ul><h3>Outcomes from High-level Analysis</h3><h4>1. What are the main factors, which affect the reservation prices?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3a3FSH0ncKNGlgwfC4inHg.png" /><figcaption>1. Heatmap of correlations between dataset features</figcaption></figure><p>It is useful to look at correlation between reservation price and other variables from the dataset. Of course, the correlation doesn’t mean for sure that price depends on variables it is correlated with, but such analysis will certainly give us a clue.</p><p>On the diagram #1, you may find a heatmap of correlation coefficients. The closer coefficient is to 1 or to -1 the more correlated are the variables.</p><p>Correlation heatmap shows us obvious fact that the reservation price depends on how large is the place i.e. the number of bedrooms, bathrooms, beds and accommodates.</p><h4>2. Does the time of the year influence prices and what are the busiest times of the year to visit Seattle?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Z3ZkgntQhBddpjAyNqMiBg.png" /><figcaption>2. The number of available listings per month in 2016</figcaption></figure><p>At first let’s look at statistics for the number of listings available for reservation in 2016.</p><p>Plot #2 shows that in summer number of listings available for reservation tends to decrease significantly. This may affect the prices, so let’s look at average reservation price over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*sBYPzTiULmmFUn7Ob3ikVg.png" /><figcaption>3. Average price depending on the time of the year</figcaption></figure><p>Reservation price over time is presented on plot #3. We can see that the average price tends to increase in summer.</p><p>To summarize all mentioned above we can say that prices definitely depend on the time of the year and for the Seattle the busiest time is summer, probably, because of a smaller number of available listings compared to the other times of the year.</p><h3>Outcomes from Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cX6E60m9GJEgEypDBp-ppw.png" /><figcaption>4. Most important features (RF model)</figcaption></figure><p>We can use machine learning techniques to find out factors, which affect reservation price.</p><p>In this article we won’t dive deep into the description of these techniques, all details you may find on <a href="https://github.com/Lexie88rus/AirBnB-Prices-Analysis">GitHub</a>. I will just say that I trained two machine learning models based on decision trees (<a href="https://en.wikipedia.org/wiki/Random_forest">Random Forest regressor</a> and <a href="https://en.wikipedia.org/wiki/XGBoost">XGBoost regressor</a>) and analyzed importances of variables from the dataset, see plot #4 and plot #5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6KjvNwUK1FPVtfqrhVi2w.png" /><figcaption>5. Most important features (XGB model)</figcaption></figure><p>The main results of the modeling are the following:</p><ul><li>The modeling shows us that factors already mentioned above have an influence on price: time of the year, location, number of bedrooms, bathrooms, beds and accommodates.</li><li>The host qualities are important: number of host’s listings, number of years since being the host, time in which the host responds to the inquiries.</li><li>The pricing might depend on reviews: number of reviews and review scores.</li></ul><h3>Conclusion</h3><p>In this analysis, we tried to understand what influences the reservation prices with the help of AirBnB data for Seattle. Of course, the results may be different for each city, but the current approach still can be used for other cities’ data.</p><p>The main takeaways of the analysis based on Seattle data include:</p><ul><li>Basic characteristics of the place (number of bedrooms, bathrooms, beds, and accommodates) affect the reservation price.</li><li>The reservation price varies depending on the time of the year. For example, the busiest time to visit Seattle is in summer.</li><li>The host qualities and the number of reviews and review scores might also affect the reservation price. That is why if you want to save some money, you may, for example, look for places which have fewer reviews or least honored host. This will help to find the places with the same characteristics (bathrooms, bedrooms, location etc.), and lower reservation price.</li></ul><p>So now when we know how to choose between places offered by AirBnB and save money it is time to travel and test it on practice!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e733a0b8dbfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>