<?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 Eyup Gulsun on Medium]]></title>
        <description><![CDATA[Stories by Eyup Gulsun on Medium]]></description>
        <link>https://medium.com/@egx21?source=rss-10079377bb2f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VT_puqFklFs-2dqlvKzzhg@2x.jpeg</url>
            <title>Stories by Eyup Gulsun on Medium</title>
            <link>https://medium.com/@egx21?source=rss-10079377bb2f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:09:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@egx21/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[A finance strategy (CPPI), implemented on Streamlit/Python, deployed on AWS EC2]]></title>
            <link>https://egx21.medium.com/a-finance-strategy-cppi-implemented-on-streamlit-python-deployed-on-aws-ec2-418f16153fe6?source=rss-10079377bb2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/418f16153fe6</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[cppi]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[insurance]]></category>
            <dc:creator><![CDATA[Eyup Gulsun]]></dc:creator>
            <pubDate>Tue, 08 Dec 2020 21:33:29 GMT</pubDate>
            <atom:updated>2020-12-14T18:02:02.490Z</atom:updated>
            <content:encoded><![CDATA[<h4>np.array([Finance, Python, Streamlit, Cloud Platform]) == <a href="http://18.219.211.47:8501/">http://18.219.211.47:8501/</a></h4><h4>The journey of building a financial web app…</h4><p>In this article, I would like to show you how to design a CPPI (Constant proportion portfolio investment) strategy and publish it on the Internet. The result is <a href="http://18.219.211.47:8501/">http://18.219.211.47:8501/</a> (much more fun if you open the link on a big screen rather in a mobile browser)</p><p>Here are the steps.</p><p>First, let’s remember what CPPI is.</p><p>DIVERSIFICATION allows you to eliminate specific or idiosyncratic risks. It cannot help you deal with systematic risk as in 2008 crisis, when systematic risk impacted all the assets simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*P671-ng1jpmgddcMKGO5Ig.jpeg" /><figcaption>The Bermuda Triangle of Investing</figcaption></figure><p>HEDGING, as an alternative, helps you with systematic risks but it is purely symmetric: you get protection on the downside only if you give up on the upside proportionately. Not very attractive…</p><p>CPPI <em>Insurance Strategy</em> gives you downside protection but offer <strong>much more</strong> upside potential by dynamic hedging nature. It is all about allocating to a risky asset in a multiple of the difference between asset value and a given floor, and then reducing the risky allocation if/when getting close to the floor.</p><p>The code below is a step-by-step implementation of CPPI. I agree a vectorized-implement code would be more efficient but also equally hard to understand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43e29c34460917d5a4ec93caa86b6761/href">https://medium.com/media/43e29c34460917d5a4ec93caa86b6761/href</a></iframe><p>Below show the benefit of CPPI over fully invested in Turkish equity indices. As you can clearly see, CPPI protects the investment in large drawdowns whereas it provides quite a lot of upside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zp5Qgl5stiIJJB8rCmsKOA.png" /><figcaption>CPPI Implementation on BIST 100 index</figcaption></figure><p>Also, if you compare the risk parameters of two portfolios, you can clearly see how Sharpe ratio, VaR and Drawdown Ratios of CPPI portfolio show huge improvements over the risky portfolio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHNbr7posLBTOrwkLOFUWQ.png" /></figure><p>Let’s also look at the performance of another index, the transportation index, with and without CPPI strategy below. Wow! Such a big protection in CPPI portfolio!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gIzMWy1TvNK3YyBwVtncMQ.png" /></figure><p>In the execution part, I implemented CPPI in nonparametric and parametric ways using several sector indices. I also included a random walk path to the assets using Geometric Brownian Motion. All parameterized!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnqoEwVVp7gMpILV9T70dQ.png" /><figcaption>Snapshot of the app</figcaption></figure><p>To make the app online and web friendly, I used Streamlit library of Python (<a href="https://www.streamlit.io/">https://www.streamlit.io/</a>) . Definitely worth checking out!</p><p>Below is a shortened code snippet with Streamlit code, but you can fork the whole code from my github account: <a href="https://github.com/deimosnphobos/cppi_strategy">https://github.com/deimosnphobos/cppi_strategy</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1fda10ee1d93c1da3f349ee94c08b49/href">https://medium.com/media/e1fda10ee1d93c1da3f349ee94c08b49/href</a></iframe><p>Final task was to deploy it on a Cloud Application Platform. I tried <a href="https://www.heroku.com/">Heroku: Cloud Application Platform</a> first, but somehow I couldn’t be able to run it smoothly -sometimes it worked, sometimes not. So I switched to Amazon Elastic Compute Cloud (<a href="https://aws.amazon.com/ec2/">Amazon EC2 - Amazon AWS</a>). It was much harder to configure than Heroku, but just did what it was supposed to do!</p><p><a href="https://aws.amazon.com/ec2/?ec2-whats-new.sort-by=item.additionalFields.postDateTime&amp;ec2-whats-new.sort-order=desc">Amazon EC2</a></p><p>The result is at <a href="http://18.219.211.47:8501/">http://18.219.211.47:8501/</a>. Please feel free to play with it, and let me know if you have any questions about it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=418f16153fe6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Which one is your volatility — Constant, Local or Stochastic?]]></title>
            <link>https://medium.com/data-science/which-one-is-your-volatility-constant-local-or-stochastic-61508ef560c1?source=rss-10079377bb2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/61508ef560c1</guid>
            <category><![CDATA[volatility-surface]]></category>
            <category><![CDATA[local-volatility]]></category>
            <category><![CDATA[stochastic-volatility]]></category>
            <category><![CDATA[brownian-motion]]></category>
            <category><![CDATA[heston]]></category>
            <dc:creator><![CDATA[Eyup Gulsun]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 08:08:26 GMT</pubDate>
            <atom:updated>2020-07-13T13:51:17.259Z</atom:updated>
            <content:encoded><![CDATA[<h3>Which one is your volatility — Constant, Local or Stochastic?</h3><h4>Analyzing the path of EURUSD derived from the market vol surface by using the Heston Model</h4><p>There are three main volatility models in the finance: constant volatility, local volatility and stochastic volatility models.</p><p>Before the stock market crash of 1987, the Black-Scholes (B-S) model which was built on geometric Brownian motion (GBM) with <strong>constant volatility</strong> and drift was the dominant model. In this model, stock price is the only source of randomness and it can be hedged with the underlying stock with a return distribution as log-normal. In the B-S model, the stock price S is described by the following stochastic differential equation (SDE), where W is a standard Brownian motion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*5D8xK8Tiz6v1CpvJB9cH8Q.png" /><figcaption>where μ (return, drift, or riskless rate) and σ ( volatility) are constants.</figcaption></figure><p>The above Stochastic Differential Equation (SDE) has the following analytical solution (under Itô’s interpretation):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*NXQU6FONZKC5wzP6fvWXvw.png" /></figure><p>After the crash of 1987, the word ‘skew’, which used to mean happiness or when something good has happened, meant something completely different: ‘skew’ indicates that very small and very large returns are realized more often than the normal distribution would imply. So, traders started to price especially lower strike options with higher volatilities (check out the implied vol curve pre- and post- 1987). Supply and demand for different options also played an important role in shaping the volatility curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*OFpdupUCLHbaOLjgNryMFA.png" /></figure><p>Local Volatility (LV) model, which is actually a simple extension of B-S model, addressed the need to incorporate the skewness into the pricing model and hence implies a non-normal distribution. In LV models, the volatility of the underlying, called as ‘instantaneous volatility,’ is modeled as a deterministic function of time t, and the time-t value of the underlying asset (S):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*MCJA_Ex6S89SxH_VH3PIOA.png" /></figure><p>This is a very intuitive formula just by thinking of the fact that <em>volatility can be viewed as an asset itself</em>. For example, VIX index, a real-time market index that represents the market’s expectation of 30-day forward-looking volatility derived from the price inputs of the S&amp;P 500 index options, can be traded through derivatives. Check out the non-constant nature of the VIX index:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMHouTonIq83vuGWhJn3kQ.png" /><figcaption>Path of S$P 500 and its volatility, VIX</figcaption></figure><p>The implied volatility surface can be transformed to LV surface, which is known as calibration of LV model of Dupire. Dupire (1994) shows that there exists a model that can match option prices quoted on the market and that there is an explicit formula for how to construct this model from observed options’ prices under the assumption that they can be interpolated across continuous strikes and maturities. (At the time Dupire actually didn’t think of local volatility as a realistic model for the evolution of actual volatility.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IowJpfrBL-Y45DnJWWVZXg.png" /></figure><p>Since the asset price is driven by a single Brownian motion, every payoff is a result of a unique self-financing replicating portfolio consisting of cash and the underlying asset, and that is to say that its price is <em>uniquely</em> defined as the initial value of the replicating portfolio (market completeness). The advantage of being complete means that derivatives written on S can be hedged perfectly. While BS and LV models are complete, stochastic volatility models are not. On the other hand, while market completeness is very convenient from a theoretical point of view, it is not necessarily a realistic property of financial markets, as we all can deal with derivatives, right?</p><p>Anyways. If we compare implied volatility surface with local volatility surface, we can see that the fit is pretty good. Actually, the LV models, unlike B-S model, are very good and sometimes even perfect at fitting arbitrage-free surface of implied volatilities, i.e. ‘smile’, via Dupire’s formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tG9n0A2Ugdq4_CXiQwZGEg.png" /><figcaption>Sources: The graphs on the left: Implied and Local Volatility Surfaces for South African Index and Foreign Exchange Options, Journal of Risk and Financial Management ISSN 1911–8074. The graphs on the right: Bloomberg</figcaption></figure><p>However, LV model has a major defect: The model only uses today prices and makes no assumptions about their behavior over time! Even though it fits the value of the smile as of today, the model gives an almost constant smile for long maturities, leading to a flattening of the forward smile (i.e. no smile in the future)! How absurd! Therefore, it leads to unreasonable skew dynamics and underestimates the volatility of volatility. This is very unrealistic especially for exotic options which depend on the forward smile such as cliquet options and other forward starting options.</p><p>Moreover, LV models are not good bad at providing stability and they may need to be re-calibrated frequently, such as hourly !!</p><p>Nonetheless, with some adjustments made to local volatility prices, especially adding some jumps to the model to capture the complex dynamics of stock price processes, these models can be used to price several barrier options.</p><p>As an upgrade/alternative to LV model, a <strong>stochastic volatility</strong> (SV) model can produce a more realistic forward volatility surface, where the smile is almost self similar, compared to LV models which flatten out the forward volatility curve and vanish the smile. LV models assume that skew in the future will be what we see the forward skew today in local vol, whereas SV models assume the skew in the future is similar to the skew today. That’s why SV model is likely to overprice options, whereas the LV and BS models tends to underestimate options.</p><p>In SV models, the asset price and its volatility are both assumed to be random processes and can change over time, hence it gives more realistic dynamics of the volatility smile. In an SV model, promoted in the late 1980s by Hull and White, the volatility of the underlying is modeled as a deterministic function of some auxiliary process, which is usually modeled as a diffusion.</p><p>The most well-known and important stochastic volatility model is the Heston model. It is a two-factor model and assumes separate dynamics for both the stock price and instantaneous volatility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*3Vh_Uq5wEzNVpK5RFRJMsg.png" /></figure><p>As a super simple example, the below code shows a simple application of Heston model to EURUSD to find the currency path in 1M, 2M, and 3M’s time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ya25VXgNPqES25yuj_SaDg.png" /></figure><p>If you compare the results with the Bloomberg forward quotes below, you can see how our results match those quotes given below perfectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*pjfxO7Zx0gpmv-w4L6zFuw.png" /></figure><p>Also now we have the path of the currency in each simulation and we can price our exotic options based on these paths (below graphs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlT5dQqmhfGSTQSyHjP5-Q.png" /></figure><p>In the above example, Heston model parameters were determined by calibrating to the market observed implied volatility smile for European options (surface given in the below graph). Ok, I admit I actually didn’t calculate them by using tedious formulas but got the recalibrated parameters directly from Bloomberg to save some time:)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*ZQet1Kv9RPc0Nn78U6hMlw.png" /><figcaption>Market observed implied volatility surface for European options in EURUSD (Source: Bloomberg)</figcaption></figure><p>SV models can produce rich spot-vol dynamics, such as large negative short term forward skews or large forward smile curvatures. However, they also have some drawbacks. They are harder to calibrate than local vol models, which is why I took them directly form Bloomnberg, and they may sometimes not exhibit enough smile for options with short maturities. And for products which depend only on terminal distributions, the fit of the volatility surface may be poor. Hedging ratios in SV models also depend strongly on the parameters and so they are sensitive with respect to changes in parameters. A simpler model can even do better since its parameters can be calibrated more efficiently and robust while hedging errors can get “averaged out”.</p><p>There are other models to overcome these shortcomings. One of them is local-stochastic volatility (LSV) models, which try to get the positive sides of local and stochastic volatility models: They model the volatility as a function of time t and the underlying asset S with additional stochastic process. There are also Path-dependent volatility (PDV) models which tries to combine benefits from both LV and SV by trying to fit the market smile and produce a wide variety of joint spot-vol dynamics at the same time.</p><p>Another alternative is using ARCH/GARCH models. Even though ARCH/GARCH represent discrete-time models for stock returns, whereas SV models are continuous-time models, discrete-time models for stock returns attract quite a lot of attention in econometrics literature and offer robust results. ARCH/GARCH can capture tail risks, volatility clustering and dependence without correlation.</p><p>All in all, it can be concluded that there is no “right” model but “suitable” model. Your choice of a vol model depends on what you are gonna use it for. For example, if you want to price exotic options, go with the SV models. For less complicated and exotic products, local vol models can perform better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61508ef560c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/which-one-is-your-volatility-constant-local-or-stochastic-61508ef560c1">Which one is your volatility — Constant, Local or Stochastic?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A classic bedtime story: Cinderella of Neural Networks]]></title>
            <link>https://medium.com/data-science/a-classic-bedtime-story-cinderella-of-neural-networks-fa9a3414286f?source=rss-10079377bb2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa9a3414286f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[stochastic-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Eyup Gulsun]]></dc:creator>
            <pubDate>Fri, 27 Sep 2019 19:12:26 GMT</pubDate>
            <atom:updated>2019-09-28T16:28:53.372Z</atom:updated>
            <content:encoded><![CDATA[<h4>Endgame for “AI Winter”</h4><h4>How a competition, ImageNet, along with a noisy algorithm, Stochastic Gradient Descent, changed the fate of AI?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*HrSR_lXcoM4QdaRnnh50Sg.png" /><figcaption>Picture from The Elders Scroll | Skyrim</figcaption></figure><p>In the early 1980s, <em>Winter was coming</em> for Artificial Intelligence (AI) with a period of reduced funding and interest in AI research, which will later be called the “AI Winter”!</p><p>During this cold-weather period which lasted until the mid-2000s, almost no research paper on Neural Nets was published because of the lost interest in the field. The reason was simple: no effective algorithms had been put forward against the traditional ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*WJaf5nv_7vdtiK3RT72aEA.jpeg" /></figure><p>AI’s misery changed dramatically when Geoffrey Hinton, you can call him as the godfather of Deep Learning, and his team submitted their research in a famous object recognition competition called ImageNet in 2012. <em>“This ImageNet 2012 event was definitely what triggered the big explosion of AI today”</em> quoted Matthew Zeiler, CEO of Clarifai.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*UbuCCvLbt-Zdf6yvzPgY_w.jpeg" /><figcaption>Picture Source: ImageNet</figcaption></figure><p>Before Geoffrey’s work, accuracy of object recognition research under algorithms had been pretty poor with classification error rates more than 25%, while error rate of human eye performance around is 5%. But as the team of Geoffrey implemented neural networks beautifully, they managed to reduce the error rate dramatically by more than 40 percent !! Following his steps, deep learning has been so intensely used such that algorithms yielded much lower error rates than human eyes only 2 years later!! Currently, in object and speech recognition areas, almost all research is performed by AI, a sub field of deep learning.</p><p>I should also mention that, while moving away from ‘AI Winter’ period into glorious ‘Great AI Awakening’ period, AI received substantial support from the improvement in GPU (careful, not CPU) computing, thanks to NVIDIA, and availability of massive data sets, thanks to all of us by creating more than 2.5 quintillion ( 10¹⁸) bytes of data every day.</p><p>Let’s turn our attention back to the back-bone algorithm of Deep Learning. As you know, algorithms try to optimize problems by minimizing the error functions, generally known as cost functions. Efficient algorithms complete in nanoseconds, others may need to run for many hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*eqtOmW8OxOFcyYfWkHt8Dw.jpeg" /></figure><p>Machine Learning algorithms require efficient optimization techniques to solve either convex problems or non-convex ones. Minimizing the error can be performed best in convex functions, because wherever your starting point is, you will always find the global minimum point! That’s why we love SVM (Support Vector Machines) or other linear functions because they have convex loss functions and you are guaranteed to find the global minimum!!</p><p>But, in real life, optimization functions are generally uglier. They live in non-convex spaces, which consist of many local minima (“valleys”) and maxima (“hills”). Neural Networks are no exception and even worse!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*1lyC_JXnn2eVMqJ94tRlTQ.png" /><figcaption>“Visualizing the Loss Landscape of Neural Nets”, Hao Li et al., 2018</figcaption></figure><p>Neural Networks have 1,000+ of local minima, so you will, for sure, be trapped into one of those and will never find a global minimum! (Tell me if you disagree after peaking at the graph on the left which shows only a small section of a nonconvex function.) Depending on where your “initialization” point is, you will always end up in a different local minimum (this issue is generally dealt with by random initializing, or perhaps adding some Gaussian noise). The reason why no one really liked Neural Networks was due to its highly complex nature in the absence of an affordable algorithm.</p><p>In the quest of a reasonable local minimum, researchers first used <em>aggressive</em> methods, like Gradient Descent or even faster <em>approximate</em> Newton or <em>approximate</em> Hessian methods (as the data size and dimensionality increase, convex optimization methods are adversely affected. For example, Hessian-based approaches which optimally handle convex optimization problems do not scale up and so approximations are required [Martens et al., 2012]). These methods are so <strong>perfect</strong> to find a minimum that they find the “closest” hole instantly. Although this sounds perfect, it is actually not! - closest holes unlikely have the ideal minimum, and you need to look for somewhere further away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*fZjielcteQnBPHdkEhZFAw.jpeg" /></figure><p>Also, even if you manage to look further away, you need to look for wide valleys rather than tight depths. A deep hole found while using train data may not be that deep while using test data. However wide valleys are likely to be there under both train and test data sets.</p><p>Which algorithm is capable of avoiding the nearest hole and settle in the wide valley space? This is exactly what SGD is actually capable of! (even though it took a lot of time for people to find this out). Who would think that the algorithm once labelled as inefficient and redundant will turn out to be the key optimization tool of almost all deep learning models? Fantastic!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*ighvUAMrSjIS0mFq.png" /><figcaption>picture source : <a href="https://wikidocs.net/3413">https://wikidocs.net/3413</a></figcaption></figure><p>How did this happen? How “Stochastic” Gradient Descent (SGD) approach works as a very effective technique for training deep neural networks with linear computational complexity in the size of the dataset, given its very noisy and random nature?</p><p>SGD is very noisy compared to Gradient Descent (GD) because while GD uses the entire data set to calculate its path (gradient), SGD uses only one single example, a batch size of 1 which is chosen at random, per iteration; therefore, it follows a random path, but ultimately in the right direction. Randomness means it doesn’t converge to the nearest hole but only settle in large valleys! This is a quality that many other algorithms do not possess!</p><p>Well, in our fairy tale, before the wheel bend, and the story end, I should tell you that, our main character, SGD, has two main limitations due to learning rate (step size): if you choose it too large, then the learning trajectory leads to horrible situations; if chosen as too small, its convergence takes ages. So, be wise to choose the right step size. You can either use one of the several variants of SGD, such as Momentum, Averaging, Implicit updates (ISGD), AdaGrad, Adam, etc., or listen to my suggestion which is to take large steps at first, and when it starts to jump back and forth, start lowering your learning rate, i.e. take smaller steps. That’s it!</p><p>Now the bridge was mended and my story’s ended.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa9a3414286f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-classic-bedtime-story-cinderella-of-neural-networks-fa9a3414286f">A classic bedtime story: Cinderella of 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[Beauty of Karger’s algorithm]]></title>
            <link>https://medium.com/data-science/beauty-of-kargers-algorithm-6de7e923874a?source=rss-10079377bb2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6de7e923874a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[karger-algorithm]]></category>
            <category><![CDATA[monte-carlo]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Eyup Gulsun]]></dc:creator>
            <pubDate>Fri, 13 Sep 2019 14:51:20 GMT</pubDate>
            <atom:updated>2019-09-18T03:17:33.646Z</atom:updated>
            <content:encoded><![CDATA[<h4>Karger’s algorithm back in town (with Python code)</h4><h3>Beauty of Karger’s algorithm: Randomness of Monte Carlo in Graphs</h3><h4>Divide and conquer! A widely used strategy for years in history. But how to divide? Generally, most intuitive way is to look for segments with lowest levels of affinity or links within systems, networks, and even for populations! So, let’s start!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*dQuD6TxbKMrkSABsi8n7qg.jpeg" /></figure><p>Are you ready for dividing and slicing? Let’s start with networks. We like dense networks, otherwise even if a very single edge or wire is disconnected, a large portion of the network can be down <em>— a situation definetely not desired ! </em>There are generally clusters, unevenly distributed segments, within networks. While dealing with separation of these segments or “clusters” efficiently, we look for edges between them such that the number of edges are minimum.</p><figure><img alt="https://conceptartempire.com/polygon-mesh/" src="https://cdn-images-1.medium.com/max/510/1*8eCkY0_fB3W4YcnJYC41jQ.png" /><figcaption><a href="https://conceptartempire.com/polygon-mesh/">Polygon Mesh</a></figcaption></figure><p>We can apply the same argument to other fields, such as ‘Image Segmentation’. If you want to break an image into segments, easiest way is to break links with low affinity, i.e. minimum number of cuts. Think of A polygon mesh. A polygon mesh is the collection of vertices, edges, and faces<strong> </strong>that make up a 3D object. Breaking images links with low affinity can give you separate distinct images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*7HTYF8FLIPD3oLOlAa9Enw.png" /></figure><p>Also think of underground lines! So many nodes (stations) and edges (railways)! If you wanna split the tube system into two, what will be the minimum number of lines to be disconnected?</p><p>As you see, there are many real-life min-cut issues. How do we deal with them? A traditional algorithm is ‘max-flow min-cut’. It is deterministic, which means when we apply this algo, we get the right min-cut 100% of the time! No failure probability! Downside is that 100% guarantee comes with a cost: it is very slow. The runtime at best is O(number of vertices * number of edges squared, so roughly an order of n³ time complexity.</p><p>There are many clever algos, which are very fast with a runtime of O(n²), but none of them, even superior ones, in my opinion, is as elegantly designed as Karger’s algorithm, which use ‘random sampling’ in a graph problem!!</p><p>If you are familiar with the Quick Sort algorithm, you already know the effectiveness of random sampling in sorting and searching. A PhD student in early 90’s, David Karger, devised the Random Contraction Algorithm for min-cut case by using randomness in graph problems. As being a Monte Carlo algorithm, Krager’s Algorithm offers a solution with a certain (albeit small) probability with a lot faster approach than max-flow min-cut algorithm.</p><figure><img alt="http://tcs.nju.edu.cn/wiki/index.php/%E9%AB%98%E7%BA%A7%E7%AE%97%E6%B3%95_(Fall_2019)/Min-Cut_and_Max-Cut" src="https://cdn-images-1.medium.com/max/1024/1*21dR1rYWLA1Yt1QA32FhYQ.png" /><figcaption><a href="http://tcs.nju.edu.cn/wiki/index.php/%E9%AB%98%E7%BA%A7%E7%AE%97%E6%B3%95_(Fall_2019)/Min-Cut_and_Max-Cut"><em>Picturing contraction of edges</em></a></figcaption></figure><p>So, say we have an undirected graph G = (V, E). In order to cut a connected graph G into two connected subgraphs in as few cuts as possible, the algo basically uses <strong>contraction </strong>of an edge. To implement it, one should pull together two vertices on two sides of the edge.</p><p>We implement the algo in pseudo code as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5obgE9hL-Z90Aqq1HEi6xA.png" /></figure><p>Now comes the question:<em> What is the probability of success?</em></p><p>In a graph with n vertices, <strong>a single run </strong>of Karger’s algorithm gives the result with a success probability of 1 / (n choose 2) and a runtime of O(n²). Not bad, but one needs to be lucky to find the min cut edge in the first run.</p><p>The probability of success can be increased by doing <strong>multiple runs</strong>. If we run Karger’s algorithm <strong>n²</strong> times, the probability of failure that we don’t get a minimum cut is 1/e. A constant! It doesn’t depend on the number of vertices!</p><p>However, if we run Karger’s algorithm <strong>n² ln (n)</strong> times, which is regarded as the optimal value, then <strong>P(fail) &lt;= 1/n</strong>, and <strong>P(success) &gt;= 1–1/n</strong>, which means as you get bigger bigger graph , the probability of success of Karger’s algorithm gets better! So, in a graph with 50 nodes, if we run the algorithm around 10,000 times, the probability of success is 98% !!</p><p>Such a good success rate of 98% comes with a cost though. The running time is polynomial in n (the number of vertices) and m (the number of edges), which is pretty slow: O(n²m).</p><p>A slightly altered version, Karger-Stein algorithm, has twice the success probability as the original algorithm!!</p><p>Python code for Karger’s algo is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fee2b3350ebe6cd82aa00508bd341525/href">https://medium.com/media/fee2b3350ebe6cd82aa00508bd341525/href</a></iframe><p>By the way, if you want to learn a bit more, I recommend you watch the <a href="https://www.youtube.com/watch?v=c75gg0wicus&amp;t=18s">youtube video of Stanford Algorithms</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6de7e923874a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/beauty-of-kargers-algorithm-6de7e923874a">Beauty of Karger’s algorithm</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>