<?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 Bibek Dhakal on Medium]]></title>
        <description><![CDATA[Stories by Bibek Dhakal on Medium]]></description>
        <link>https://medium.com/@dhakal-bek?source=rss-4d82954e65ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I8V5QxPxsBdlik4PKVTl3w.jpeg</url>
            <title>Stories by Bibek Dhakal on Medium</title>
            <link>https://medium.com/@dhakal-bek?source=rss-4d82954e65ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:33:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhakal-bek/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[Diving into different GAN architectures]]></title>
            <link>https://medium.com/data-science/diving-into-different-gan-architectures-a96d05c03c5c?source=rss-4d82954e65ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/a96d05c03c5c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[Bibek Dhakal]]></dc:creator>
            <pubDate>Fri, 12 Feb 2021 20:54:52 GMT</pubDate>
            <atom:updated>2021-02-12T20:54:52.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CskV6PKYn1KmsISb" /><figcaption>Photo by <a href="https://unsplash.com/@ingmarr?utm_source=medium&amp;utm_medium=referral">Ingmar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Introduction</strong></p><p><strong>GAN </strong>is one of the interesting and exciting innovation in Machine Learning. <strong>Generative Adversarial Network</strong>(GAN) is a class where two neural networks contesting with each other in the form of a zero-sum game. Given a training set, this technique learns to generate new data with the same statistics as the training set.</p><p>It is an <a href="https://en.wikipedia.org/wiki/Unsupervised_learning">unsupervised learning</a> task in machine learning that involves automatically discovering and learning the patterns in input data in such a way that the model can be used to generate or output new examples that can be drawn from the original dataset.<br>In an unsupervised learning, only the inputs are given and the goal is to find the interesting patterns in data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*7VGwvZyB0dq-7lf06w3FlA.png" /><figcaption>Fig:Unsupervised Learning Example Img Ref: <a href="https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/">Machine Learning Mastery</a></figcaption></figure><p>GANs are generative models i.e. they create new data instances from training data.</p><p><strong>Applications</strong></p><p>The use of GAN has been increasing rapidly in the field of fashion, art, science, video games etc. For example, GANs create images that look like a human from the statues of a Roman emperor.</p><p><strong>Architecture</strong></p><p>A generative adversarial network consists of two parts as Generator and Discriminator. The generator learns to generate the probable data which seems from the training data and on the other hand discriminator tries to differentiate the generator’s fake data from real data. The discriminator penalizes the generator for implausible results.</p><p>The Generator tries to fool the discriminator into thinking that the generated images are real and the discriminator tries to differentiate between real and fake images. Random noise is fed into the Generator that transforms it into a “fake image”. The Discriminator is fed from both the training set images and the fake images coming from the generator and it has to tell them apart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*9jwIuW0KPi3THIvoYg9BUQ.png" /><figcaption>Fig: Architecture of GAN Img Ref: <a href="https://developers.google.com/machine-learning/gan/gan_structure">Google Developers</a></figcaption></figure><p>The main idea behind GAN is to train both the generator and discriminator alternatively to do the best they can in generating and discriminating images. The aim is that by improving one of these networks, in this game-theoretic manner, the other network has to do a better job to win the game, and that in turn improves the performance and this loop continues. Generative Adversarial Networks have demonstrated impressive performance for unsupervised tasks.</p><p>Some of the most popular GAN architectures are :</p><p>a. <strong>CycleGAN</strong></p><p>b.<strong>StyleGAN</strong></p><p>c.<strong>LSGAN</strong></p><p>d.<strong>DiscoGAN</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CGJa8fxBofn2hJFx" /><figcaption>Photo by <a href="https://unsplash.com/@michalbarhaim?utm_source=medium&amp;utm_medium=referral">Michal Bar Haim</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>a. CycleGAN</strong></p><p>It is a technique that involves the automatic training of image to image translation models without paired examples. Example of the image to image translation is translating horse to zebra or vice versa. CycleGAN uses a cycle consistency loss to enable training without the need for paired data. It can translate from one domain to another without a one-to-one mapping between the source and the target domain. The goal of the image-to-image translation problem is to learn the mapping between an input image and an output image using a training set of aligned image pairs.</p><p>For two domains <strong>X</strong> and <strong>Y</strong>, CycleGAN learns a mapping <strong>G:X -&gt; Y </strong>and <strong>F:Y -&gt; X</strong>.</p><p>CycleGAN has three sections: <strong>Encoder, Transformer </strong>and <strong>Decoder.</strong></p><p>CycleGAN can be helpful when there is a need for colour transformation.</p><p><strong>b. StyleGAN</strong></p><p>Introduced by Nvidia researchers, StyleGAN is a novel generative adversarial network.The StyleGAN is an extension to the GAN architecture that proposes large changes to the generator model, including the use of a mapping network to map points in latent space to an intermediate latent space, the use of the intermediate latent space to control style at each point in the generator model, and the introduction to noise as a source of variation at each point in the generator model.<br>The resulting model is capable not only of generating impressively photorealistic high-quality photos of faces, but also offers control over the style of the generated image at different levels of detail through varying the style vectors and noise.</p><p><strong>c. LSGAN(Least Square Adversial Network)</strong></p><p>In a normal GAN, the discriminator uses cross-entropy loss function which sometimes leads to vanishing gradient problems. Instead of that LSGAN uses the least-squares loss function for the discriminator. It has the desire to provide a signal to the generator about the fake samples that are far from the discriminator model’s decision boundary for classifying them as real or fake. It can be implemented with a minor change to the output layer of the discriminator layer and the adoption of the least-squares, or loss function.</p><p><strong>d. DiscoGAN</strong></p><p>It generates images of products in <strong>domain B </strong>given an image in <strong>domain A</strong>. It transfers elements from one image to another.<br>DiscoGAN has two generators. The first generator maps the input image from <strong>Domain A</strong> to <strong>Domain B</strong>. The second generator reconstructs the image from Domain B to Domain A.</p><p>There is a slight similarity between CycleGAN and DiscoGAN. In CycleGAN it has an addition hyperparameters to adjust the contribution of reconstruction/cycle-consistency loss in the overall loss function.<br>DiscoGAN can be used for transferring decoration from a fashion item such as a bag to another fashion item as a pair of shoes.</p><p><strong>Conclusion</strong></p><p>There are thousands of papers on GANs and many hundreds of named-GANs, that is, models with a defined name that often includes “<em>GAN</em>“.There can be some difficulties while creating a new architecture using the GAN architecture. It is known that training GAN networks is highly unstable. Hyperparameter optimization is difficult to find the right balance between learning rates to efficiently train the network. In all of the architectures generators is most used for training the data.</p><p>References:</p><p>1.<a href="https://en.wikipedia.org/wiki/Generative_adversarial_network">https://en.wikipedia.org/wiki/Generative_adversarial_network</a></p><p>2.<a href="https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/">https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/</a></p><p>3.<a href="https://developers.google.com/machine-learning/gan/gan_structure">https://developers.google.com/machine-learning/gan/gan_structure</a></p><p>4.<a href="https://www.kaggle.com/roydatascience/introduction-to-generative-adversarial-networks">https://www.kaggle.com/roydatascience/introduction-to-generative-adversarial-networks</a></p><p>5.<a href="https://www.geeksforgeeks.org/cycle-generative-adversarial-network-cyclegan-2/">https://www.geeksforgeeks.org/cycle-generative-adversarial-network-cyclegan-2/</a></p><p>6.<a href="https://neptune.ai/blog/6-gan-architectures">https://neptune.ai/blog/6-gan-architectures</a></p><p>7.<a href="https://medium.com/towards-artificial-intelligence/generating-matching-bags-from-shoe-images-and-vice-versa-using-discogans-8149e2cbc02">https://medium.com/towards-artificial-intelligence/generating-matching-bags-from-shoe-images-and-vice-versa-using-discogans-8149e2cbc02</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a96d05c03c5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/diving-into-different-gan-architectures-a96d05c03c5c">Diving into different GAN architectures</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[Using Prophet in Stock Market]]></title>
            <link>https://medium.com/swlh/using-prophet-in-stock-market-e79238c38c8e?source=rss-4d82954e65ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/e79238c38c8e</guid>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[Bibek Dhakal]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 18:15:09 GMT</pubDate>
            <atom:updated>2021-02-12T16:18:55.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0TJzymvKizg1sJ7e" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Forecasting is one of the most common data science task used in time series data. It helps to know where the direction of the next data is.</p><p>Time-series analysis or forecasting may be a bit hard because there are different types of methods, parameters etc. Producing high-quality forecast is not an easy problem neither for machine nor data analysts.</p><h4>Introduction</h4><p>Facebook made a tool “<a href="https://facebook.github.io/prophet/docs/quick_start.html">Prophet</a>” which helps to do time-series forecasting at a scale with ease.</p><p>Prophet does forecasting model based on an additive model where non-linear trends are fit with daily, weekly and yearly seasonality plus holidays.</p><p>Most of the time it works best with time-series data that have strong seasonal effects and several seasons of historical data. It handles outliers well.It uses the model in three main components: seasonal, trends, holidays or events effect and error which are combined into the equation.</p><p>They are combined in the following equation as:</p><p><strong>y(t) = g(t) + s(t) +h(t) + εt .</strong></p><p>The Prophet is an open- source library for making univariate analysis, prediction in time-series data.</p><p>One of the easiest, friendly library for time series, it has got many components and features inside of it.</p><p>The most interesting feature of Prophet is that it supports trends, seasonality, holidays effects weekly, yearly and even daily.</p><p>Here we will move lightly in basic towards some of the analysis and forecasting with Prophet in Stock Market Data using Python. Dataset and all the source code is available on <a href="https://github.com/Dhakal29/FBProphet"><em>Github</em></a>.</p><p><strong>Implementation</strong></p><p>For implementing in Python, it is needed to have some of the libraries installed:</p><p><strong>1.Pandas</strong></p><p><strong>2.Matplotlib</strong></p><p><strong>3.FB Prophet</strong>( we can install it through <em>!pip install fbprophet</em>)</p><p><strong><em>Note:</em></strong><em> Stock Market and prices change over a lot of attributes like sentiments, demand and supply of stocks. The following procedure and algorithm do not guarantee any returns of profits.</em></p><p>Prophet works under the specific format that is the data frame should have only <strong>‘ds’ </strong>and <strong>‘y’</strong> as names <strong>ds</strong> for <em>dates</em> and <strong>y</strong> for <em>observations</em>.</p><p><strong>Loading and Filtering the data</strong></p><p>The dataset used here is of <a href="https://nepalre.com.np/ne/">Nepal Reinsurance Company(NRIC)</a>. It contains the columns like <strong>Date, Closing Price, Previous Closing, Traded Shares </strong>etc.</p><p>When the data is loaded from pandas, for prediction only two attributes are needed.</p><p><strong>Date</strong> and <strong>Closing price</strong> are filtered and taken under <em>data_to_use</em>. The whole dataset is loaded under <strong>df</strong>.</p><pre>data_to_use = df.filter([&#39;Date&#39;,&#39;Closing Price&#39;])</pre><p>While visualizing through Matplotlib <strong>Date</strong> vs <strong>Closing Price</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*s3f-msD0xWqLk7NVUlsyQQ.png" /><figcaption>Fig:Closing Price vs Date(Image by author)</figcaption></figure><p>Since Date and price of the table are already selected next process is to change their name to <strong>‘ds’</strong> and <strong>‘y’</strong> respectively through Python code.</p><pre>data_to_use.columns = [&#39;ds&#39;,&#39;y&#39;]</pre><p>After renaming the columns now the next thing to do is to change the data to date time format using Pandas as Prophet algorithm uses DateTime format.</p><pre>data_to_use[&#39;ds&#39;] = pd.to_datetime(data_to_use[&#39;ds&#39;])</pre><p>All done.</p><p>Now the data is ready for an algorithm.</p><p><strong>Prophet Algorithm</strong></p><pre>from fbprophet import Prophet<br>model = Prophet()</pre><p>After the model is created it is fitted with the data(<em>data_to_use </em>here) like in other Deep Learning/Machine Learning Models i.e.</p><pre>model.fit(data_to_use)</pre><p>While running the above code some of the warnings may be given, it can easily be ignored.</p><p>Warnings example will be like:</p><pre>INFO:fbprophet:Disabling yearly seasonality. Run prophet with yearly_seasonality=True to override this.<br>INFO:fbprophet:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.</pre><p>One of the interesting things about Prophet is that with <em>make_future_dataframe</em> function Periods for the future prediction can be provided.</p><p>Here, <strong>periods</strong>=<strong>10 </strong>is taken for the next 10 days prediction from the end date.</p><pre>future_dates = model.make_future_dataframe(periods=10)</pre><p><strong>Prediction</strong></p><p>Since the model is ready with our previous and future date to predict. Future dates are loaded now for next:</p><pre>prediction = model.predict(future_dates)</pre><p>When the models are loaded with future dates, the <strong>‘y’</strong> component values get predicted.</p><p>If the code below is run,</p><pre>prediction.tail()</pre><p>The end of the predicted model where the future dates are seen with columns(<strong>trends,yhat</strong> etc.) is seen.</p><p><strong>Visualization</strong></p><p>For visualizing the plot, matplotlib is there so,</p><p>Let us see from this cool library.</p><pre>import matplotlib.pyplot as plt<br>model.plot(prediction)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*99Pcrp5pntQayPMizv2CXg.png" /><figcaption>Graph with Predicted value after November 26(Image By author)</figcaption></figure><p>When trends need to be seen from weekly or monthly basis, the prophet has another function as components.</p><pre>model.plot_components(prediction)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qf1qTpzgLE7wb1HVTl-3qA.png" /><figcaption>Weekly, trends from components(Image by author)</figcaption></figure><p><strong>Conclusion</strong><br>With the help of the Prophet, there can be a better understanding of time-series data. It has got different inbuilt tools like cross-validation, predictive trend, performance metrics etc. It can be used to understand deeper features of time-series which helps to know better about the properties of data. It’s fast to understand the forecasting scenario with spending too much time in building the model with other amazing algorithms. <em>fbprophet</em> package can make us dive deeper into the analysis of time-series data.</p><p><strong>References:</strong></p><p>1.<a href="https://machinelearningmastery.com/time-series-forecasting-with-prophet-in-python/">https://machinelearningmastery.com/time-series-forecasting-with-prophet-in-python/</a></p><p>2.<a href="https://peerj.com/preprints/3190/">https://peerj.com/preprints/3190/</a></p><p>3.<a href="https://levelup.gitconnected.com/time-series-forecasting-with-prophet-in-r-a9ee81dc82e1">https://levelup.gitconnected.com/time-series-forecasting-with-prophet-in-r-a9ee81dc82e1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e79238c38c8e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/using-prophet-in-stock-market-e79238c38c8e">Using Prophet in Stock Market</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is there to fear?]]></title>
            <link>https://dhakal-bek.medium.com/what-is-there-to-fear-2e16b334e16c?source=rss-4d82954e65ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e16b334e16c</guid>
            <category><![CDATA[happiness]]></category>
            <category><![CDATA[fear]]></category>
            <category><![CDATA[depression]]></category>
            <category><![CDATA[peace-of-mind]]></category>
            <category><![CDATA[elemental]]></category>
            <dc:creator><![CDATA[Bibek Dhakal]]></dc:creator>
            <pubDate>Fri, 16 Oct 2020 16:41:45 GMT</pubDate>
            <atom:updated>2020-12-02T17:05:09.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFYX05p4N1_QTIw3D71C2g.jpeg" /><figcaption>Image by: Alexandra Gorn Source:Unsplash</figcaption></figure><h3>Introduction</h3><p>In this world with more than 7.8 billions people, everyone is in their journey.</p><p>No one is free from problems whether they live in a large building or mud roof houses, whether they eat in gold plated plates or on leaves.</p><p>For each success matters a lot. Everyone wants to become successful.</p><p>The success here is measured in money they have, name, fame they have, supporters who care and properties they own. But if we go deep down inside of them then can we get some true answer?</p><blockquote>Are all successful people satisfied with their life?</blockquote><blockquote>Are all happy?</blockquote><p>The public celebrity, whom everyone wants to have a selfie. Do all people who take a photo with them, do they care? Do they ask how are their mental health? Do they ask how are you?</p><p>I think its <strong>No</strong>. Because people here don’t care about others. We have to care about us ourselves.</p><p>The less expectation the more cheerful you are.</p><p>People may have been sleeping in a luxurious bed but can they sleep within a minute or is there a pill near their bed?</p><p>This story doesn’t mean that if you become rich you will not be happy so don’t be rich or successful.</p><p>I want to say take care of your happiness, you inside self-worth and your internal body things.</p><p>Deep inside your heart have you ever cared what is left there which you have been ignoring since ages?</p><p>The happiness, relief, calm things don’t matter only to money, property-rich people. It matters to all of us.</p><p>Are we having a calm mind? Are we having peace in sleep? Do we always feel stressed in working with only 10 hours a day?</p><blockquote>Don’t we feel ourselves the only busy, struggler, stressful person in this world?</blockquote><blockquote>The fear of failures is for everybody in this whole world.</blockquote><blockquote>The fear of losing their property is for everybody.</blockquote><blockquote>The older you get the more fearful you become.</blockquote><p>Like we have a god with different faces from a different religion, we have a ghost/demon of different faces. Such faces are fears, jealousy, hatred, ego, anger.</p><p>If you believe in god then, of course, there is a ghost.</p><p>God is love, support, help while ghost/ demon are fear, hatred, jealousy, anger.</p><p>The fears may come differently,</p><p>When you think in the way of more what if, then you are fearful.</p><blockquote>What if I failed to impress people?</blockquote><blockquote>What if I failed to get a job?</blockquote><blockquote>What if my marriage doesn’t get success?</blockquote><blockquote>What if my parents die?</blockquote><blockquote>Most of us have such questions always in all of our minds.</blockquote><blockquote>Why do we need to think always in what if?</blockquote><p>Why do we always have to predict ourselves?</p><p>Do such questions have helped you to overcome problems?</p><p>I think most of it is <strong>No.</strong></p><p><strong>Fear affects how you feel physically, mentally and how you behave.</strong></p><p>Fear prepares us to react to danger. When we sense danger, our body releases hormones that slow or shut down functions not needed for survivals. Fear interrupts processes in our brains that allow us to regulate emotions, read non-verbal cues and other information presented to us.</p><p><strong>Why do we fear?</strong></p><blockquote>“<strong>The only thing we have to fear is to fear itself.”</strong></blockquote><blockquote><strong>-Franklin D. Roosevelt</strong></blockquote><p>If we couldn’t be afraid, we wouldn’t survive so long. We may go towards carrying poisonous snakes in hand or the jungle with lots of wild animals. We’d be hanging out with lions, tigers in the forest. Most of us are no longer running in the wild, but fear is far from an outdated instinct. It serves the same purpose today as it did when we might run into a lion carrying water back from the river.</p><p>We are all afraid of snakes, wild animals. Imagine we are standing on the railway track and some train is coming at full speed. Don’t we get fear, unless we are going to kill ourselves?</p><p>Yeah, Fear is there for everybody. But what I am talking about now is the fear inside of you related to your emotions. Not fear like people chasing with a knife towards you but thinking of such things which may not be going in your life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvM64yuTHTAQ0oskN3dCzQ.jpeg" /><figcaption>Image by:Aaron Blanco Tejedor Source:Unsplash</figcaption></figure><h4>I am saying about over thinking of fear.</h4><p>Whatever the problem you are dealing with right now may get amplify if you overthink about it and always make your heart beats faster.</p><p>We need to be ok with the things that are out of control from our hand. If we can’t handle it, if it not being out of control then just be ok. Don’t get stress, don’t grind your teeth. Don’t make negative of yourself. There no use of that.</p><p>Practice self-care. Sometimes being lonely is also good. Give yourself some enough time. By being lonely, it doesn’t mean you are watching Netflix yourself or going to movies alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZXmg2Uqzp0434EHG7txBA.jpeg" /><figcaption>Image by: Denise Jones Source:Unsplash</figcaption></figure><p>Being lonely means give yourself, your body, your mind your heart time.</p><p>Go to a peaceful natural place and focus inside your body breath, heartbeat.</p><p>Training the brain to accept that there’s no threat, the fear inside of us matters a lot. We need to realize ourself that it’s the fear of fear that we fear.</p><p>Why do we need to think of the things that never gonna happen?</p><p>Let us all together tell us ourselves to not fear.</p><p>Let us breathe in-out with the long rush and let it go.</p><p><em>Have a great life ahead.</em></p><p><em>The great here doesn’t mean to be rich or luxury. I mean to say, satisfactory, happiness, love and peace.</em></p><p><em>Thank you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e16b334e16c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPT-3 “The Giant Language Model so far”]]></title>
            <link>https://medium.com/thinking-machine/gpt-3-the-giant-language-model-so-far-1cd41dfba87a?source=rss-4d82954e65ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd41dfba87a</guid>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Bibek Dhakal]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 04:49:41 GMT</pubDate>
            <atom:updated>2020-09-20T16:17:47.514Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Natural Language Processing(NLP)</strong> has been one of the hottest topics in the field of <strong>AI</strong>. The advancements in it and research have made it more flexible and easier to deal with large data and sort out the result. From chatbot to language translation to every other aspect <strong>NLP</strong> has ruled in the field of <strong>AI</strong>. Natural Language Processing tasks flow from generating new articles to language translation and answering standardised test questions.</p><p>Recent research and work have shown substantial gains on many <strong>NLP</strong> tasks and benchmarks by pre-training on a large corpus of text followed by fine-tuning on a specific task. There is a vast array of work while doing NLP. One of the most common tasks among all the NLP is Language Model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_S1G3UqXijrCvsQVcJ9NQ.jpeg" /><figcaption>Image by author</figcaption></figure><p><strong>Language Model</strong></p><p>A language model is one of the most important parts of modern NLP. There have been developed many sorts of applications for Language Modeling like Machine Translation, Spell Correction Speech Recognition, Summarization, Question Answering, Sentiment Analysis etc. Language Model is required to represent the text to a form understandable from the machine point of view. The main goal of the language model is to compute a probability of a token<em>(e.g. a sequence or a sentence of words)</em>. Language Model(<strong>LM</strong>) is a grammar of a language as it gives the probability of word that will follow.</p><p>In unsupervised pre-training, a language model develops a broad set of skills and pattern recognition abilities. It then uses these abilities at inference time to rapidly adapt to or recognize the desired task.</p><p><strong>GPT-3 : Bigger language Model</strong></p><p>From the first announcement of GPT in 2018 to 2020, the researchers are able to develop in extending upto version 3.</p><p>The full-form of GPT-3 is Generative Pertained Transformer-3. It is a successor to a GPT-2. A member team from OpenAI published a research paper describing GPT-3, a deep learning model for natural-language with 175 billion parameters, 100x more than the previous GPT-2. This model is pre-trained on nearly half a trillion words and achieves state-of-the-art performance on several NLP benchmarks without the fine-tuning. It is one of the advancement in language model.</p><p><em>Yeah! GPT-3 is a </em><strong><em>175 billion parameters. </em></strong><em>But what can we do ? It will need a lot of computer and a lot of money to run it. But sure, they have done a great engineering with it.</em></p><p>The researchers goal was to produce a NLP system that performs well on a variety of tasks with little or no fine-tuning, and previous work has indicated that larger models might be the solution. To test that hypothesis, the team increased the size of their previous model, GPT-2, from 1.5 billion parameters to 175 billion of 8 different sizes of model. The GPT-3 is a family of models ranging from 125M weights to 175B</p><p>The developed model was evaluated on over two dozen NLP datasets as well as several novel tasks designed to test rapid adaptation of tasks unlikely to be directly contained in the training set. For each task GPT-3 was evaluated under conditions : ‘<em>few-shot learning’, ‘one-shot learning’ and ‘zero-shot learning’.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*UstO7x7C3buM1kzK2gT1DA.png" /><figcaption>Fig: Larger Models make increasingly efficient use if in-context information(Image Ref:OpenAI research)</figcaption></figure><p>For GPT-3, the OpenAI team used the same model and architecture as GPT-2 includes modified initialisation, pre-normalisation, and reversible tokenization along with alternating dense and locally banded sparse attention patterns in the layers of the transformer.</p><p><strong>Training Process</strong>: As found in other models, larger models can typically use a larger batch size, but require a small learning rate. The team measured the gradient noise scale during training and use it to guide the choice of batch size. And to train the larger models without running out of memory, the team used a mixture of model parallelism within each matrix multiply and model parallelism across the layers of the network.</p><p>GPT-3 learns from a blend of training data that mixes many languages together in a natural way, combining them on a word, sentence, and document level. It also uses a single training objective which is not customized or designed for any task in particular. However, our one/few-shot settings aren’t strictly comparable to prior unsupervised work since they make use of a small amount of paired examples. Such things correspond up to a page or two of in-context training data.</p><p><strong>Performance</strong></p><p>On the basis of performance, different tasks vary, however, and it is not as good as models that have been specifically designed for narrow applications, such as translation or math problem-solving. GPT-3 is also not always good at answering questions.</p><p>Well, we know it is a language model means it is to predict the next word in sequence but in terms of arithmetic operation it sometimes memorizes the data and predicts the next. For example: 2+2=4, 34+52=86. It goes pretty in a small operation. Larger the number gets, its harder for it to memorize.</p><p><strong>Finally, </strong>the GPT-3 architecture is similar to the GPT-2 or GPT but there are only some of the minor differences. The researchers did not use fine-tuning or any other task-specific training except in language Model. But it can perform in a really large amount of data.</p><p><strong>References:</strong></p><p>1. <a href="https://github.com/openai/gpt-3">https://github.com/openai/gpt-3</a></p><p>2.<a href="https://arxiv.org/pdf/2005.14165.pdf">https://arxiv.org/pdf/2005.14165.pdf</a></p><p>3.<a href="https://mchromiak.github.io/articles/2017/Nov/30/Explaining-Neural-Language-Modeling/#.XwCDepZS9uQ">https://mchromiak.github.io/articles/2017/Nov/30/Explaining-Neural-Language-Modeling/#.XwCDepZS9uQ</a></p><p>4.<a href="https://analyticsindiamag.com/open-ai-gpt-3-language-model/">https://analyticsindiamag.com/open-ai-gpt-3-language-model/</a></p><p>5.<a href="https://blog.inten.to/gpt-3-language-models-are-few-shot-learners-a13d1ae8b1f9">https://blog.inten.to/gpt-3-language-models-are-few-shot-learners-a13d1ae8b1f9</a></p><p>6.<a href="https://www.youtube.com/watch?v=_8yVOC4ciXc&amp;t=176s">https://www.youtube.com/watch?v=_8yVOC4ciXc&amp;t=176s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd41dfba87a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thinking-machine/gpt-3-the-giant-language-model-so-far-1cd41dfba87a">GPT-3 “The Giant Language Model so far”</a> was originally published in <a href="https://medium.com/thinking-machine">Inside Thinking Machine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Convolutional Neural Networks]]></title>
            <link>https://medium.com/data-science/inside-convolutional-neural-network-e1c4c1d44fa2?source=rss-4d82954e65ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1c4c1d44fa2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[image-recognition]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[Bibek Dhakal]]></dc:creator>
            <pubDate>Tue, 09 Jun 2020 07:41:07 GMT</pubDate>
            <atom:updated>2020-06-11T08:07:31.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evl1rZpcj7-uR8gIpNWvVg.jpeg" /><figcaption>Image by author</figcaption></figure><h3><strong>Introduction</strong></h3><p><strong>Convolutional Neural Network(CNN)</strong> is one of the deep learning algorithms used in recognition, classification, etc. most commonly applied to analyze visual images which is one of the difficult tasks on doing it, designing it, or implementing it. Here, each layer of the network is connected to all neurons in the next layer. From a biological experiment in the 1950s, there has been a lot of progress and advancement in this area. Usually, a few decades ago, it was really hard for a computer to recognize between the cat and a dog but now it has become like a ‘<em>Hello World</em>’ project.</p><p>From the past few decades, <strong>image recognition </strong>or <strong>computer vision </strong>has been a great subject of increasing interest, continuous and advancement in research, analysis and predictions. The way we humans recognize an image and its type, an electronic machine has trained itself in recognizing and seeing things more deeply. Computer vision is adept at identifying patterns from images than the human visual cognitive system.</p><p><strong>Computer vision </strong>or i<strong>mage recognition </strong>is powered by deep learning algorithms that use <strong>CNN </strong>to get a sense of images. Not only it recognizes patterns but memorizes the ideal output that it should provide for each input image(in the case of <em>supervised learning</em>) or classifies components of images by scanning characteristics like contours and colours. And then this memory is used while scanning those images.</p><p>While moving inside a CNN model for the <strong>first time</strong>, it is really hard to understand it more deeply. So, I have tried to make clear with the basic and short answer to understand the inside CNN layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BMOsij92-KqiIYf1lBamkA.jpeg" /><figcaption>Image by author</figcaption></figure><p>Feedforward neural network with multiple hidden layers in the artificial neural network is usually known as <strong>Deep Neural Network(DNN)</strong>. Convolutional Neural Network is also one kind of feed-forward neural network. As of now, we can say that CNN is a recognition algorithm which is widely used in recognition and image processing, it has many features such as simple structure, less training parameters and adaptability.</p><p>As the neural network receives an input(tensor) and transforms it through a series of hidden layers. Each hidden layer is made up of a set of neurons, where each neuron is fully connected to all neurons in the previous layer.</p><p>At each layer, units are organized into <strong>2-D </strong>grids called feature maps. Each of these feature maps is the result of convolution <strong>i.e. </strong>the same convolutional layer(<em>set of weights</em>) is applied at each location in the layer. So, a unit at a particular location on the 2-D grid can only receive input from units at a similar location at the layer. And the weights attached to the inputs are the same for each unit in feature maps.</p><p>When the convolutional layer is completed, a few other computations are done. One of them is cross-feature normalization. Here the activity of the unit at a particular spatial location in a feature map is divided by the activity of units at the same location in other feature maps. A common other operation is pooling. Pooling shrinks the size of the feature maps. This whole set of operations is combinedly called <strong>‘layer’</strong>. The architecture of a network is defined by the number of layers and choices about various parameters associated with them like the size of convolutional filters.</p><p>Inside the convolutional layer, we need to specify the number of filters, Filter size, Padding, Activation Function/Non-linearity.</p><p>Let us discuss some of it with others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*e-Wwir7QhVBXvpcMeB-DvQ.png" /><figcaption>Fig:CNN architecture Img Ref: <a href="https://neurdiness.wordpress.com/2018/05/17/deep-convolutional-neural-networks-as-models-of-the-visual-system-qa/">Neurdiness</a></figcaption></figure><p>In short, CNN contains following different layers:</p><p><strong>a. Dense layer</strong></p><p><strong>b. Convolutional layer</strong></p><p><strong>c. Max pooling layer</strong></p><p><strong>d. Dropout</strong></p><p>So, after understanding its basic architecture, here comes the problem that <strong>How do we design a Convolutional Neural Network with code?</strong></p><p>This question seems hard but it’s actually not. Python has got good libraries and frameworks for designing a neural network whether it maybe <strong>CNN, RNN </strong>or whatever. The only thing we need to understand is the layers, pooling and other parameters inside them.</p><p>Let us move into a basic simple way to design it and choosing the best parameters and hyperparameters in an abstract way.</p><p>The convolutional layer is the core building block of a convolutional network that does most of the computational heavy lifting. While choosing the layer number it is better to start from the <strong>smallest layer </strong>and gradually increasing the size of the layers or either going with the large model layer and gradually decreasing it. When going with the larger model it really becomes difficult to choose how large the model we build initially.</p><p>When deeper networks are able to start converging, a degradation problem has been exposed: with the network depth increasing, accuracy gets saturated(which might be unsurprising) and then degrades rapidly. Unexpectedly, such degradation is not caused by <em>overfitting </em>and adding more layers to suitably deep models lead to <em>higher training error.</em></p><p>The degradation of training accuracy shows that not all systems are similarly easy to optimize.</p><p>While giving the same number of trainable parameters it may arise to take a decision between using more layers or more units per layer. In such a sense, it is usually better to go deeper than wider. Another way to make deep models easier is to add skip connections that connect non-consecutive layers. Like we can use <strong>ResNet </strong>architecture type connections.</p><p>The skip connections also create an additional path for the gradient to flow back more easily. This makes it easier to optimize the earlier layers. In neural network design, using skip connections is a common pattern.</p><h4>Pooling Layer</h4><p>Pooling layer makes the representations smaller and more manageable and operates over each activation map independently. Pooling layer accepts a volume in three dimensions requiring three hyperparameters with their <strong>spatial extent</strong> <strong>F</strong>, the <strong>stride S</strong> and produces a volume of three dimensions where <strong>W=(W1-F)/S+1 </strong>,<strong>H=(H1-F)/S+1</strong>, <strong>D2=D1</strong>. Pooling layer introduces zero parameters since it computes a fixed function of the input. We donot use zero-padding for pooling layers.</p><p>While using the kernels or filter models it is usually better to use <strong>3X3 </strong>or <strong>1X1 </strong>kernels as most of the time it works best. We can stack <strong>3X3 </strong>kernels on top of each other to achieve a larger receptive field. One of the advantages of using <strong>1X1 </strong>filter is that they can be used for dimensionality reduction.</p><h3>Summary</h3><p>In short answer, we can say a <strong>Convolution layer</strong> is a layer which accepts a volume of <strong>W1*H1*D1</strong> (<strong>W</strong>eights, <strong>H</strong>eights and <strong>D</strong>epth)which require four hyperparameters with number of <strong>filters</strong> defined as <strong>K,</strong> their <strong>spatial extent</strong> <strong>F,</strong> <strong>stride</strong> <strong>S,</strong> with the amount of <strong>zero padding</strong> <strong>P. </strong>With the above inputs the convolution layers produces a volume of size <strong>W2*H2*D2</strong> where <strong>W2 =(W1-F+2P)/S+1, H2 =(H1-F+2P)/S+1</strong>(i.e. <strong>width</strong> and <strong>height</strong> are computed equally by symmetry) and <strong>D2=K. </strong>With parameter sharing, it introduces <strong>F.F.D1 </strong>weights per filter, for a total of <strong>(F.F.D1).K </strong>weights and <strong>K </strong>biases. In the output volume, the<strong> d-</strong>th<strong> </strong>depth slice (of size<strong> W2*H2</strong>) is the result of performing a valid convolution of the <strong>d-</strong>th filter over the input volume with a stride of <strong>S, </strong>and then offset by the <strong>d-</strong>th bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*4o114oe7bI8zmyLD-bJC7Q.png" /><figcaption>Fig: CNN with filter</figcaption></figure><p><em>Thanks for reading.</em></p><p><em>References:</em></p><p><em>1. </em><a href="https://arxiv.org/pdf/1506.01195.pdf"><em>https://arxiv.org/pdf/1506.01195.pdf</em></a></p><p><em>2.</em><a href="https://en.wikipedia.org/wiki/Convolutional_neural_network"><em>https://en.wikipedia.org/wiki/Convolutional_neural_network</em></a></p><p><em>3.</em><a href="https://www.forbes.com/sites/cognitiveworld/2019/06/26/the-present-and-future-of-computer-"><em>https://www.forbes.com/sites/cognitiveworld/2019/06/26/the-present-and-future-of-computer-</em></a><a href="https://www.forbes.com/sites/cognitiveworld/2019/06/26/the-present-and-future-of-computer-vision/#185e3778517d"><em> vision/#185e3778517d</em></a></p><p>4.<a href="https://cs231n.github.io/convolutional-networks/">https://cs231n.github.io/convolutional-networks/</a></p><p>5.<a href="https://neurdiness.wordpress.com/2018/05/17/deep-convolutional-neural-networks-as-models-of-the-visual-system-qa/">https://neurdiness.wordpress.com/2018/05/17/deep-convolutional-neural-networks-as-models-of-the-visual-system-qa/</a></p><p>6.<a href="http://cs231n.stanford.edu/">http://cs231n.stanford.edu/</a></p><p>7.<a href="https://www.youtube.com/watch?v=fTw3K8D5xDs">https://www.youtube.com/watch?v=fTw3K8D5xDs</a></p><p>8.<a href="https://keras.io/api/applications/resnet/">https://keras.io/api/applications/resnet/</a></p><p>9.<a href="https://arxiv.org/pdf/1512.03385.pdf">https://arxiv.org/pdf/1512.03385.pdf</a></p><p>10.<a href="https://cs231n.github.io/">https://cs231n.github.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1c4c1d44fa2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/inside-convolutional-neural-network-e1c4c1d44fa2">Inside Convolutional Neural Networks</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[Designing a LSTM!!!]]></title>
            <link>https://dhakal-bek.medium.com/designing-a-lstm-c64c0a642e09?source=rss-4d82954e65ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/c64c0a642e09</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[thinking-machine]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bibek Dhakal]]></dc:creator>
            <pubDate>Tue, 26 May 2020 08:23:12 GMT</pubDate>
            <atom:updated>2020-08-24T09:34:16.287Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing a LSTM Model!!!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vabl9Ud-kypieNmWhFIP_A.jpeg" /><figcaption>Tilicho. <strong>Image by author</strong></figcaption></figure><p><strong>Long Short Term Memory</strong> Network is capable of learning long term dependencies. Mostly used for solving <em>time-series</em> data, they are capable of learning the patterns from the previous inputs and predicting future.</p><p>In Neural Network features are learned from data. <strong>LSTM</strong> also does the same. Designing the <strong>LSTM</strong> layer might be difficult some time. While designing it for the first time, we may stick in choosing the right number of layers, sizes, etc. While using <strong>LSTM</strong> for stock price prediction I really got difficult in designing it. Sometime my model used to over fit and sometime it under fit.</p><p>Designing a good model usually involves a lot of trial and error. I have written here, from my experience in designing a <strong>LSTM</strong> for the first time and how did I made it.</p><p><strong>So how do we design a model???</strong></p><p><em>Answer</em>:<em> </em>We don’t.</p><p>We pick something that works in similar to our model and use it. But this approach works in many cases, but not applicable in all cases, especially like if we are working on a <em>unique problem </em>or <em>doing bleeding-edge research.</em></p><p>We can borrow ideas from successful models while designing our own model.</p><p><strong>How do we choose many layers and units??</strong></p><p><em>Answer:</em> At most of the time, beginning with a small model and gradually increasing the model size will be easier for us to build. By increasing the model size means adding layers and increasing the number of units.</p><p>Yeah, we can start with a large model and go on decreasing, but how big do we start?</p><p>It is usually better to go deeper than taller in the sense of a model because it’s very hard to optimize a very tall and skinny network.</p><p><strong>How to choose the activation function?</strong></p><p><em>Answer:</em> Choosing Relu except for the output layer might be easier.</p><p><strong>And what about regularization?</strong></p><p><strong>Answer:</strong> Mostly, we should use L2 regularization at first and start with it.</p><p><strong>Batch size??</strong></p><p><em>Answer:</em> In most of the other blogs, they have written that batch size of 32 is good in a neural network but if the gradient is too noisy, we need to use a large number of batches.</p><p>If we get stuck in local minima or out of memory, then we use smaller batches.</p><p><strong>Epochs??</strong></p><p><strong>Answer:</strong> One epoch is when an entire dataset is passed forward and backward through a neural network. On choosing epoch, we can select a large number of epoch i.e. &gt;&gt;100 and use <a href="https://machinelearningmastery.com/early-stopping-to-avoid-overtraining-neural-network-models/"><strong>early stopping.</strong></a></p><p>While using early stopping, we can stop the model and prevent from overfit. Early stopping is used before fitting a model through epoch.</p><p>These are only some of the ways of designing an LSTM network for the first time and stuck in starting with it. There can be many other ways of designing a network and these are only from my experience.</p><p>Thanks for reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZf0GntBDYt_lGZW5pENQQ.jpeg" /><figcaption>Tilicho Lake(4919m). <strong>Image by author</strong></figcaption></figure><p>Code with implementation of LSTM model click <a href="https://github.com/Dhakal29/NepalTelecom-Stock-Price-Prediction">here</a>.</p><p><em>References:</em></p><ol><li><a href="https://faroit.com/keras-docs/1.0.1/getting-started/sequential-model-guide/#the-merge-layer">https://faroit.com/keras-docs/1.0.1/getting-started/sequential-model-guide/#the-merge-layer</a></li><li><a href="https://www.kdnuggets.com/2018/11/keras-long-short-term-memory-lstm-model-predict-stock-prices.html">https://www.kdnuggets.com/2018/11/keras-long-short-term-memory-lstm-model-predict-stock-prices.html</a></li><li><a href="https://machinelearningmastery.com/diagnose-overfitting-underfitting-lstm-models/">https://machinelearningmastery.com/diagnose-overfitting-underfitting-lstm-models/</a></li><li><a href="https://www.analyticsvidhya.com/blog/2018/04/fundamentals-deep-learning-regularization-techniques/">https://www.analyticsvidhya.com/blog/2018/04/fundamentals-deep-learning-regularization-techniques/</a></li><li><a href="https://www.youtube.com/watch?v=JEWzWv1fBFQ">https://www.youtube.com/watch?v=JEWzWv1fBFQ</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c64c0a642e09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering in Unsupervised Categorical data]]></title>
            <link>https://dhakal-bek.medium.com/clustering-in-unsupervised-categorical-data-7f10db4bb9fc?source=rss-4d82954e65ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f10db4bb9fc</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kdnuggets]]></category>
            <dc:creator><![CDATA[Bibek Dhakal]]></dc:creator>
            <pubDate>Wed, 20 May 2020 12:51:13 GMT</pubDate>
            <atom:updated>2020-08-24T09:33:18.459Z</atom:updated>
            <content:encoded><![CDATA[<h3>K-Means in categorical data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJnIAFJ_HN53M6LQ_2_JcQ.jpeg" /><figcaption>Source:<a href="https://www.reddit.com/r/datascience/comments/d6buto/kmeans_be_like_mine_mine_mine/">https://www.reddit.com/r/datascience/comments/d6buto/kmeans_be_like_mine_mine_mine/</a></figcaption></figure><p>Like supervised data can be used for <strong>Predictive </strong>modelling, unsupervised data are mostly used for grouping together with similar features. Data with numerals are easier to handle. They can be used with label encoding or leaving as it is for the future. But with Categorical data!!!</p><p>Well, categorical data are the types of data which are present in categories like we say Name, Food Place, Group etc.</p><p>Let us take with an example of handling categorical data and clustering them using the<strong> K-Means </strong>algorithm.</p><p>We have got a dataset of a hospital with their attributes like Age, Sex, Final Diagnosis and Place where they come from.</p><p><strong>Let us import essential libraries first as below:</strong></p><pre><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>researchpy</strong> <strong>as</strong> <strong>rp</strong><br><strong>import</strong> <strong>seaborn</strong> <strong>as</strong> <strong>sns</strong><br><strong>from</strong> <strong>sklearn.datasets</strong> <strong>import</strong> make_blobs <br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br><strong>from</strong> <strong>scipy</strong> <strong>import</strong> stats<br>%matplotlib inline<br><strong>import</strong> <strong>warnings</strong><br>warnings.filterwarnings(&quot;ignore&quot;)</pre><p>After importing libraries in python, we are gonna read the .csv files from pandas.</p><pre>nch = pd.read_csv(&quot;final.csv&quot;)</pre><p>After reading the csv files we are gonna remove the duplicated files as to not keep the same files in our dataset.</p><pre>nch.drop_duplicates(keep=<strong>False</strong>)<br>nch.drop_duplicates(keep=<strong>False</strong>, inplace=<strong>True</strong>)</pre><p>After dropping duplicated data from our set, lets us <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html">Label Encode</a> our dataset for further process. We need to change our categorical to numerical for clustering as K-Means doesn’t work with categorical data.</p><p>Here, we are using Sklearn library to encode our data.</p><pre><strong>from</strong> <strong>sklearn.preprocessing</strong> <strong>import</strong> LabelEncoder <em>#changing to numerical by label encoder</em><br>number = LabelEncoder()<br>nch[&quot;Sex&quot;] = number.fit_transform(nch[&quot;Sex&quot;].astype(&#39;str&#39;))<br>nch[&quot;Place&quot;] = number.fit_transform(nch[&quot;Place&quot;].astype(&#39;str&#39;))<br>nch[&quot;FinalDiagnosis&quot;] = number.fit_transform(nch[&quot;FinalDiagnosis&quot;].astype(&#39;str&#39;))</pre><p>Hurrah, we have changed to numerical type. We need to check them whether they are in numerical or not. If not then, using <strong>pandas</strong> libraries we are changing their properties to numeric.</p><pre>nch.Age = pd.to_numeric(nch.Age)  <em>#change to numeric type data</em><br>nch.Sex = pd.to_numeric(nch.Sex)<br>nch.Place = pd.to_numeric(nch.Place)<br>nch.FinalDiagnosis = pd.to_numeric(nch.FinalDiagnosis)</pre><p>We have got our dataset in numeric but still we cant apply algorithm because changing to label encoding data and applying K-Means may not give good result so we are again changing them to One-Hot encoded data with <a href="https://machinelearningmastery.com/why-one-hot-encode-data-in-machine-learning/">One-Hot Encoding</a> method.</p><pre>nch_onehot = nch.copy()<br>nch_onehot = pd.get_dummies(nch_onehot, columns = [&#39;Sex&#39;,&#39;FinalDiagnosis&#39;,&#39;Place&#39;], prefix = [&#39;Sex&#39;,&#39;FinalDiagnosis&#39;,&#39;Place&#39;] )</pre><p>When we apply one-hot encoding, our dataset attributes increased upto 42.But before moving to think about it, let us use scaling method(<a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html">Standard Scaling</a>) to scale our data.</p><pre><strong>from</strong> <strong>sklearn.preprocessing</strong> <strong>import</strong> StandardScaler<br>SS = StandardScaler()<br>Nchs = SS.fit_transform(nch_onehot)</pre><p>Now we need to reduce the dimension of our data, so we are applying PCA technique.</p><pre><em>#fitting the pca algorithm with our data</em><br>pca=PCA().fit(Nchs)<br><em>#plotting the cumulative summation of the explained variance</em><br>plt.figure()<br>plt.plot(np.cumsum(pca.explained_variance_ratio_))<br>plt.xlabel(&#39;Number of components&#39;)<br>plt.ylabel(&#39;Variance <strong>% f</strong>or each components&#39;)<br>plt.title(&#39;Explained variance&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*vVis-17hKskrmOuXbY8QMw.png" /><figcaption>PCA visualization</figcaption></figure><p>From above figure it seems that our components bends after approx. 37 so we select nearly 37 for 100% variance data.</p><pre>pca=PCA(n_components=37)<br>pca.fit(Nchs)</pre><pre>x_pca=pca.transform(Nchs)</pre><p>Now comes the last part. We are applying K-Means algorithm to our data. But how to determine K value!! It is easy. We will use <strong>Elbow method</strong> to determine the value of K. We will visualize it and see from where it forms an elbow.</p><pre><strong>from</strong> <strong>matplotlib</strong> <strong>import</strong> pyplot <strong>as</strong> plt<br><strong>from</strong> <strong>sklearn.datasets.samples_generator</strong> <strong>import</strong> make_blobs<br><strong>from</strong> <strong>sklearn.cluster</strong> <strong>import</strong> KMeans<br>Sum_of_squared_distances = []<br>K = range(1,15)<br><strong>for</strong> k <strong>in</strong> K:<br>    km = KMeans(n_clusters=k)<br>    km = km.fit(x_pca)<br>    Sum_of_squared_distances.append(km.inertia_)</pre><pre>#Visualing the plot<br>plt.plot(K, Sum_of_squared_distances, &#39;bx-&#39;)<br>plt.xlabel(&#39;k&#39;)<br>plt.ylabel(&#39;Sum_of_squared_distances&#39;)<br>plt.title(&#39;Elbow Method For Optimal k&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*41ORDMreRQPrxLimSL6u5A.png" /><figcaption>Fig: Elbow Method</figcaption></figure><p>From about K =2, it has formed an elbow. So we are taking k=2 for our K-Means clustering.</p><pre>kmeans = KMeans(n_clusters=2, init=&#39;k-means++&#39;, n_init=10, max_iter=1000, tol=0.0001, precompute_distances=&#39;auto&#39;, verbose=0, random_state=<strong>None</strong>, copy_x=<strong>True</strong>, n_jobs=<strong>None</strong>, algorithm=&#39;auto&#39;)<br>y_kmeans=kmeans.fit_predict(x_pca)</pre><pre>#Plotting through K-Means</pre><pre>plt.scatter(x_pca[y_kmeans==0,0],x_pca[y_kmeans==0,1],s=100,c=&#39;red&#39;,label=&#39;Cluster1&#39;)<br>plt.scatter(x_pca[y_kmeans==1,0],x_pca[y_kmeans==1,1],s=100,c=&#39;blue&#39;,label=&#39;Cluster2&#39;)<br>plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=300,c=&#39;yellow&#39;,label=&#39;Centroids&#39;)<br>plt.title(&#39;Clusters of data&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*BgZ5KZJY3s6Ct6qJBoAmeQ.png" /><figcaption>Fig:K-Means with K=2</figcaption></figure><p>In this way, we can work with the categorical data for clustering technique.</p><p>Github codes are available <a href="https://github.com/Dhakal29/ClusteringHospitalData">here</a>.</p><p><em>References</em>:</p><ol><li><a href="https://www.analyticsvidhya.com/blog/2016/11/an-introduction-to-clustering-and-different-methods-of-clustering/">https://www.analyticsvidhya.com/blog/2016/11/an-introduction-to-clustering-and-different-methods-of-clustering/</a></li><li><a href="https://www.youtube.com/watch?v=4b5d3muPQmA">https://www.youtube.com/watch?v=4b5d3muPQmA</a></li><li><a href="https://en.wikipedia.org/wiki/Cluster_analysis">https://en.wikipedia.org/wiki/Cluster_analysis</a></li><li><a href="https://www.datacamp.com/community/tutorials/categorical-data">https://www.datacamp.com/community/tutorials/categorical-data</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f10db4bb9fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>