<?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 Marios Kokmotos on Medium]]></title>
        <description><![CDATA[Stories by Marios Kokmotos on Medium]]></description>
        <link>https://medium.com/@marioskokmotos2?source=rss-a988d8b4ddd3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*J7S0sVE8hk0fN_FoBvBPag.jpeg</url>
            <title>Stories by Marios Kokmotos on Medium</title>
            <link>https://medium.com/@marioskokmotos2?source=rss-a988d8b4ddd3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 07:50:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marioskokmotos2/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[The Travelling Salesman Problem — an implementation in Python]]></title>
            <link>https://medium.com/@marioskokmotos2/the-travelling-salesman-problem-an-implementation-in-python-d2b87e48b9d9?source=rss-a988d8b4ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2b87e48b9d9</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[travelling-salesman]]></category>
            <category><![CDATA[traveling-salesman]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Marios Kokmotos]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 20:18:15 GMT</pubDate>
            <atom:updated>2023-02-28T20:18:15.565Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Travelling Salesman Problem — an implementation in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kpIqMD3vNZZE8jdxN2PKHw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@drwmrk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Andrew Stutesman</a> on <a href="https://unsplash.com/s/photos/map?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>You find yourself in Central Europe in the 1800’s. You need to make a living by selling your goods (let’s say ceramic and metallic household goods). After having a good night’s rest at the ‘Feisty Goat’ guest house, you feed your horses and pack your things while planning your route. You need to travel to 12 cities through the summer in order to sell your goods and maximise your profit.</p><p>So, next stop…Tubingen…oh..wait! Is that so?</p><p>“Perhaps, Ulm first?”, you think to yourself. How would you make the best choice, travelling through every city only once, coming back to where you started, and all that by minimising the travelling distance? Your horses are not that young anymore…you need to take care of them.</p><h4>The problem</h4><p>This is a common setup of the<a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem"> <strong>Travelling Salesman Problem</strong></a> (or<strong> TSP</strong>). The Travelling Salesman Problem (TSP) is a classic optimization problem that has been around for centuries. At its core, the TSP is a simple problem: Given a list of cities and the distances between them, what is the shortest possible route that visits each city exactly once and returns to the starting point?</p><p>This problem might sound easy, but it quickly gets tricky when the number of cities increase. Imagine you’re a travelling salesman trying to visit 100 cities, there are 100! (that’s 100 factorial) possible routes to choose from. That’s a lot of possibilities to check, and the bigger the number of cities gets the bigger the number of routes gets.</p><p>The TSP was mathematically formulated in the 19th century by the Irish mathematician <a href="https://en.wikipedia.org/wiki/William_Rowan_Hamilton">William Rowan Hamilton</a> and by the British mathematician <a href="https://en.wikipedia.org/wiki/Thomas_Kirkman">Thomas Kirkman</a>. It is one of the most important problems in computer science and a well-known representative of the very elusive problem <a href="https://en.wikipedia.org/wiki/P_versus_NP_problem">P versus NP</a>.</p><p>The TSP has a wide range of modern applications, routing problems for logistic companies, bus routes and deliveries, airlines’ schedules and more. For example, in logistics and transportation, the TSP is used to plan delivery routes for trucks, buses, and even drones. This ensures that the routes are as efficient as possible and that the vehicles are used in the most optimal way. In scheduling, the TSP is used to schedule tasks on a machine, such as chip fabrication in computer manufacturing. It’s also a popular problem in the field of computational biology, where it’s used to model the folding of proteins.</p><h4>Complexity</h4><p>Complexity theory is the branch of computer science that deals with the study of problems that cannot be solved in a reasonable amount of time. The theory classifies problems into different categories, such as P, NP, NP-hard and NP-complete. The TSP falls into the category of NP-hard problems, which means that there is no known algorithm that can solve the problem in polynomial time (O(n^k)) for large values of n. These are problems that cannot be solved in a reasonable amount of time, even with the most powerful computers. The TSP is considered one of the most difficult problems in this class. So difficult that it’s used as a benchmark to test the performance of optimization algorithms. However, there are approximate algorithms that can find good solutions in a reasonable amount of time.</p><p>The complexity of the TSP comes from the fact that there are a lot of possible routes to consider, and checking each one of them is not feasible. Therefore, approximate algorithms are used to find good solutions in a reasonable amount of time. The most popular approximate algorithms for solving the TSP are the nearest neighbour algorithm, the simulated annealing algorithm and the genetic algorithm.</p><h3>Setup of our problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itTMKZ1oDj3rRTkBqYTmuw.png" /><figcaption>The <a href="https://en.wikipedia.org/wiki/Confederation_of_the_Rhine">Confederation of the Rhine</a>, a confederation of client states of the First French Empire, existed from 1806 to 1813. (Source Wikipedia, see therein “18th-century history of Germany”)</figcaption></figure><p>We find ourselves in the outskirts of Augsburg, Bavaria. A very pretty quiet town in the south just a bit away from the Alps. We have a list of cities we must visit: Munich, Stuttgart, Nuremberg, Leipzig, Dresden, Berlin, Hanover, Bremen, Hamburg, Cologne and Frankfurt (pretty much the whole circumference of modern-day Germany!).</p><h3>Solution and Implementation</h3><p><strong>Brute Force Algorithm</strong></p><p>Obviously, the first solution that comes to mind is the brute force one (usually the most inefficient). As the name suggests, we start attacking the problem straight away, we try all possible solutions and pick up the best one. The complexity of this approach is O(n!) since we can select the first city in n ways, the second one in (n-1) ways etc. This is tractable for small values of n, but quickly becomes computationally horrific!</p><p><strong>Nearest Neighbour Heuristic</strong></p><p>The nearest neighbour algorithm starts at a random city (for us the start is always Augsburg), and at each step it chooses the nearest unvisited city to visit next. This algorithm is simple to implement and can find good solutions quickly, but it’s not guaranteed to find the optimal solution.</p><p><strong>Dynamic Programming</strong></p><p>A more clever way to solve the problem, guaranteed to give an optimal solution is Dynamic Programming. However, this exact algorithm is quite slow for large values of n. Its time complexity is O(n² * 2^n). It also requires space of O(n²).</p><p><strong>Simulated Annealing</strong></p><p>Simulated annealing is a metaheuristic algorithm that is inspired by the process of annealing in metallurgy. The algorithm starts with a random solution and at each step, it makes small changes to the solution and accepts or rejects them based on a probability function. The probability of accepting a change decreases as the algorithm progresses, allowing it to escape local optima and find better solutions.</p><p><strong>Genetic Algorithms</strong></p><p>A Genetic algorithm is a metaheuristic inspired by the process of natural evolution. The algorithm starts with a population of potential solutions, and at each generation, it applies genetic operators such as selection, crossover, and mutation to create new solutions. The new solutions are then evaluated and the best ones are selected to form the next generation. This process is repeated until a satisfactory solution is found or a stopping criterion is met. Genetic algorithms are powerful optimization tools, but they can be computationally expensive.</p><p><strong>Christofides’ Algorithm</strong></p><p>The Christofides algorithm is a heuristic algorithm for solving the TSP problem. The algorithm is based on the observation that the TSP is equivalent to finding a minimum-weight perfect matching in a complete graph, where the weight of an edge is the distance between two cities. The Christofides algorithm consists of the following steps:</p><ol><li>Start by finding a minimum spanning tree of the graph.</li><li>Find the set of nodes that have an odd degree in the minimum spanning tree and form a subgraph with these nodes.</li><li>Find a minimum-weight perfect matching in the subgraph formed in step 2.</li><li>Combine the minimum spanning tree and the perfect matching to form an Eulerian graph.</li><li>Find an Eulerian tour of the Eulerian graph.</li><li>Convert the Eulerian tour back into a Hamiltonian cycle by removing repeated edges.</li></ol><p>Noote that the Christofides algorithm guarantees a solution that is at most 3/2 times the optimal solution and it is also known as a “Heuristic algorithm” and it’s not guaranteed to find the optimal solution but it provides a fast and a good approximate solution.</p><p><strong>Solution implementation for our problem</strong></p><p>For demonstration purposes, in our problem, we’ll use the Nearest Neighbour Heuristic. It will give a quick solution but it is not guaranteed to be optimal.</p><pre>from typing import List<br>import math<br><br>def nearest_neighbor(cities: List[str], distances: List[List[int]]) -&gt; List[str]:<br>    unvisited = set(cities)<br>    current = cities[0]<br>    unvisited.remove(current)<br>    tour = [current]<br>    while unvisited:<br>        next_city = min(unvisited, key=lambda city: distances[cities.index(current)][cities.index(city)])<br>        tour.append(next_city)<br>        unvisited.remove(next_city)<br>        current = next_city<br>    return tour</pre><h4><strong>Results</strong></h4><p>We have the following enumeration of cities:</p><p>0 — Augsburg, 1 — Munich, 2 — Stuttgart, 3 — Nuremberg, 4 — Leipzig, 5 — Dresden, 6 — Berlin, 7 — Hanover, 8 — Bremen, 9 — Hamburg, 10 — Cologne, 11 — Frankfurt</p><p>and for the distances between the cities we have (taken approximately by Google maps in km):</p><pre>[[0,57,133,122,347,362,495,452,543,578,404,250], # Augsburg<br> [57,0,188,144,356,355,498,483,577,605,449,298], # Munich<br>[133,188,0,157,365,412,511,402,480,534,289,153], # Stuttgart<br>[122,144,157,0,225,258,374,338,433,461,337,187], # Nuremberg<br>[347,356,365,225,0,99,150,215,311,295,380,294], # Leipzig<br>[362,355,412,258,99,0,165,312,406,380,473,372], # Dresden<br>[495,498,511,374,150,165,0,250,316,255,477,422], #Berlin<br>[452,483,402,338,215,312,250,0,100,135,245,257], #Hanover<br>[543,577,480,433,311,406,316,100,0,95,270,330], # Bremen<br>[578,605,534,461,295,380,255,135,95,0,355,392], # Hamburg<br>[404,449,289,337,380,473,477,245,270,355,0,150], # Cologne <br>[250,298,153,187,294,372,422,257,330,392,150,0] #Frankfurt<br>]</pre><p>The first list is all the distances to Augsburg, the second list is all the pair-wise distances to Munich etc.</p><p><strong><em>Nearest Neighbour heuristic</em></strong></p><p>Running the code gives the following route:</p><pre>index   city    total distance<br>    1 Augsburg       0<br>    2 Munich        57<br>    3 Nuremberg    201<br>    4 Stuttgart    358<br>    5 Frankfurt    511<br>    6 Cologne      661<br>    7 Hanover      906<br>    8 Bremen      1006<br>    9 Hamburg     1101<br>   10 Berlin      1356<br>   11 Leipzig     1506<br>   12 Dresden     1605<br>   13 Augsburg    1967</pre><p>When plotted on the map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*bwlzERhzikqfNtoDzF5nSg.png" /><figcaption>Output of the TSP-Nearest Neighbour</figcaption></figure><p><strong><em>Brute Force</em></strong></p><p>It is interesting to see what the exact solution is for this problem with relatively few items to consider. 12 cities are not a lot, and our brute force implementation can run in a reasonable time. Although it takes significantly longer (see minutes!!) to check all the possible permutations, it is feasible. Compare this with the instantaneous results we got with the Nearest Neighbour approach. This is a typical example of the power of heuristics when you deal with problems of exponential complexity.</p><p>The resulting route gives a minimum distance of 1821 km and is given below:</p><pre>1 Augsburg<br>2 Stuttgart<br>3 Frankfurt<br>4 Cologne<br>5 Hanover<br>6 Bremen<br>7 Hamburg<br>8 Berlin<br>9 Dresden<br>10 Leipzig<br>11 Nuremberg<br>12 Munich<br>13 Augsburg</pre><p>Now, certainly our Nearest Neighbour approach is quite a bit off the optimal solution, but we have to keep in mind that the penalty we paid for the brute force was quite higher in time (and computation power). For our problem of 12 cities this might be peanuts.. but for a problem of thousands of items, the combinatorial explosion would make the brute force solution simply infeasible.</p><h3>Conclusion</h3><p>In conclusion, the TSP is a classic optimization problem that has a wide range of modern applications in logistics, transportation, scheduling, and computational biology. The problem is difficult to solve because of the large number of possible routes to consider, but approximate algorithms such as nearest neighbour, simulated annealing and genetic algorithm can find good solutions in a reasonable amount of time. The complexity of the problem comes from the fact that the number of routes to consider grows exponentially as the number of cities increases. Understanding the TSP and these approximate algorithms, will give you a deeper understanding of optimization problems and the limits of what can be computed and solved in a reasonable amount of time. Additionally, experimenting with different algorithms and solutions, and trying to implement them on your own will help you to get a better understanding of the problem and to see what works best for a specific use case.</p><p><em>If you liked the article please consider giving it a ‘like’ and following for more.</em></p><p><em>As always, feel free to leave a comment and discuss further.</em></p><p><em>Thank you for your time, I hope it was time well spent!</em></p><p><em>Cheers!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2b87e48b9d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5+5=15 Deep Learning resources for beginners and beyond — 2023 edition]]></title>
            <link>https://medium.com/@marioskokmotos2/5-5-15-deep-learning-resources-for-beginners-and-beyond-2023-edition-aa9e8e3008ca?source=rss-a988d8b4ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa9e8e3008ca</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[resources]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[course]]></category>
            <dc:creator><![CDATA[Marios Kokmotos]]></dc:creator>
            <pubDate>Fri, 25 Nov 2022 11:57:49 GMT</pubDate>
            <atom:updated>2022-11-25T11:57:49.463Z</atom:updated>
            <content:encoded><![CDATA[<h3>5+5=15 Deep Learning resources for beginners and beyond — 2023 edition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZA1S0Nhe55fwdzFKBAsRA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@gunnarridder?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Gunnar Ridderström</a> on <a href="https://unsplash.com/s/photos/books-computer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Deep Learning is one of the cornerstones of modern Artificial Intelligence advancements. The increasingly powerful computation machines called GPUs have made it possible to build vision and language models that in some (a lot) instances outperform humans. The free availability of GPU resources in the cloud has democratised (a little bit) the access to this technological revolution of our days and has bestowed upon everyone the power to develop systems that solve daily problems, enhance their business capabilities or even nurture one’s soul by creating fantastic pieces of art.</p><p>Language models such as GPT-3 and BERT, diffusion models such as DALL-E and computer vision models such as Visual Transformers have really had a huge impact in the field demonstrating the immense possibilities of AI and specifically Deep Learning.</p><p>No doubt Deep Learning is one of the hottest topics in AI right now. No doubt either, that a lot of people want to break into Deep Learning, fascinated by the sheer marvels one can perform. What seemed unimaginable even a decade ago, is now everyday practice.</p><p>We want to avoid over-hyping Deep Learning though! There are still issues to be solved related to performace, complexity, universality of the models, economics of training the models (that deem them not so widely available), explainability (notorious about this), fairness, bias etc…</p><p>Without further ado, we give some resources for the aspiring Deep Learning engineers/scientists. The resources are ranked (approximately) according to difficulty. All of them are free!</p><p>We tried to avoid suggesting resources that we have already shared in <a href="https://medium.com/@marioskokmotos2/autodidacts-path-to-ai-machine-learning-part-2-bead9686e381">part 2 of the Autodidact’s path</a>, and the resources presented here are (in my opinion) at a slightly higher level of difficulty. If you want more beginner-friendly resources, I suggest you have a look at that article.</p><p>Obviously, there is no reason to go through all of them since they have a huge overlap in the subjects that they treat, but it’s nice to have options!</p><p>As usual, it all starts with Courses and books, 5 each… but it would be a shame not to include some more resources that are definitely worth to be in your bookmarks, so there you have it, another 5.</p><p>My recommendation would be to pick one course, one book and then browse through the blogs and the channels trying to implement and understand as much as possible.</p><h3>Courses</h3><ol><li><a href="https://deeplearning.cs.cmu.edu/S22/index.html">11–785 Deep Learning (cmu.edu)</a> — Carnegie Mellon’s Intro to Deep Learning course. It contains handouts and video lectures. It requires a certain mathematical sophistication but is highly rewarding (it is CMU after all!)</li><li><a href="https://cs182sp21.github.io/">CS 182: Deep Learning (cs182sp21.github.io)</a> — Deep Learning course from Berkeley and Sergey Levine. It includes slides and homework. The videos are on YouTube.</li><li><a href="https://uvadlc.github.io/">UvA Deep Learning Course (uvadlc.github.io)</a> — Deep Learning course at the University of Amsterdam. It is part of the MSc in Artificial Intelligence and includes slides, notebooks and more. The video lectures are available on Youtube.</li><li><a href="http://cs231n.stanford.edu/">Stanford University CS231n: Deep Learning for Computer Vision</a> — Stanford would not be absent from the list. This is a Deep Learning course oriented towards Computer Vision. Notes and assignments are available while the lectures from 2017 can be found on YouTube.</li><li><a href="https://web.stanford.edu/class/cs224n/index.html#coursework">Stanford CS 224N | Natural Language Processing with Deep Learning</a> — If NLP is more of your taste, then this is the place to start. On the website you’ll find slides and notes among others, while the video lectures from 2022 are available on Youtube.</li><li><a href="https://youtu.be/7R52wiUgxZI">DeepMind’s Deep Learning lectures</a> — This is a bonus. DeepMind-UCL lectures. Enough said.</li></ol><h3>Books</h3><ol><li><a href="https://d2l.ai/index.html">Dive into Deep Learning — Dive into Deep Learning 1.0.0-alpha1.post0 documentation (d2l.ai)</a> — A complete book accompanied by lectures and notebooks in both Tensorflow and PyTorch.</li><li><a href="https://www.deeplearningbook.org/">Deep Learning (deeplearningbook.org)</a> — THE Deep Learning book. Pretty complete in the theoretical perspective and maths behind DL, but no code implementations.</li><li><a href="https://pytorch.org/tutorials/">Welcome to PyTorch Tutorials</a> — The PyTorch website itself provides a lot of tutorials and suggestion for someone interested in a quick start.</li><li><a href="https://www.learnpytorch.io/">Zero to Mastery Learn PyTorch for Deep Learning</a> — Not technically a book but can be read as one. It is hands-on PyTorch and can definitely give you a boost whether you are a beginner or a more intermediate practitioner. It includes a lot of examples and is basically a walkthrough of ZTM’s course, part of which has been uploaded to FreeCodeCamp’s channel on YouTube.</li><li><a href="https://web.stanford.edu/~jurafsky/slp3/">Speech and Language Processing (stanford.edu)</a> — Jurafsky’s and Martin’s book freely available online. An excellent resource for NLP covering a lot of the modern advances in the field. Currently a draft of the 3rd edition.</li></ol><h3>Blogs/Channels</h3><ol><li><a href="https://paperswithcode.com/sota">Browse the State-of-the-Art in Machine Learning | Papers With Code</a> — A nice repository to keep up with the current trends and advances.</li><li><a href="https://aman.ai/papers/#">Aman’s AI Journal • Papers List</a> — A blog containing a large collection of links to papers in every subject of ML and DL. Best feature is the categorisation based on importance.</li><li><a href="https://theaisummer.com/start-here/">Start Here | AI Summer (theaisummer.com)</a> — A very interesting blog containing a lot of information and explanations on state-of-the-art models.</li><li><a href="https://www.youtube.com/c/TheAIEpiphany">Aleksa Gordić — The AI Epiphany — YouTube</a> — The AI Epiphany guy, at the time of writing, a Research Engineer at DeepMind does an excellent job in explaining hard concepts and state-of-the-art papers. Definitely worth a subscription.</li><li><a href="https://jalammar.github.io/">Jay Alammar — Visualizing machine learning one concept at a time. (jalammar.github.io)</a> — Another awesome blog. Jay Alammar explains in an interesting pedagogical and visual way modern deep learning architectures and concepts.</li></ol><p>If you liked the article, consider sharing! Let’s spread that Deep Learning enthusiasm.</p><p>Stay tuned for more.</p><p><em>Disclaimer: No links are affiliate</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa9e8e3008ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stable matchings (cheaters, bankers and a Nobel Prize!)]]></title>
            <link>https://medium.com/@marioskokmotos2/stable-matchings-cheaters-bankers-and-a-nobel-prize-1461ab5c217?source=rss-a988d8b4ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1461ab5c217</guid>
            <category><![CDATA[stable-matching]]></category>
            <category><![CDATA[stable-marriage-problem]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Marios Kokmotos]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 21:36:54 GMT</pubDate>
            <atom:updated>2022-11-24T10:18:40.271Z</atom:updated>
            <content:encoded><![CDATA[<p>An implementation in Python.</p><p>Also known in Computer Science as the <a href="https://en.wikipedia.org/wiki/Stable_marriage_problem">Stable Marriage Problem</a>. Matching pairs is one of the problems with various applications in everyday life.</p><p>Some applications appear in the areas of economics and markets, where order books of stocks try to match seller and buyer, in college admissions where each college tries to select the best applicant for them and at the same time each applicant tries to select the best school (this problem is also seen as the hospital/residents problem). We also see it in <a href="https://en.wikipedia.org/wiki/Content_delivery_network">Content delivery networks</a> where servers are matched to clients requesting content at different geographic locations.</p><h3>The problem</h3><p><em>(Adapted from Wikipedia)</em></p><p>The <strong>stable marriage problem</strong> (also <strong>stable matching problem</strong> or <strong>SMP</strong>) is the problem of finding a stable matching between two sets of the same size, where the elements of the first set are matched to the elements of the second set (nobody remains unmarried) given an ordering of preferences for each element. Just matching the pairs would be an easy job if we wouldn’t impose an extra constraint on the problem. The matching needs to be stable.</p><p>In simple terms, a matching is stable if there is no pair which both prefer each other to their current partner under the existing matching.</p><h3>The set-up</h3><p>The problem set-up is pretty simple actually!</p><p>We have two sets with n elements each that need to be connected according to their preferences. The typical description of the problem discusses marriages between men and women, but since is the 21st century and it is only proper and considerate to be inclusive, we will replace this terminology with a more universal one. The set on the left will be the set of incoming students (students to be admitted to college) and the set on the right will be the set of the colleges. To simplify the discussion, we will enumerate both sets starting from 0 to n-1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d4krPmG3YVB9iLv18LFHcg.png" /><figcaption>The two sets of the problem.</figcaption></figure><p>Now, each student has their own preferences, a ranking of the colleges he/she would like to be admitted to. Similarly, each college has its own list of preferred candidates to which it would like to extend offers.</p><h3>The Gale-Shapley algorithm</h3><p>A solution to the stable matching problem is given by the <a href="https://en.wikipedia.org/wiki/Gale%E2%80%93Shapley_algorithm">Gale-Shapley algorithm</a> that was developed in 1962. It is a simple algorithm that has a very intuitive real-life action representation.</p><p>Let S be the set of students and C the set of colleges.</p><pre>Algorithm stable_matching:<br>Start:<br>    Initialize s ∈ S and c ∈ C to be free<br>    while ∃ free student s who has a college c to apply to, do:<br>        c := first college on s&#39;s list to whom s has not yet applied<br>        if ∃ some pair (s&#39;, c) then<br>            if c prefers s to s&#39; then<br>                c&#39; becomes free<br>                (s, c) become connected<br>            end if<br>        else<br>            (s, c) become engaged<br>        end if<br>    repeat<br>End:</pre><p><strong>Explanation in simple terms:</strong></p><ul><li>We have a set of students and a set of colleges each one of which have their own preferences. The students have a ranking of the colleges they prefer, and the colleges have a ranking of the students they prefer.</li><li>We initialise the students and colleges to be free (they are not connected to anyone)</li><li>While there is a free student that has a college to apply to, the student applies to the college that is currently first in their preference list, let it be college ‘c’. We check if college ‘c’ is already paired to a student.</li><li>If college ‘c’ is not paired to anyone, then we pair student ‘s’ and college ‘c’.</li><li>However, if college ‘c’ is already paired to some else student “s2“, we have to check if college ‘c’ prefers student ‘s’ over “s2“. If that is the case, then we pair ‘c’ and ‘s’ and apparently now “s2“ which was part of the match, is now free.</li><li>Note that if a student is rejected by a college ‘c’, then the student will never try to apply to that college again. The preference now is the next college in his/her ranking.</li></ul><p>The runtime complexity of this algorithm is O(n²) where n is the number of men or women. Since the input preference lists also have size proportional to n², the runtime is linear in the input size.</p><p><strong>Unfairness of the algorithm:</strong></p><p>It can be proven that the Gale-Shapley algorithm returns an optimal matching for the set that makes the proposal. However, it will return the worst stable matching for the set that accepts the proposal. At the same time, it guarantees that in the end there won’t be any unpaired participants.</p><p>While it seems counter-intuitive, the algorithm favours the students over the colleges. While the colleges have the ability to reject applications by the students, they are still the set that is unfavoured by getting the worst possible stable matching.</p><p>The algorithm is also truthful for the proposing set (the students in our case), that is the students cannot get a better matching for themselves by misrepresenting their preferences — they cannot trick the system by lying about their preferences so that they get a better matching. On the other hand, the set that accepts the proposals can indeed cheat the system and get a better matching by lying.</p><p>Lloyd Shapley and Alvin Roth were awarded the 2012 <a href="https://en.wikipedia.org/wiki/Nobel_Memorial_Prize_in_Economic_Sciences">Nobel Memorial Prize in Economic Sciences</a> “for the theory of stable allocations and the practice of <a href="https://en.wikipedia.org/wiki/Market_design">market design</a>”; Gale had already died in 2008.</p><h3>Python implementation</h3><p>We have assumed in our problem that the matching will be 1-on-1, so we only allow one student to one college and vice versa. Our python implementation will use lists to keep track of the assigned numbers each time (note that this could also be done with dictionaries).</p><p>The input is of order n² since we have n preferences for each of the n students and colleges.</p><pre>def stableMatching(n, studentPreferences, collegePreferences):<br><br>    # Initially, all n students are unpaired<br>    unpairedStudents = list(range(n))<br>    # None of the students has a college, we denote this by the value None<br>    studentPair = [None] * n                      <br>    # None of the colleges has accepted a student yet, we denote this by the value None<br>    collegePair = [None] * n                      <br>    # Each student made 0 proposals, which means that <br>    # his/her next proposal will be to the college number 0 in his list<br>    nextStudentChoice = [0] * n                       <br>    <br>    # While there exists at least one unpaired student:<br>    while unpairedStudents:<br>        # Pick an arbitrary unpaired student. Here we just pick the first one<br>        student = unpairedStudents[0]                      <br>        # Store his/her ranking in this variable for convenience<br>        stPreferences = studentPreferences[student]       <br>        # Find a college to apply to<br>        college = stPreferences[nextStudentChoice[student]] <br>        # Store the college&#39;s preference in this variable for convenience<br>        colPreferences = collegePreferences[college]<br>        # Find the student that is currently paired to the college (it might be None)<br>        currentPair = collegePair[college]         <br>        <br>        # The college only admits the student if he/she ranks higher<br>        # in the college&#39;s preferences or if the college is unpaired<br>        if (currentPair is None) or (colPreferences.index(currentPair) &gt; colPreferences.index(student)):<br>            # pair the student and the college<br>            studentPair[student] = college<br>            collegePair[college] = student<br>            # the student is now paired, remove them from the list<br>            unpairedStudents.remove(student)<br><br>            # if the college was already paired to a student, <br>            # now that student is unpaired, so we put them in the list<br>            if currentPair != None:<br>                unpairedStudents.append(currentPair)<br>        else:<br>            # if the student is rejected, they will move to their next preference<br>            nextStudentChoice[student] += 1<br><br>    return studentPair</pre><p>If we run the above for n=5 and the following preferences for students:</p><p>studentPreferences = [[0,2,4,1,3], [0,1,4,2,3], [1,2,0,4,3], [3,2,4,0,1],[1,4,2,0,3]]</p><p>and the preferences of colleges:</p><p>collegePreferences = [[0,1,4,2,3], [2,1,4,0,3], [1,3,0,4,2], [3,4,2,0,1],[3,4,2,0,1]]</p><p>we get the following stable matching:</p><p>[0, 2, 1, 3, 4]</p><p>which simply means that student 0 is paired with college 0, student 1 is paired with college 2 etc…</p><p>We see that both college 0 and student 0 get what they want since they both prefer participant 0 of the other set. The same thing happens to student 3 and college 3, where number 3 is top of their list respectively. Observe that student 2 prefers college 1 and college 1 also prefers him/her over the other candidates, so this will give a match. The result of the algorithm is depicted below. Next to each participant there is a list with their preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*rjNAbi7hsjGDOnWQD2ndUw.png" /><figcaption>Stable matching for our example</figcaption></figure><h3>Conclusion</h3><p>We’ve seen a very interesting algorithm in Computer Science that has a lot of important applications such as assigning users to servers in a large distributed Internet service or matching buyers and sellers of a commodity or stock. Although optimal for one of the participating groups, it is unfair to the other. However, it is quite efficient as it is linear in the size of the input.</p><p>Besides solving some large-scale real-life problems, the algorithm can also make you a proud owner of a Nobel Prize! If you have some space on that dusty bookshelf of yours.</p><p>I hope you found the article interesting! Feel free to leave a comment for further discussion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1461ab5c217" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Dining Philosophers problem-a simple implementation in Go]]></title>
            <link>https://medium.com/@marioskokmotos2/the-dining-philosophers-problem-a-simple-implementation-in-go-189a4ae7edf7?source=rss-a988d8b4ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/189a4ae7edf7</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[dining-philosophers]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Marios Kokmotos]]></dc:creator>
            <pubDate>Thu, 10 Nov 2022 19:36:17 GMT</pubDate>
            <atom:updated>2022-11-25T17:03:24.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywbHwR7NV6ZCQtBqG7UBtw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alexx_27?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alex G</a> on <a href="https://unsplash.com/s/photos/forks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>“Give me my fork!!” shouted Descartes,</blockquote><blockquote>“I will only use it for a bite or two, and besides… it is not yours…we’re sharing…remember?” replied Francis Bacon.</blockquote><blockquote>Kant remained silent…partly because his mouth was full devouring the food at the lavish banquet.</blockquote><p>While I doubt this ever happened as described…It could quite well set the stage of our scene and problem, that of the Dining Philosophers.</p><p><strong>The problem in simple terms</strong> reads as follows:</p><p><em>Five philosophers dine together at the same table. Each philosopher has their own place at the table and obviously a plate in front of them. There is a fork between each plate. The dish served is a specific recipe which requires two forks in order to be enjoyed. Each philosopher can only alternately think and eat. A philosopher can only eat their meal when they have both a left and right fork. Thus, two forks will only be available when their two nearest neighbours are thinking, not eating. After an individual philosopher finishes eating, they will put down both forks.</em></p><p>This is a very interesting problem in computer science, and it is the essence of concurrent algorithms. The problem is how to design a concurrent algorithm such that no philosopher will starve, i.e., each can forever continue to alternate between eating and thinking and does not get stuck in the ‘thinking’ state. We further assume that no philosopher can know when others may want to eat or think (an issue of incomplete information).</p><p>In computer science, we are not interested in philosophers — well, we might be, but not for the purposes of this article — but we are interested in process starvation. This is a situation where a process or a thread within a process does not get enough computing resources to execute its job [2].</p><p>Perhaps the most severe situation is when all of the processes are driven to starvation. The situation to be avoided is known as a <strong>deadlock </strong>[3]<strong>,</strong> a situation where threads, processes or other members of a group of entities, each wait for another member before taking action. Thus, no progress is achieved in the overall system. An extreme case of deadlock would occur if each one of the 5 philosophers grabbed the fork on his left (or right). Then they would wait for their respective fork on the right (left) to become available so that they can commence eating. Stubborn as they are, they are not programmed to abandon their attempt, so they are led to starvation holding one fork in their hands! Moral of the story…stubbornness kills!</p><p>As can be easily deduced, a deadlock state can be fatal for a system’s performance and even catastrophic to human lives if the system is safety critical.</p><p>Our implementation will utilise the Go programming language. Partly because it is elegant and modern, but mostly because concurrent features are inherent in the language. Go was created with concurrency in mind.</p><h3>Solution with host</h3><p>We will implement the simple (but perhaps not most efficient) solution of introducing an arbitrator, in our case a host.</p><p>The existence of an arbitrator (host) that grants permission to a philosopher to start eating guarantees that a philosopher can only pick up both forks under certain conditions. In order to pick up the forks, a philosopher must ask permission from the host. The host gives permission to only one philosopher at a time until the philosopher has picked up both of their forks. In addition to introducing a new central entity (the host), this approach can result in reduced parallelism: if a philosopher is eating and one of his neighbours has requested permission first among the rest, all other philosophers must wait until this request has been fulfilled even if forks for them are still available.</p><p>In our solution we will explicitly allow up to 2 philosophers to be eating in at the same time although this is not strictly necessary in our case since the philosophers will be constrained to 2 by the problem design.</p><p>E.g. If philosopher 1 is eating then we know that philosophers 5 (modulo 5 arithmetic) and 2 cannot be eating. Only 3 or 4 can be eating but because they share one fork, only one of them at a time will be able to eat.</p><p>We will also allow each one of the philosophers to eat up to 3 times, so that we don’t run the simulation indefinitely.</p><p><strong>Channels</strong></p><p>Channels are the main means of communication between Go routines. When a channel is set up, a Go routine can receive or send data on it. Channels are abstractions that can be thought of as pipes that transfer data between Go routines and help them synchronize and avoid race conditions making the output deterministic.</p><h3><strong>Setting up the problem and Code</strong></h3><p>We start by declaring our philosophers and the chopsticks constructs. The chopstick/fork will be just a Mutex that will be locked and unlocked by the philosophers. Each philosopher will have a left and right chopstick and an ID number.</p><pre>type ChopS struct{ sync.Mutex }<br><br>type Philo struct {<br> leftCS, rightCS *ChopS<br> id              int<br>}</pre><p>The host will keep track of the number of philosophers currently eating, will keep a tab of how many times each philosopher has already eaten and a value represnted as “sum_of_eat” here which is essentially decremented every time a philosopher reaches 3 times. Once the sum_of_eat reaches -5, it will mean that all philosophers have eaten their maximum allowed times and the host’s job is done.</p><pre>type host struct {<br> Philosophers_eating int<br> tab                 map[int]int<br> sum_of_eat          int<br>}</pre><p>The communication between the philosophers and the host will take place through channels. We will have 1 channel on which every philosopher will send their requests to eat, and the host will be listening to. We will also have 5 separate channels, 1 per philosopher, where the host will be sending permission or not to the specific philosopher allowing them to start eating.</p><p>We first create the function for the philosopher to request permission and eat. The parameters are the WaitGroup necessary for concurrent operations in Go, the send channel where the philosopher sends to the host (this will be the host’s channel basically the same for everyone) and the receive channel which is specific to each philosopher and through which they will receive permission from the host. Once they receive permission from the host, the philosophers pick up the forks (randomly) and start eating. They print to the screen so that we know which Go routine is eating and has locked the forks. Each time the philosopher stops eating, they send ‘-1’ back to the host. If the philosopher receives a ‘-1’ from the host, he/she terminates the routine since we know that the host will not allow them to eat any more.</p><pre>func (p Philo) eat(wg *sync.WaitGroup, send_ch chan int, receive_ch chan int) {<br> for {<br>  // the philosopher notifies the host in order to be allowed to eat<br>  send_ch &lt;- p.id<br>  // wait for response from the host<br>  allowed := &lt;-receive_ch<br>  if allowed == 1 {<br>   // if allowed to eat, pick up the forks randomly<br>   r := rand.Float64()<br>   if r &gt; 0.5 {<br>    p.leftCS.Lock()<br>    p.rightCS.Lock()<br>   } else {<br>    p.rightCS.Lock()<br>    p.leftCS.Lock()<br>   }<br>   fmt.Println(&quot;Starting to eat &quot;, p.id+1)<br>   fmt.Println(&quot;Finishing eating &quot;, p.id+1)<br>   p.rightCS.Unlock()<br>   p.leftCS.Unlock()<br>   // when the philosopher finishes, he/she sends -1 to the host<br>   send_ch &lt;- -1<br>  }<br>  // if the host sends -1, the philosopher will terminate<br>  // they won&#39;t be allowed to eat anymore<br>  if allowed == -1 {<br>   wg.Done()<br>   return<br>  }<br> }<br>}</pre><p>For the host, we run an infinite loop until everyone has eaten 3 times. If everyone has eaten their 3 times, then the value of <em>sum_of_eat</em> will be -5 and the go routine will terminate. The host always listen to his/her channel for incoming ID integers which basically tell him/her who is the philosopher that is asking for permission. If -1 is received, then it means that a philosopher has stopped eating. If a positive number is received (the philosophers ID) then the host checks if that particular philosopher has already eaten 3 times or more. If they have then the host sends a -1 which will make the philosopher to terminate (stop asking for more food!!). If the philosopher is allowed to eat, then the host checks how many philosophers are currently eating. If less than 2 are eating, then the host allows the philosopher to eat by sending back a +1. If 2 are already eating then the host sends back a 0, so that the philosopher takes no action (the 0 here is an arbitrary value, it could be anything but -1 and 1).</p><pre>func (h host) allow_to_eat(wg *sync.WaitGroup, channels []chan int) {<br> for {<br>  // every time someone has eaten 3 times<br>  // we decrease by 1, so when we reach -5 the host is done<br>  if h.sum_of_eat == -5 {<br>   wg.Done()<br>   return<br>  }<br>  // read which philosopher requests permission, listen at channel 5<br>  // for incoming requests<br>  id := &lt;-channels[5]<br>  // if a philosopher has sent -1, it means they have stopped eating<br>  // so the host can decrease the number of people currently eating<br>  if id &lt; 0 {<br>   h.Philosophers_eating -= 1<br>  } else {<br>   // if the philosopher has eaten more than 2 times, send them -1 so they stop<br>   if h.tab[id] &gt;= 3 {<br>    h.sum_of_eat -= 1<br>    channels[id] &lt;- -1<br>   } else {<br>    // if there are less than 2 philosophers eating and the philosopher has not eaten<br>    // more than 3 times, let him eat and note down by incrementing his counter<br>    if h.Philosophers_eating &lt; 2 {<br>     h.tab[id] += 1<br>     channels[id] &lt;- 1<br>     h.Philosophers_eating += 1<br>    } else {<br>     // if already 2 philosphers are eating, send 0 so that the requesting philosopher does nothing<br>     channels[id] &lt;- 0<br>    }<br>   }<br>  }<br> }<br>}</pre><p>The main function of the program is a s follows: We basically create all the variables; chopsticks philosophers and host and we initialize them. Then we create the 6 go routines (5 philosophers, 1 host) with the necessary arguments each time and we let them run.</p><pre>var wg sync.WaitGroup<br><br>func main() {<br>// create the chopsticks, the channels and the philosophers<br> // each philosopher will have their own channel to require<br> // permission to eat<br> CSticks := make([]*ChopS, 5)<br> for i := 0; i &lt; 5; i++ {<br>  CSticks[i] = new(ChopS)<br> }<br> philos := make([]*Philo, 5)<br> // we make 6 channels, 1 where the host will listen all the<br> // requests and 5 where the host will send the permissions to each<br> // one of the philosophers<br> // 0-4 are the philosophers and 5 is the host<br>channels := make([]chan int, 6)<br>for i:=0; i&lt;6; i++{ <br>  channels[i] = make(chan int)<br>}<br>for i := 0; i &lt; 5; i++ {<br>  philos[i] = &amp;Philo{CSticks[(i+1)%5], CSticks[i], i}<br> }<br>// initialize host<br> var h host<br> h.Philosophers_eating = 0<br> h.tab = map[int]int{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}<br>wg.Add(6)<br> // the host has access to all channels<br> go h.allow_to_eat(&amp;wg, channels)<br> for i := 0; i &lt; 5; i++ {<br>  // every philosopher sends to channel 5 (host), and receives at channel i<br>  go philos[i].eat(&amp;wg, channels[5], channels[i])<br> }<br> wg.Wait()<br>return<br>}</pre><p>After running the full code, we get a result of the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*CXyJfMsPRgCsuFKkHyyC4g.png" /><figcaption>typical run of the program</figcaption></figure><p>We can see that there is a point where 2 philosophers (1 and 4) start eating together with 1 getting permission first. It is difficult (or impossible) to know when each philosopher will request and receive permission to eat since their routines run concurrently and it is the Go runtime along with the OS that decides in what order to run them. Every run will likely give different results, but we can see that all philosophers eat 3 times each and we never have more than 2 eating at the same time.</p><p><strong>Resources:</strong></p><p>Some interesting resources for Go beginners and beyond:</p><ol><li><a href="https://www.manning.com/books/get-programming-with-go">Get Programming with Go (manning.com)</a></li><li><a href="https://www.packtpub.com/free-ebook/the-go-workshop/9781838647940">The Go Workshop Free eBook | Packt (packtpub.com)</a></li><li><a href="https://www.manning.com/books/go-in-practice">Go in Practice (manning.com)</a></li><li><a href="https://nostarch.com/networkprogrammingwithgo">Network Programming with Go | No Starch Press</a></li></ol><p>and many more (some free) at: <a href="https://github.com/golang/go/wiki/Books#english">Books · golang/go Wiki (github.com)</a></p><p>If you found this interesting, please share your thoughts in the comments below and consider following for more articles!</p><p>Disclaimer: No links are affiliate</p><h3><strong>References:</strong></h3><p>[1] <a href="https://en.wikipedia.org/wiki/Dining_philosophers_problem">Dining philosophers problem — Wikipedia</a></p><p>[2] <a href="https://en.wikipedia.org/wiki/Starvation_(computer_science)">Starvation (computer science) — Wikipedia</a></p><p>[3] <a href="https://en.wikipedia.org/wiki/Deadlock">Deadlock — Wikipedia</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=189a4ae7edf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple simulation of ‘6 Degrees of Separation’ (or, how we are all connected)]]></title>
            <link>https://medium.com/@marioskokmotos2/a-simple-simulation-of-6-degrees-of-separation-or-how-we-are-all-connected-8f8f82a16893?source=rss-a988d8b4ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f8f82a16893</guid>
            <category><![CDATA[6-degrees-of-separation]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Marios Kokmotos]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 20:33:42 GMT</pubDate>
            <atom:updated>2022-11-09T10:03:28.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTKpW04SfIdZp-I_rmGzag.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">NASA</a> on <a href="https://unsplash.com/s/photos/earth?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I know a friend who knows a friend, who knows a friend….and most probably, you know him too!</p><p>How many friends would you need in this chain to reach any person in the world. Well, experiments and mathematical proofs have been devised that declare the answer to this being… 6 (or thereabouts)!</p><p>Well, with the ‘caveat’ of this being that it is a statistical estimate. Nevertheless, it is impressive and definitely counter-intuitive. Would you think you only need on average 6 people until you reach Mark Zuckerberg, Elon Musk or your favourite scientist…</p><p>This is a very interesting problem arising in <a href="https://en.wikipedia.org/wiki/Random_graph">random networks</a>, a subject with a plethora of modern applications and very active research. Applications range from social networks to complex physical networks in condensed matter and biology [3–5].</p><p>It is a mathematical proven fact that the average distance in a (living) population is around 6. More specifically, Watts and Strogatz have shown [8] that the average path length between two nodes in a random network is equal to ln <em>N</em> / ln <em>K</em>, where <em>N</em> = total nodes and <em>K</em> = acquaintances per node. Thus, if <em>N</em> = 6,000,000,000 (90% of the World population) and <em>K</em> = 30 then <em>Degrees of Separation</em> = 22.5 / 3.4 = 6.6. (Assume 10% of population is too young to participate.)</p><p>The problem and its result certainly carry very interesting implications for various areas of science (political, social, natural etc) but they also carry a very interesting philosophical notion; none other than the fact that…</p><blockquote><em>We are all connected on this planet.</em></blockquote><p>Adopting this perspective, however bold it might sound, gives us a way of thinking, being inclusive towards others, even reaching the level of solidarity — if you feel strong enough to go there.</p><p>Your friends, your role-models, your so-called enemies, or even your…celebrity crush!…They are all just a mere few ‘steps’ from you. And this is extraordinary and frankly, humbling.</p><p>But enough with knocking on philosophy’s door. Let’s get down to some engineering!!!</p><h3>Introduction Set-up of the problem</h3><p>The problem is essentially that of random graphs. You have a lot of nodes (the people) and you draw edges between them (their relationships/friendship). The randomness of the system comes from the fact that the edges are assigned following a certain probability distribution. Different distributions give rise to different kind of graphs each one demonstrating its own features and emergent phenomena.</p><p>A common assumption is that the edges are independent of each other, but keep in mind that this is not always true in real-life networks, and it is one of the reasons it cannot model them perfectly. For the interested reader, you can have a look at [1–5]</p><h3>Simplification ‘Small worlds’</h3><p>In order to make the simulations more manageable we’ll work with a simplified version of the problem. We will deal with a small-world network consisting of up to 1000 participants in which we set the number of nearest neighbours in advance, and we also assign additional edges at random with probability p without re-wiring any connections. We will name these random edges; ‘shortcuts’. We also note that they are very important for the viability of a small-world network and the creation of clusters.</p><p>Our network structure consists of L participants, each one with Z nearest-neighbours and additional p*L*Z/2 shortcuts.</p><h3>Small World Simulation</h3><p>Below we show an example of a small-world consisting of 50 participants each one having 4 acquaintances (nearest neighbours) and a probability of 0.1 for shortcuts. This is much easier to plot than a network consisting of 1000 participants, it sets, however, the landscape of the experiment nicely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zJsvH46PE7NUSNKj6ERLWQ.jpeg" /><figcaption>Image generated by author</figcaption></figure><p>The layout is circular for visibility of the network. Note that the network above is basically a collection of points where each one is connected to 4 others in its vicinity (2 on its right and 2 on its left). In addition to that we have randomly connected some of the points, the paths are shown as chords of the circle. If we didn’t have these connections, we would expect the distance of 2 antipodal points to be approximately N/4, where the nearest-neighbour distance is considered to be 1. This would give for N=50, a minimum distance of 12.</p><p>Now, if we plot the histogram for the distances between the nodes of the network, we get the following result. We can see that no pair-wise distance is greater than 8. This is even more profound for N=1000, where the distance of 2 antipodal points would be approximately 250 and we see that again the average is far less around 8 if we include shortcuts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*c9vXzG1OWM7nrmH-_wNODg.png" /><figcaption>Histogram of the distances between nodes, N=50, Z=4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*y6UEJuKIulGJk4o96yuwJQ.png" /><figcaption>Histogram of the distances between nodes, N=1000, Z=4, p=0.1</figcaption></figure><p>In a small-world network, the shortcuts are crucial for the transfer of information. We can measure the criticality of a node by measuring its ‘betweeness centrality’. The implementation of such an algorithm requires the use of DFS.</p><p>We should also check the behaviour of the network for different values of the shortcut probability. We set a constant population of L=1000 (any value much more than that will be too slow due to the BFS implementation) and a nearest neighbour value of Z=4. We will vary the probabilities of a random shortcut and we’ll plot the average path distance for different p values normalized by the average path distance for p=0. Remember that for the p=0 case we have no random shortcuts thus the average path is deterministic and gives a measure of the extent of the network.</p><p>Below is the network for this run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*dWOnGlQZf0Xj1iYI1wqKGg.jpeg" /><figcaption>Network for L=1000, Z=4, p=0.01</figcaption></figure><p>And its corresponding histogram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*5QHM2wonRmTsainmm7xBWg.png" /><figcaption>Histogram of paths for a network with L=1000, Z=4, p=0.01</figcaption></figure><p>We see that the most frequent distance (and very close to the average) is around 27. We still see, however that the maximum path is close to 70. The average path for a network of this size with no shortcuts (p=0) is 125. We can see that with 20 random shortcuts in a population of 1000 participants we were able to lower the average distance from 125 to only 27. Below we plot the normalized average path against the shortcut probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*POwB0SY4lFhftDsvNEgCWg.png" /><figcaption>Normalized average path length against probability of shortcuts.</figcaption></figure><p>There is a slight difference in the above figure with respect to fig.2 of the paper by Watts and Strogatz [8]. This is a result of the values that we used for the simulation. Watts and Strogatz used a higher Z*L factor, and this creates a shift in the probabilities. For the purposes of our demonstration this is not of huge importance.</p><p>There are a lot of datasets out there ranging from electrical grids to social networks and even film-actor graphs like the one created based on IMDb data that is behind the famous ‘6-Degrees of Kevin Bacon’ game. You can have a try on your own and verify for yourself whether the 6 degrees rule still holds or not. I will definitely have a go in another article!</p><h3><strong>Code</strong></h3><ol><li><strong>Network</strong></li></ol><p>First, we create the Network class that will create the Small-world network and will provide methods to access the nodes. There are some</p><pre>import numpy as np</pre><pre>class Network():<br>    def __init__(self, L, Z, p, verbose=False):<br>        self.L = L # number of nodes size of network<br>        self.Z = Z # number of nearest neighbors<br>        self.p = p # probability of shortcut creates p*L*Z/2 shortcuts<br>        self.verbose=verbose<br>        self.network = {}</pre><pre>    def __str__(self):<br>        return str(self.network)</pre><pre>    def HasNode(self, node):<br>        return node in self.network.keys()</pre><pre>    def AddNode(self, node):<br>        if not self.HasNode(node):<br>            self.network[node] = set()<br>    <br>    def AddEdge(self, node1, node2):<br>        if self.HasNode(node1) and self.HasNode(node2):<br>            self.network[node1].add(node2)<br>            self.network[node2].add(node1)<br>        else:<br>            if self.verbose:<br>                if not self.HasNode(node1):<br>                    print(f&quot;Node {node1} is not in the network.&quot;)<br>                else:<br>                    print(f&quot;Node {node2} is not in the network.&quot;)<br>    <br>    def GetNodes(self):<br>        return list(self.network.keys())</pre><pre>    def GetNeighbors(self, node):<br>        if self.HasNode(node):<br>            return self.network[node]<br>        else:<br>            if self.verbose:<br>                print(f&quot;Node {node} is not in the network.&quot;)<br>            return None</pre><pre>    def ConstructNetwork(self):<br>        assert self.p &lt;=1 ,&quot;probability cannot be greater than 1&quot;<br>        assert self.p &gt;=0 ,&quot;probability cannot be less than 0&quot;</pre><pre>        assert self.Z &lt; self.L, &quot;nearest neighbors cannot be more than total nodes&quot;</pre><pre>        for i in range(self.L):<br>            self.AddNode(i)<br>            for j in range(1,self.Z//2+1):<br>                self.AddEdge(i, (i+j)%self.L)<br>                self.AddEdge(i, (i-j)%self.L)<br>        random_edges = int(self.p * self.L * self.Z/2)<br>        for _ in range(random_edges):<br>            node1 = np.random.choice(self.L)<br>            node2 = np.random.choice(self.L)         <br>            while node2 in self.GetNeighbors(node1):<br>                node2 = np.random.choice(self.L)<br>            self.AddEdge(node1, node2)</pre><p><strong>2. Graph Algorithms</strong></p><p>We create the algorithms that will traverse the network and will calulate the distances between the nodes and the average path lengths.</p><p>To find all the distances from one node to all other nodes, we use an implementation of the <a href="https://en.wikipedia.org/wiki/Breadth-first_search">BFS algorithm</a>.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np</pre><pre>def FindPathLengthsFromNode(net, node):<br>    &quot;&quot;&quot;This is basically a BFS that returns all the distances<br>        to all other nodes in the network from node&quot;&quot;&quot;</pre><pre>    # the nodes of the network    <br>    nodes = net.GetNodes()<br>    # initialize the distances to each node<br>    distances = {n:0 for n in nodes}</pre><pre>    #################################<br>    #### BFS Implementation #########<br>    #################################</pre><pre>    # we initialize the frontier (our FIFO queue)<br>    curShell = [node]<br>    # a set to keep track of the nodes whose distance has been calculated<br>    distance_set = set()<br>    # the distance to self is obviously zero so it is calculated<br>    distance_set.add(node)</pre><pre>    l = 0<br>    while len(curShell):<br>        nextShell = []<br>        for curNode in curShell:<br>            neighbors = net.GetNeighbors(curNode)<br>            <br>            for n in neighbors:<br>                if n not in distance_set:<br>                    distances[n] = l + 1<br>                    nextShell.append(n)<br>                    distance_set.add(n)<br>        # update the frontier<br>        curShell = nextShell<br>        # increase the distance to be assigned to the next shell<br>        l = l + 1</pre><pre>    return distances</pre><p>Having the function for the distances, we can easily implement a function utilising a for loop that calculates the distances of every pair in the network. Having all the pairwise distances, we can then plot the histogram for our network.</p><p><strong>3. Statistics</strong></p><p>We can plot a distribution of the path lengths for the network:</p><pre>def HistAllPathLengths(net):<br>    &quot;&quot;&quot;Plots a histogram of the pair-wise distances&quot;&quot;&quot;<br>    all_nodes = net.GetNodes()<br>    distances = []<br>    for node in all_nodes:<br>        temp = FindPathLengthsFromNode(net, node)<br>        del temp[node]<br>        distances.extend(list(temp.values()))<br>    <br>    # plot the histogram of distances<br>    plt.hist(np.array(distances), bins=int(net.L**0.5))<br>    plt.savefig(&#39;hist.png&#39;)</pre><p>For various values of the probability p and fixed population N and nearest neighbours Z, we can plot the average path with the code below. We also normalize the results with respect to the average path of the case with no shortcuts (p=0)</p><pre>def AveragePathAgainstP(N,Z,p_list):<br>    &quot;&quot;&quot;Plots the average path of the network for different p values&quot;&quot;&quot;<br>    average_paths = []</pre><pre>    net = Network(N,Z,p=0)<br>    net.ConstructNetwork()<br>    normalize = FindAveragePathLength(net)</pre><pre>    for p in p_list:<br>        net = Network(N,Z,p)<br>        net.ConstructNetwork()<br>        av_path = FindAveragePathLength(net)<br>        average_paths.append(av_path/normalize)<br>    averages = np.array(average_paths)<br>    p_values = np.array(p_list)<br>    plot.figure()<br>    plt.xscale(&quot;log&quot;)<br>    plt.plot(p_values, averages)<br>    plt.xlabel(&#39;probability p&#39;)<br>    plt.ylabel(&#39;average distance / distance for p = 0&#39;)<br>    plt.savefig(&#39;averages_p.png&#39;)</pre><h3>Conclusion (and future work)</h3><p>Network theory and especially Random Networks are a fascinating and very active area of research where a lot of complex problems arise. Interesting real-world applications are constantly devised that can be viewed as random graphs and have far-reaching implications on life sciences, engineering, computer science, social science etc. See [1] and the ‘See also’ references therein.</p><p>The area is vast and varied, it is impossible to give a suggestion that covers every possible corner or idea, but some interesting reads are the following (no link is affiliate):</p><ol><li><a href="https://www.amazon.co.uk/Linked-Everything-Connected-Business-Everyday/dp/0465085733?asin=0465085733&amp;revisionId=&amp;format=4&amp;depth=1">Linked: How Everything Is Connected to Everything Else and What It Means for Business, Science, and Everyday Life , by Albert-László Barabási</a></li><li><a href="https://www.amazon.co.uk/Small-Worlds-Randomness-Princeton-Complexity/dp/0691117047">Small Worlds: The Dynamics of Networks between Order and Randomness, by Duncan J. Watts</a></li><li><a href="https://www.amazon.co.uk/Networks-Mark-Newman-dp-0198805098/dp/0198805098/ref=dp_ob_title_bk">Networks: Second Edition, by Mark Newman</a></li></ol><p>In a next article we will dive into a real dataset trying to find if the 6-degree rule holds! We will also implement the DFS for finding the centrality of a node.</p><blockquote>Until then, you jump 3 steps my way and I will find a friend of a friend of a friend to jump 3 steps your way…</blockquote><blockquote>Or we could simply connect on LinkedIn: <a href="https://www.linkedin.com/in/marios-kokmotos/">Marios Kokmotos | LinkedIn</a></blockquote><p>Thanks for your time, I hope you found this interesting!</p><p>I would be happy to discuss further in the comments below, don’t hesitate to leave one with your thoughts, any mistakes that you spot or any other suggestions.</p><h3>References:</h3><p>[1]<a href="https://en.wikipedia.org/wiki/Random_graph">Random graph — Wikipedia</a></p><p>[2]<a href="https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model">Erdős–Rényi model — Wikipedia</a></p><p>[3] <a href="https://en.wikipedia.org/wiki/Bianconi%E2%80%93Barab%C3%A1si_model">Bianconi–Barabási model — Wikipedia</a></p><p>[4] <a href="https://en.wikipedia.org/wiki/Percolation_theory">Percolation theory — Wikipedia</a></p><p>[5] <a href="https://en.wikipedia.org/wiki/Complex_network">Complex network — Wikipedia</a></p><p>[6] <a href="https://en.wikipedia.org/wiki/Small-world_network">Small-world network — Wikipedia</a></p><p>[7] <a href="https://en.wikipedia.org/wiki/Watts%E2%80%93Strogatz_model">Watts–Strogatz model — Wikipedia</a></p><p>[8] Watts DJ, Strogatz SH (June 1998). “Collective dynamics of ‘small-world’ networks”. <em>Nature</em>. <strong>393</strong> (6684): 440–2.</p><p>[9]<a href="https://arxiv.org/abs/cond-mat/0303516#"> The structure and function of complex networks — M. E. J. Newman</a></p><p>[10] <a href="https://arxiv.org/abs/cond-mat/0001118">Models of the Small World: A Review — M. E. J. Newman</a></p><p><strong><em>The article is heavily based on exercise 1.7 of James Sethna’s book, ‘Statistical Mechanics, Entropy, Order Parameters, and Complexity’</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8f82a16893" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple Classification example (ML_Zoomcamp)]]></title>
            <link>https://medium.com/@marioskokmotos2/a-simple-classification-example-ml-zoomcamp-cc3ba571a024?source=rss-a988d8b4ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc3ba571a024</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[sklearn-metrics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Marios Kokmotos]]></dc:creator>
            <pubDate>Wed, 05 Oct 2022 20:48:10 GMT</pubDate>
            <atom:updated>2022-10-05T20:48:10.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOvzmBEDeOg4fPhtJ7nuYw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@io_exception?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Antonio Feregrino</a> on <a href="https://unsplash.com/s/photos/crossroads?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Classification is one of the major categories of supervised machine learning problems (the other being <a href="https://medium.com/@marioskokmotos2/a-simple-linear-regression-problem-from-scratch-ml-zoomcamp-86b853c349c5">regression</a>) and as the name suggests it boils down to classifying our data observations in one or more categories. That is to say that we select the most probable class that we think our data observation belongs to (hard classification) or output a series of probabilities that our observation belongs to each one of the classes in the problem (soft classification) with the obvious constraint that they have to add up to 1.</p><p>In this article we’ll go through a simple classification problem and the relevant considerations for the metrics when developing a model.</p><ol><li>The problem and the data</li><li>Setting up the framework</li><li>Selecting the metrics</li><li>Why accuracy is not enough</li><li>Precision and Recall</li><li>F1 Score</li><li>ROC AUC Score</li><li>The Model</li><li>Conclusion</li></ol><h3>The Problem and the Data</h3><p>The problem will be a classification task of whether an application for a credit card is approved or not. The data comes from the book “Econometric Analysis” and the dataset can be found on Kaggle (<a href="https://www.kaggle.com/datasets/dansbecker/aer-credit-card-data">Credit Card dataset</a>). Our goal is to build a model that predicts the approval of a credit card application and inspect the quality of the model using various metrics.</p><p>We start by importing some useful libraries as standard and the relevant data.</p><pre>#We import the libraries and the data<br><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> numpy <strong>as</strong> np<br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt</pre><pre># import the data<br>data <strong>=</strong> pd<strong>.</strong>read_csv(&#39;AER_credit_card_data.csv&#39;)</pre><p>We continue with the standard approach of taking a first look at some properties of our dataset,</p><pre>data<strong>.</strong>head()</pre><figure><img alt="The first few rows of the data" src="https://cdn-images-1.medium.com/max/735/1*nRmI2RuwgtwV9aOeKMMTEA.png" /></figure><pre>print(data<strong>.</strong>shape)</pre><pre>(1319, 12)</pre><p>We see that we have 12 columns in our dataset, one of which will be our target variable (the one we are trying to predict). This will be the ‘card’ column which signifies approval or rejection of a credit card application.</p><p>We can also see that we have a lot of columns which have a yes/no value. We can make them boolean by replacing with 1 or 0 respectively.</p><pre>data <strong>=</strong> data<strong>.</strong>replace([&#39;yes&#39;,&#39;no&#39;],[1,0])</pre><p>Now the summary of the columns is as follows:</p><pre>data<strong>.</strong>info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*DZZLwoBI0sA2F_ZXIaaHRA.png" /></figure><p>We can also see that the dataset has no missing values. Let’s also get a statistical description of all the numerical columns. This is a useful step for detecting unphysical values and errors in the data as well as get a first idea of the distribution of values.</p><pre>data<strong>.</strong>describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*NOCWY6j4lgAuSHk9jj9a4w.png" /></figure><p>As a last step at this stage, we split our data columns in features and target variable</p><pre>y <strong>=</strong> data[&#39;card&#39;]<br>X <strong>=</strong> data<strong>.</strong>drop([&#39;card&#39;], axis<strong>=</strong>1)</pre><h3>Setting up the framework</h3><p>As usual, the framework consists of splitting the data in train, validation and test sets. Following the <em>‘golden rule’</em> we set the test set aside and for now we behave as if it doesn’t exist. Only at the end of our project will we apply our model to the test set.</p><p>We’ve seen that the data consist of 1319 samples, so a reasonable split would be 60%/20%/20% for train, validation and test sets respectively.</p><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split</pre><pre>X_temp, X_test, y_temp, y_test <strong>=</strong> train_test_split(X, y, test_size<strong>=</strong>0.2, random_state<strong>=</strong>1)<br>X_train, X_val, y_train, y_val <strong>=</strong> train_test_split(X_temp, y_temp, test_size<strong>=</strong>0.25 , random_state<strong>=</strong>1)</pre><pre>print(X_train<strong>.</strong>shape, y_train<strong>.</strong>shape)<br>print(X_val<strong>.</strong>shape, y_val<strong>.</strong>shape)<br>print(X_test<strong>.</strong>shape, y_test<strong>.</strong>shape)</pre><p>(791, 11) (791,)<br>(264, 11) (264,)<br>(264, 11) (264,)</p><h3>Selecting the metrics</h3><p>As a first step, accuracy is always a reasonable metric that we want to maximise when dealing with a classification problem. We want our model to be able to correctly classify the data observations to their respective true classes. We want to maximise the following sum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*kYorjBec004HK0SV4ma3Aw.png" /></figure><p>Where <em>I</em> is the indicator function which takes the value 1 only when the argument is true, otherwise takes the value 0. In simple terms, accuracy is the average number of correctly classified observations.</p><h3>Why accuracy is not enough</h3><p>Be it as it may, accuracy is a very intuitive indicator of model performance, but is not enough in a lot of cases.</p><p>Imagine for example that we have a model that needs to classify our observations between two classes, let’s call them in a binary fashion, 1 and 0. Consider the situation where our sample data (and the population data) are distributed in such a way where only 1% of the data points belong to class 1. In such a case, a very dummy classifier that always predicts class 0 would have a 99% accuracy! However, this tells us nothing about its ability to detect the class 1 data, which is terrible. In fact, it cannot predict class 1 data by construction.</p><p>From the above simple example it is evident that accuracy is not enough as a metric, especially when we have a high imbalance of classes. We need some more metrics that can provide us with insights of the model performance and help with model training.</p><p>Enter Precision and Recall.</p><h3>Precision and Recall</h3><p>Before we give a simple definition for Precision and Recall, it is useful to introduce some terminology.</p><p><strong>True Positives</strong>: are those that have been predicted by the model as belonging to the positive class (in our case class 1) and indeed belong to that class.</p><p><strong>True Negatives</strong>: are those that have been predicted by the model as belonging to the negative class (in our case class 0) and indeed belong to that class.</p><p><strong>False Positives</strong>: are those that have been predicted by the model as belonging to the positive class (in our case class 1) but in truth belong to class 0.</p><p><strong>False Negatives</strong>: are those that have been predicted by the model as belonging to the negative class (in our case class 0) but in truth belong to class 1.</p><p>In layman’s terms, Precision is the ratio of the true positives over all that have been predicted as positives (including the False Positives)</p><p><strong>Precision = TP / (TP + FP)</strong></p><p>while Recall is the ratio of the predicted true positives over all that in truth belong to the positive class (this includes True Positives that have been correctly classified by the model and False Negatives that have been incorrectly classified as negatives but are in truth positives).</p><p><strong>Recall = TP / (TP + FN)</strong></p><p>Recall is also known as True Positive Rate (TPR).</p><p>So, if we go back to our dummy classifier example, while the accuracy is 99% (let’s consider a sample of 100 points), the Recall will be 0/(0+1) = 0 and the Precision will be 0/(0 + 0) which is undefined and ill-posed since the model by construction is unable to predict the positive.</p><h3>F1 Score</h3><p>Usually what we want to achieve is the best of both worlds. We want both a good precision and a good recall for our model. Unfortunately, we cannot maximise both at the same time, but we can find the best model that achieves a good enough performance with respect to both. For this we introduce another metric that takes into consideration both precision and recall. It is called the F1 and is basically the harmonic mean of precision and recall defined as:</p><figure><img alt="Definition of F1 score" src="https://cdn-images-1.medium.com/max/260/1*VJ-naXkyDOGk0v8JlSnNIQ.png" /></figure><p>You can <a href="https://en.wikipedia.org/wiki/F-score">learn more about this</a> here.</p><p>We can also get a summary of our model’s performance by looking at the classification report (we’ll see later how)</p><pre><strong>from</strong> sklearn.metrics <strong>import</strong> classification_report</pre><h3>ROC AUC Score</h3><p>Another very useful metric is the area under curve (AUC) of the ROC curve. The ROC curve (Receiver operating characteristic, a name derived from radar systems) is basically a plot of the true positive rate (TPR) against the false positive rate (FPR) for different values of threshold.</p><p>The TPR (Recall) has been defined previously:</p><p><strong>TPR =</strong> <strong>TP / (TP + FN)</strong></p><p>while the FPR is defined as the ratio of False Positives over all truly negatives (meaning the ones that have erroneously been predicted as positives and those that have correctly been predicted as negatives):</p><p><strong>FPR = FP/N = FP/(FP+TN)</strong></p><p>Intuitively, we want our model to maximize the TPR while at the same time minimizing the FPR. This is ideally we want to touch the top left corner where the TPR is 1 and the FPR is 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*IdyCr4d9XYQ3mLOAQTpqrQ.png" /><figcaption>ROC curve of the model presented in the next section</figcaption></figure><p>As the name suggests, AUC is the area under the ROC. The maximum value is 1 and the higher score, obviously, the better. We also see that a random model, for every threshold predicts equally true and false labels. In other words, the threshold does not affect it because the model never looks at it, it just assigns classes at random!</p><p>Now, what are the thresholds? They are simply the points where our model considers the separation of the classes. E.g a threshold of 0.6 means that if the predicted probability of an example is above 0.6 then it will be classified as positive whereas if it is below that value it will be classified as the negative class. We see that a very low threshold (e.g. 0) will have a very high TPR since all positive examples will be assigned to the positive class, but at the same time all negative examples will also be assigned to the positive class, thus a high FPR.</p><h3>The Model</h3><p>For our project the selected model will be that of the Logistic Regression. You can learn more about the <a href="https://en.wikipedia.org/wiki/Logistic_regression">algorithm behind the model</a> here. It is sufficient to know that the model approximates the log-odds as a linear function. Log-odds is simply the logarithm of the ratio of the probabilities between class 1 and class 0.</p><p>Let’s build the model by simply calling:</p><pre><strong>from</strong> sklearn.linear_model <strong>import</strong> LogisticRegression<br><br>logreg <strong>=</strong> LogisticRegression(solver<strong>=</strong>&#39;liblinear&#39;,C<strong>=</strong>1.0,max_iter<strong>=</strong>1000)</pre><p>and then we simply fit the model to the training data</p><pre>logreg<strong>.</strong>fit(X_train, y_train)</pre><p>Now that we have fit the model, we can make predictions on the validation test to see how well it generally performs. We want to predict the probability of getting the positive class 1 for each sample in the validation set.</p><pre>y_val_pred <strong>=</strong> logreg<strong>.</strong>predict_proba(X_val)[:,1]</pre><p>In order to see what the performance is we can calculate the ROC AUC Score. We do that with the next line</p><pre><strong>from</strong> sklearn.metrics <strong>import</strong> roc_auc_score</pre><pre>print(&quot;AUC score: &quot;,round(roc_auc_score(y_val, y_val_pred),3))</pre><p>AUC score: 0.995</p><p>A very good score!</p><p>The classification report gives:</p><pre><strong>from</strong> sklearn.metrics <strong>import</strong> classification_report</pre><pre>y_pred = logreg.predict(X_val)</pre><pre>print(classification_report(y_val, y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*f8w-QcSLm4lpjwMxzdSYhg.png" /><figcaption>classification report</figcaption></figure><p>Which includes the accuracy of the model, the f1-score and the precision, recall.</p><p><em>(from the sklearn site): The reported averages include macro average (averaging the unweighted mean per label), weighted average (averaging the support-weighted mean per label), and sample average (only for multilabel classification).</em></p><p>In our case, Macro averaging is:</p><p>macro_precision = (1+0.88)/2 = 0.94</p><p>macro_recall = (0.98+0.97)/2 = 0.97 (rounded)</p><h3>Conclusion</h3><p>In this article we’ve seen a pretty simple classification problem of Credit Card related data that has been approached with a Logistic Regression model.</p><p>There are tons of things that can be said and added to our analysis and here we’ve only scratched the surface, but we have demonstrated some important topics that always arise in classification problems.</p><p>I hope you liked the article and have found it useful. Rest assured that we’ll come back to classification problems in the future focusing more on other aspects of the analysis such as Exploratory Data Analysis and Cross-Validation of our models!</p><p>Stay tuned!</p><p>Let’s connect: <a href="https://www.linkedin.com/in/marios-kokmotos">https://www.linkedin.com/in/marios-kokmotos</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc3ba571a024" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autodidact’s path to AI/Machine Learning (part 2)]]></title>
            <link>https://medium.com/@marioskokmotos2/autodidacts-path-to-ai-machine-learning-part-2-bead9686e381?source=rss-a988d8b4ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bead9686e381</guid>
            <category><![CDATA[self-taught]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Marios Kokmotos]]></dc:creator>
            <pubDate>Sat, 24 Sep 2022 18:25:21 GMT</pubDate>
            <atom:updated>2022-09-24T18:25:21.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4QpdBM516FvHCha1B67-Yw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alina Grubnyak</a> on <a href="https://unsplash.com/s/photos/network?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In the first part of the <a href="https://medium.com/@marioskokmotos2/autodidacts-path-to-ai-machine-learning-part-1-48e0f665ec90">Autodidacts path</a> to a MSc level in AI/Machine Learning, using UCL’s MSc as a lighthouse to guide us through the rough waters of building a Machine Learning MSc curriculum, we had a look at some of the most established and helpful resources for a beginning ML engineer.</p><p>Moving on to the second part of our attempt to build a curriculum for the autodidact enthusiast of Machine Learning, we will dive into one of the hot topics during the past decade. This is no other than Deep Learning.</p><p>Although technically a sub-category of Machine Learning, Deep Learning has evolved into its own paradigm and has earned the title of ‘<em>one of the pillars of ML’</em> and for good reasons. The past decade has seen a huge number of successful applications and technological advancements that utilise Deep Learning. Deep Learning algorithms and architectures have helped solved some very interesting and — until now — almost intractable problems but have also provided a lot of fun applications. Deep Learning is a paradigm of Machine Learning where the workhorse is the concept of neural networks. Neural networks are algorithms, mathematical constructs that are translated in programmes and in their basic forms they consist of nodes (realized with the help of data structures) and computations (realized as actions performed on data). As you can infer from the name, their abstract architecture is that of a network. Nodes perform actions on data and are connected to each other by exchanging data. This over-simplified description of what a Neural Network is doesn’t do justice to such a beautiful concept, but I recommend you search online for a more detailed description. It suffices to know that a network is a convenient way of seeing how the actions are performed on data.</p><p>There is a plethora of good resources out there. Fantastic YouTube channels that do a better job at explaining the concepts than a lot of university professors, videos that show you how to apply the concepts by building real-life projects and even how to create your own state-of-the-art chatbot or model that creates art.</p><p>Unfortunately, there is neither the time nor the space to document all of these (although we will try to at least mention some of them) so we’ll have to revert to a more classic approach. We’ll present some well-established resources that can be proven useful to a beginner as well as a more experienced ML engineer.</p><p>The goal here is to present resources that can act as the stepping stone to enter the Deep Learning world, and we’ll dive into more specific areas such as Computer Vision and NLP in a future article.</p><h3>Assumptions on background knowledge</h3><p>Just like core Machine Learning, Deep Learning is a sophisticated area that requires certain background knowledge. Luckily, the ubiquity of frameworks and libraries make the job easier, but they don’t — nor should they — save you from the need to understand what you are building and how your model should work. This is where mathematical maturity and programming skills enter the game. Linear Algebra is a must, while well-honed Python skills are needed. This means you have to be comfortable with OOP and the whole Numpy stack, you need to know how to multiply matrices (a lot of matrices!) and would be more than helpful to have a solid understanding of ML as presented in parts of <a href="https://medium.com/@marioskokmotos2/autodidacts-path-to-ai-machine-learning-part-1-48e0f665ec90">Autodidacts path part 1</a> (mostly about the approach).</p><h3>Introductory Resources</h3><p>Some resources grouped by cost and increasing difficulty from a beginner’s perspective.</p><p><strong>Totally free Courses</strong></p><ul><li><a href="https://d2l.ai/index.html">Dive into Deep Learning</a> — If you are a beginner in DL but have a fair background in ML (as described in the 1st part of this series) then this is a very good place to start. Created by scientists and faculty members in top US universities such as Stanford and Carnegie Mellon, this course provides a thorough beginner-friendly introduction to Deep Learning. A big bonus (besides it is totally free!) is the fact that the examples are provided in both PyTorch and Tensorflow (two of the most well-known frameworks for DL) along with recorded lectures.</li><li><a href="https://www.fast.ai/">Fast.ai</a> — An attempt to democratise Deep Learning, the instructors of this course have made a huge effort to simplify the required background for a Deep Learning journey. There is also a book of a similar title and mindset that closely follows the course, as well a whole library that helps you build models. On the website, you’ll find more than one courses and definitely one of them will catch your eye!</li><li><a href="https://cs230.stanford.edu/">Andrew Ng’s Stanford Course</a> — The natural continuation of the famous Machine Learning course. A very nice overview of the field. It is highly recommended to supplement this course with the <a href="https://www.coursera.org/specializations/deep-learning">Coursera version</a> which is much more detailed at some points and also free (requires paid access to certain items).</li><li><a href="https://cds.nyu.edu/deep-learning/">Yann LeCun’s Deep Learning Course at CDS</a> — A course by one of the fathers of Deep Learning. I dare say it is a little bit unorthodox in its delivery approach and syllabus compared to the other entries in the list but is definitely something you wouldn’t miss (perhaps after you had a look at one of the above). It is a complete course with notebooks and lectures.</li></ul><p><strong>Paid Courses</strong></p><ul><li>Udemy (£10-£14 /course): £ /course. Udemy has a lot of courses to choose from, but you have to choose wisely. Usually, the high-rated courses are sufficient to get you started in an applied fashion and help you build some projects to display in your portfolio. I have found really interesting the courses by <strong><em>The Lazy Programmer, Zero to Mastery </em></strong>and <strong><em>Jose Portilla.</em></strong></li><li><a href="https://www.coursera.org/specializations/deep-learning">Deep Learning Ng Coursera specialization</a>: ££ /month. This has also been mentioned in the list above but finds its way here for completeness. The cost depends inversely on the time you invest and how fast you can move through the courses. <em>(Note: It is possible to finish the specialization in 2 months)</em></li><li><a href="https://www.coursera.org/professional-certificates/tensorflow-in-practice">AI TensorFlow Developer Certificate Coursera Specialization</a>: ££/month. Another specialization by Deeplearning.ai on Coursera that focus on the practical use of TensorFlow and prepares you for the Developer Certificate. It complements nicely the specialization above and there is also a book by the instructor, Laurence Moroney, that closely follows the course.</li><li><a href="https://www.udacity.com/course/deep-learning-nanodegree--nd101">Deep Learning Nanodegree Udacity</a>: ££££/month. Udacity offers a wide selection of semester-long courses that provide lectures, guidance and projects. It is quite pricier than the rest and perhaps there are equal quality if not better resources to start with. It makes the list as a well-round resource and due to personal experience with it.</li></ul><p><strong>Books</strong></p><p>Some interesting books with an applied approach to the subject are the following:</p><ul><li><a href="https://www.amazon.co.uk/Deep-Learning-Coders-fastai-PyTorch/dp/1492045527/ref=sr_1_1?crid=3HGL2UXWQ9CIA&amp;keywords=deep+learning+for+coders+with+fastai+and+pytorch&amp;qid=1664043258&amp;sprefix=deep+learn%2Caps%2C116&amp;sr=8-1">Deep Learning with Fast.ai</a> — The complement book to Fast.ai courses.</li><li><a href="https://www.amazon.co.uk/Machine-Learning-PyTorch-Scikit-Learn-learning/dp/1801819319/ref=sr_1_3_sspa?crid=3HGL2UXWQ9CIA&amp;keywords=deep+learning+for+coders+with+fastai+and+pytorch&amp;qid=1664043258&amp;sprefix=deep+learn%2Caps%2C116&amp;sr=8-3-spons&amp;psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEzRlM0S0ZTT0FTT0g2JmVuY3J5cHRlZElkPUEwMDE5NTk5MzZTR0RBRUFCMVhITCZlbmNyeXB0ZWRBZElkPUEwODUxOTczM0JBOFBWN1VDVEUxWSZ3aWRnZXROYW1lPXNwX2F0ZiZhY3Rpb249Y2xpY2tSZWRpcmVjdCZkb05vdExvZ0NsaWNrPXRydWU=">Machine Learning with PyTorch</a> — A very nice introduction to Deep Learning with PyTorch.</li><li><a href="https://www.amazon.co.uk/Machine-Learning-Coders-Programmers-Intelligence/dp/1492078190/ref=sr_1_7?crid=3HGL2UXWQ9CIA&amp;keywords=deep+learning+for+coders+with+fastai+and+pytorch&amp;qid=1664043258&amp;sprefix=deep+learn%2Caps%2C116&amp;sr=8-7">AI and Machine Learning For Coders</a> — The complement book to the Coursera Specialization.</li><li><a href="https://www.amazon.co.uk/Deep-Learning-Pytorch-Eli-Stevens/dp/1617295264/ref=sr_1_11_sspa?crid=3HGL2UXWQ9CIA&amp;keywords=deep+learning+for+coders+with+fastai+and+pytorch&amp;qid=1664043258&amp;sprefix=deep+learn%2Caps%2C116&amp;sr=8-11-spons&amp;psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEzRlM0S0ZTT0FTT0g2JmVuY3J5cHRlZElkPUEwMDE5NTk5MzZTR0RBRUFCMVhITCZlbmNyeXB0ZWRBZElkPUEwMDk2MjkxMjc0OFlZREZSSDBFNyZ3aWRnZXROYW1lPXNwX210ZiZhY3Rpb249Y2xpY2tSZWRpcmVjdCZkb05vdExvZ0NsaWNrPXRydWU=">Deep Learning with PyTorch</a> — A classic introduction to PyTorch.</li></ul><p>My personal choice would be to start with the free resources. Depending on your preferences and what you’d like to focus on (e.g. computer vision, NLP etc) you can follow-up on these with projects that you can find through tutorials online or even articles here on Medium.</p><h3>Theoretical/Mathematical Resources</h3><p>Besides the extremely interesting projects one can build with the above resources, the theory behind Deep Learning is interesting on its own. A good background in Linear Algebra and Probability theory is required at an undergraduate level.</p><p>THE textbook regarding Deep Neural networks is none other than:</p><ul><li><a href="https://www.deeplearningbook.org/">Goodfellow, Bengio and Courville book</a> — A golden standard in Deep Learning theory. Mostly oriented towards the mathematical underpinnings of the theory. You won’t find code written in here, but I believe this book deserves a place in any practitioner’s library.</li></ul><p>There can be found chapters on Neural Networks in most modern ML Textbooks out there, including:</p><ul><li><a href="https://www.amazon.co.uk/Probabilistic-Machine-Learning-Introduction-Computation/dp/0262046822/?_encoding=UTF8&amp;pd_rd_w=VyJn8&amp;content-id=amzn1.sym.9987c01f-79a1-401b-8cc0-4469362e1651&amp;pf_rd_p=9987c01f-79a1-401b-8cc0-4469362e1651&amp;pf_rd_r=T5CN50AJSPTWXQW6TG55&amp;pd_rd_wg=Opzzt&amp;pd_rd_r=57c5a7ea-85f8-4187-8ebb-0836eb1e9a32&amp;ref_=pd_gw_ci_mcx_mr_hp_atf_m&amp;asin=B094X9M689&amp;revisionId=1082b543&amp;format=1&amp;depth=1">Kevin Murphy’s great Probabilistic ML textbook</a></li><li><a href="https://www.amazon.co.uk/Elements-Statistical-Learning-Springer-Statistics/dp/0387848576/ref=pd_rhf_d_gw_s_pd_crcd_sccl_1_4/262-5212715-5395441?pd_rd_w=6wXIy&amp;content-id=amzn1.sym.48cd8206-854f-4d53-baa5-acd3460f23ee&amp;pf_rd_p=48cd8206-854f-4d53-baa5-acd3460f23ee&amp;pf_rd_r=5QM49FX0SVNAJFGDRR1T&amp;pd_rd_wg=lly0J&amp;pd_rd_r=6d9b0faa-a1ad-4d88-9a08-20071c383a7c&amp;pd_rd_i=0387848576&amp;psc=1&amp;asin=0387848576&amp;revisionId=&amp;format=4&amp;depth=1">Elements of Statistical Learning</a></li><li><a href="https://www.amazon.co.uk/Machine-Learning-Bayesian-Optimization-Perspective/dp/0128188030/ref=sr_1_6?crid=2N4RYFM7FA5S5&amp;keywords=theodoridis&amp;qid=1664040718&amp;s=books&amp;sprefix=theodoridis%2Cstripbooks%2C98&amp;sr=1-6&amp;asin=0128188030&amp;revisionId=&amp;format=4&amp;depth=1">Machine Learning, Theodoridis</a></li></ul><p>But most likely, you’ll find yourself returning to Goodfellow’s et. al. bible.</p><h3>Projects and interesting applications</h3><p>Throughout the past decade numerous applications of Deep Neural Networks have made an impact and have stolen the spotlight from more traditional Machine Learning algorithms. This is not without merit since we’ve witnessed a lot of instances where the models have achieved super-human performance. They are able to classify images among thousands of classes with a smaller error than humans, they can detect cancer (melanoma, breast cancer etc) in patients at a specialised human’s level and can seamlessly hold a conversation (I am talking about you GPT-3…!) that makes you think it passes the <a href="https://en.wikipedia.org/wiki/Turing_test">Turing test</a>. They’ve solved <a href="https://www.deepmind.com/research/highlighted-research/alphago">Go</a> and Chess…even <a href="https://openai.com/five/">DOTA</a>.</p><p>Bringing it more down-to-earth, we can also create useful and interesting projects without necessarily spending millions on training the models. A lot of companies such as DeepMind, Google and OpenAI have made their models available to the public for free! This gives us a head start when building our own applications. The concept of <strong>transfer learning</strong> is what comes to mind here. By exploiting pre-trained models, we can achieve high accuracy scores for our own specific application by training only few of the last layers of our model (which consists of pre-trained layers appended by our layers pertinent to our application).</p><p><strong>Youtube channels</strong></p><p>Some nice YouTube channels including a lot of tutorials:</p><ul><li><a href="https://www.youtube.com/c/Freecodecamp">FreeCodeCamp.org</a></li><li><a href="https://www.youtube.com/c/RohanPaul-AI">Rohan Paul — AI</a></li><li><a href="https://www.youtube.com/c/sentdex">Sentdex</a></li><li><a href="https://www.youtube.com/c/NicholasRenotte">Nicholas Renotte</a></li></ul><h3>Conclusion</h3><p>Deep Learning is probably one of the most important advancements in Artificial Intelligence in the last 10–15 years. The GPU technology and new algorithms have made it possible to train huge models that in a lot of cases outperform humans in vision and language tasks. This alone, unequivocally makes it a hot topic that can make a difference and you should care about!</p><p>Stay tuned for the next parts of the Autodidact’s curriculum…</p><p>I would be happy to know your thoughts below and whether you’ve used these resources yourself!</p><p><em>Disclaimer: No links are affiliate.</em></p><p>Let’s connect: <a href="https://www.linkedin.com/in/marios-kokmotos">https://www.linkedin.com/in/marios-kokmotos</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bead9686e381" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple Linear Regression problem from scratch (ML Zoomcamp)]]></title>
            <link>https://medium.com/@marioskokmotos2/a-simple-linear-regression-problem-from-scratch-ml-zoomcamp-86b853c349c5?source=rss-a988d8b4ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/86b853c349c5</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <dc:creator><![CDATA[Marios Kokmotos]]></dc:creator>
            <pubDate>Wed, 21 Sep 2022 20:31:37 GMT</pubDate>
            <atom:updated>2022-09-21T20:31:37.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTMMF6NqU8ExcrTiabmKsw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@boontohhgraphy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sorasak</a> on <a href="https://unsplash.com/s/photos/plane?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Linear Regression is possibly everyone’s first contact with Machine Learning, although it predates ML by some hundreds of years!</em></p><p><em>(The photo was selected as a ‘hyper-plane’, pun fully intended)</em></p><p>In a previous post, I shared some resources especially oriented towards beginners in Machine Learning. — <a href="https://medium.com/@marioskokmotos2/autodidacts-path-to-ai-machine-learning-part-1-48e0f665ec90">Autodidacts path to AI/ML Part 1</a>— One that I highly recommend is the ML Zoomcamp. While it assumes prior experience in Python and some ML related packages such as Numpy and Pandas, it basically introduces the student to ML from an applied perspective with hands-on projects. The curriculum could be considered complete as it includes projects ranging from Linear Regression and Classification to Model Deployment and Deep Learning.</p><p>In this post we will go through a first simple example of Linear Regression which also is one of the first projects of the course. The problem is that of the house prices prediction based on the well-known dataset as can be found on Kaggle (<a href="https://www.kaggle.com/datasets/camnugent/california-housing-prices">California Housing Prices</a>).</p><p>Below is an outline and implementation of the steps:</p><ol><li>Data preparation — we get the data and select what we’ll use</li><li>EDA — we perform a simple exploration and observation of data</li><li>Train-test framework — we split our data</li><li>Linear Regression — the model</li><li>Regularization and tuning the model — select the best model for our data</li></ol><h3>Data preparation</h3><p>The first step is to acquire the data and inspect its characteristics. The Pandas library comes in very handy in these kind of tabular data problems. We first import the library ready to be used and then read the csv file that we have already downloaded previously from the Kaggle website (or any other data source that suits us).</p><p>We print the shape of the dataframe (here named in the very imaginative name ‘data’). This will help us to identify how many examples we have in our dataset, and most importantly how many features we have. We also print the head of the file (5 rows by default) to get an idea of how the data looks.</p><pre><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt</pre><pre><strong># Read the csv file containing the data</strong><br>data <strong>=</strong> pd<strong>.</strong>read_csv(&#39;housing.csv&#39;)</pre><pre><strong># Print the shape of the dataframe</strong><br>print(&quot;data shape: &quot;,data<strong>.</strong>shape)</pre><pre><strong># Print the first few lines of the dataframe</strong><br>data<strong>.</strong>head()</pre><p>data shape: (20640, 10)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ZuVGx6jrQvK1Fp9xAn48bA.png" /></figure><p>Out of all the columns that we have in our dataset, the next question is:</p><p><em>What is the quantity that we’re trying to predict?</em></p><p>In our problem the aim is to predict the house prices as they appear in the Median house value. The fact that the value to be predicted is a continuous number makes it a regression problem. A very simple but quite useful first approach is Linear Regression. Despite its simplicity and the fact that it has been around for centuries, Linear Regression often proves to be the workhorse of many industries (in one form or another) and surely one of the first approaches to be tested during development and definition of a baseline.</p><p>We can plot the distribution of the target value to get an idea of the proportions of different values that we have in our dataset and whether our models of choice are expected to perform well or not.</p><blockquote>It is always wise to keep in mind that different ML algorithms build on top of different assumptions about the underlying data and that no single algorithm will outperform all others in every single problem out there.</blockquote><p>That said, we plot the distribution of the target value.</p><pre>plt<strong>.</strong>hist(data[&#39;median_house_value&#39;], bins<strong>=</strong>50)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*zU7tleWVabVmCY8GA9dyEA.png" /><figcaption>The ‘median house value’ histogram</figcaption></figure><p>We see that the distribution of the target variable (median house value) is quite skewed. We can also see quite a few values high median values at the right end of the spectrum. We see that the distribution is well-behaved, and no transformation seems to be necessary.</p><p>To keep it simple we will only keep the numerical features and will perform our analysis based only on these. In other words, we will discard the ‘ocean_proximity’ (feature describing qualitatively the distance of the house from the sea) feature which is, however, expected to have an impact on the value of the house. Rest assured that we will treat a problem with categorical features in a different post.</p><pre><strong># select the columns</strong><br>cols <strong>=</strong> [&#39;latitude&#39;,&#39;longitude&#39;,&#39;housing_median_age&#39;,&#39;total_rooms&#39;,&#39;total_bedrooms&#39;,&#39;population&#39;,&#39;households&#39;,&#39;median_income&#39;,&#39;median_house_value&#39;]</pre><pre>data <strong>=</strong> data[cols]</pre><h3>Exploratory Data Analysis (EDA)</h3><p>The next step once we set up our data is to start doing a more serious exploration. This includes checking for missing values and other abnormalities in data such as unphysically high or low values, negative values where there shouldn’t be any and of course…outliers.</p><p>We will start by checking whether we have any Null values (a.k.a NaN, n/a etc). This is an important first step since all the algorithms that we use in ML require a certain availability of data to be able to operate as expected. An algorithm needs to know the data it needs to perform on, because…well it is an abstract construct that has a very well-defined realization as a computer program.</p><p>The line below prints the number of entries that have a Null value for each one of the features (columns) of our dataset.</p><pre>data<strong>.</strong>isnull()<strong>.</strong>sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*Z8rLGTgVDq7gY5I5O2ANWQ.png" /></figure><p>If any Null values are detected, we can decide how we will treat the missing values in a next step. We see that here we have 207 missing values in the ‘total_bedrooms’ column.</p><p>A recommended step is to also check the data types of the features and some additional information specific to the numerical features (the features that are basically represented as numbers). In contrast to numerical features, the categorical features represent a qualitative characteristic of the data. In our case, the original ‘ocean_proximity’ feature is a categorical one since it represents in a qualitative way where the house is located with respect to the sea. For the original dataset (including the ‘ocean_proximity’ column) we would have:</p><pre>data.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*PLezByzzLrB2957mConR7w.png" /></figure><p>We see that the ‘ocean_proximity’ is of type object which means it is of a data type that cannot be readily considered a number. Note that strings can be of type object and is usually worth it to explicitly check whether it is erroneously assigned as an object while it should be a number. Note also the number of non-null values for the ‘total_bedrooms’ column which is less than the total number of entries 20640.</p><pre><strong># print some statistics</strong><br>data.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*mEPtE7xN0BWC03xCJQ0phA.png" /></figure><p>For the numerical columns we can also get some statistics as shown above. It includes the mean and the standard deviation for each column as well as some quantiles.</p><h3>Set up the train-validation-test framework</h3><p>The golden rule of the train-validation-test framework is very simple and as a rule of thumb can be stated as:</p><blockquote>Once you get the data, separate the test set and forget about it!</blockquote><p>It really saves you a lot of frustration and erroneous approaches to data once you do that. The reasoning behind that is quite simple. You don’t want to have leakage of information between your train and test sets. The sole purpose of a test set is to simulate a real-life scenario where your model won’t have access to the future data that it might encounter. Hence, you don’t want the training of your model to rely on the test set in any way.</p><p>There is an underlying assumption here though, and that is that the train and test sets have similar probability distributions of the data in the high-dimensional space that is constructed by the features. In other words, it doesn’t make any sense to train a model based on data that only contain a specific type of house, call it type-A, and expect it to perform well on predicting the price of a totally different type, call it type-B. As we can understand, a fair split of the data will help with that.</p><p>That said, the golden rule is a quite simple and general approach. Once you do the fair split, where you make sure that the data are thoroughly shuffled, and your training examples approach the i.i.d state (independent and identically distributed) as much as possible, then you forget about the test data until the very end, where you will do one and only last check of the model.</p><p>We can create a function that will be used to split the data and return a train set, a validation set and a test set. The function below is a simple — and not the most efficient — implementation of a split function. A typical split ratio would be 60% training data, 20% validation and 20% test data.</p><p>As we’ve mentioned, the test data will be set aside, and we forget it for now. The training data will be used to train the model while the validation data will be used to fine-tune the parameters of a model.</p><pre><strong>def</strong> split_data(data, train_ratio <strong>=</strong> 0.6, test_ratio <strong>=</strong>0.2, val_ratio <strong>=</strong> 0.2):</pre><pre>    <strong># we create a random shuffle of the dataset indexes</strong><br>    idx <strong>=</strong> np<strong>.</strong>arange(data<strong>.</strong>shape[0])<br>    np<strong>.</strong>random<strong>.</strong>shuffle(idx)</pre><pre>    <strong># we find the indexes that we&#39;ll split</strong><br>    train <strong>=</strong> int(train_ratio<strong>*</strong>len(idx))<br>    test <strong>=</strong> int(test_ratio<strong>*</strong>len(idx))<br>    val <strong>=</strong> int(val_ratio<strong>*</strong>len(idx))<br>    <br>    <strong>assert</strong> train_ratio <strong>+</strong> val_ratio <strong>+</strong> test_ratio <strong>==</strong> 1</pre><pre>    y <strong>=</strong> data[&#39;median_house_value&#39;]<strong>.</strong>copy()<br>    X <strong>=</strong> data<strong>.</strong>drop([&#39;median_house_value&#39;], axis<strong>=</strong>1)<strong>.</strong>copy()<br>    <br>    <strong># we create our train, validation and test datasets</strong><br>    X_train <strong>=</strong> X<strong>.</strong>iloc[:train]<br>    X_val <strong>=</strong> X<strong>.</strong>iloc[train:train<strong>+</strong>val]<br>    X_test <strong>=</strong> X<strong>.</strong>iloc[<strong>-</strong>test:]</pre><pre>    y_train <strong>=</strong> np<strong>.</strong>log1p(y<strong>.</strong>iloc[:train])<br>    y_val <strong>=</strong> np<strong>.</strong>log1p(y<strong>.</strong>iloc[train:train<strong>+</strong>val])<br>    y_test <strong>=</strong> np<strong>.</strong>log1p(y<strong>.</strong>iloc[<strong>-</strong>test:])</pre><pre><strong>    return</strong> X_train, X_val, X_test, y_train, y_val, y_test</pre><p>Once we have the split data, we can decide what to do with the missing values. In our case we decided to fill in the missing value using the mean value of the training set for that specific feature. Other valid choices would be to use the median, another statistic or even just zero. Note that whatever we choose it is the training set that dictates the value, because this is what the model sees and trains on.</p><pre>mean_bedrooms <strong>=</strong> X_train[&#39;total_bedrooms&#39;]<strong>.</strong>mean()<br>X_train_mean <strong>=</strong> X_train<strong>.</strong>fillna(mean_bedrooms)</pre><h3>Linear regression in vector form, The normal equation</h3><p>The next step is to build the model. In our case the model is a simple linear regression. We construct the Linear Regression model in vector form, also known as the Normal Equation which is the solution to the Least Squares problem (see <a href="https://en.wikipedia.org/wiki/Ordinary_least_squares">Ordinary least squares — Wikipedia</a>). Provided that the columns of the X matrix are linearly independent and that the number of features is not creating an over-determined situation, so that the inversion of the matrices is possible,</p><p>assuming a solution of the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/1*U-bdnju6Be_CClf1_kT34A.png" /></figure><p>solving the optimization problem for a least squares loss function, we have for the vector of unknowns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*CZKowYqmM-04DnfsS_V-5w.png" /></figure><pre><strong>def</strong> train_linear_regression(X, y):<br>    ones <strong>=</strong> np<strong>.</strong>ones(X<strong>.</strong>shape[0])<br>    X <strong>=</strong> np<strong>.</strong>column_stack([ones, X])<br>    XTX <strong>=</strong> X<strong>.</strong>T <strong>@</strong> X<br>    XTX_inv <strong>=</strong> np<strong>.</strong>linalg<strong>.</strong>inv(XTX)<br>    w <strong>=</strong> XTX_inv <strong>@</strong> (X<strong>.</strong>T) <strong>@</strong> (y)<br>    <strong>return</strong> w[0], w[1:]</pre><p>We initially add a column of ones to the data which corresponds to the constant term in the linear equation. We calculate the Gram matrix X^T*X and then its inverse using the Linear Algebra functions provided by Numpy. As a last step we calculate the vector of coefficients w as per the equation above.</p><p>It is well-known that this method is not the most efficient especially for high-dimensional spaces, because the matrix inversion has a time complexity of O(n³) in the number of features. To overcome this high computational complexity, usually numerical iterative methods are used such as Stochastic Gradient Descent etc.</p><h3>The baseline model</h3><p>We have to select a model that will act as our baseline. This is usually the simplest model that can make predictions based on our data. In our case this could be a model that just always predicts the mean of the target variable, that is it would always give as a prediction mean(y_train) and would disregard any effect of the features.</p><p>Another model that could act as baseline would be the one calculated by the Normal Equation. As we will see later on, we can build models that contain hyperparameters to be fine-tuned in search of the best possible performance. These models would then be compared with the baseline and the best one would be selected.</p><h3>Error metrics and performance</h3><p>But how do we score our models? How do we set our baseline and how do we compare them?</p><p>For this we need a metric of performance. In the Linear Regression case, a common metric is the Root Mean Squared Error (RMSE). This is simply (starting from the left) the root of the average of the squared differences between the predicted target value and the actual target value. In other words, we first calculate the differences of the predicted values and the actual values for each one of our data samples, we then square these differences, take their average (for a non-weighted average this is simply a summation and division by the number of samples) and finally we take the square root of that. So, the RMSE is measured in the same units as the target variable y.</p><pre><strong>def</strong> RMSE(y_true, y_pred):<br>    <strong>return</strong> (np<strong>.</strong>sum((y_true <strong>-</strong> y_pred)<strong>**</strong>2) <strong>/</strong> y_true<strong>.</strong>shape[0]) <strong>**</strong> 0.5</pre><p>In our case we will select as our baseline model, the model that results from the normal equation shown above. The model has a training set RMSE , and a validation RMSE .</p><p>Let’s get our baseline model trained on the X_train where the missing values have been filled in with the average of each column:</p><pre><strong># baseline model</strong><br>w0, w = train_linear_regression(X_train_mean, y_train)</pre><p>Our model is basically the coefficients w0 and w, where w0 is a constant and w is a vector of 8 numbers, as many as the features (columns) that are used for prediction.</p><p>To calculate our RMSE performance, we first have to make some predictions. We will make the predictions on our validation dataset.</p><pre>y_pred = w0 + X_val_mean @ w</pre><p>Where the X_val_mean is the validation dataset with the missing values being filled in with the mean of the corresponding feature in the X_train.</p><pre>X_val_mean = X_val.fillna(mean_bedrooms)</pre><p>It is time now to calculate the RMSE, for this we simply do:</p><pre>RMSE(y_val, y_pred)</pre><p>After calculating the performance of our model according to the RMSE metric, it would be a good time to go back and check that the underlying assumptions of the Linear Regression are indeed satisfied.</p><h3>Feature engineering</h3><p>It is often the case that we are not satisfied with our model’s performance, and we would like to see it increased. The features might not be informative enough by themselves or they might be inducing noise in the dataset that our model would have a hard time trying to fit to.</p><p>Feature engineering is the concept of modifying the features with the aim of improving the performance. This could include scaling the features or combining them to create new meaningful ones. The new features could replace the old ones leading to a lower dimension space. If they are informative enough, they can lead to better performance since the model will have less chances of overfitting or can even gain access to a new feature that can explain the phenomenon better than its constituents. Think of having a new feature that is a nonlinear combination of some original ones. This would mean we now have access to a nonlinear relationship in the data, that can pretty much take any shape that we want. In that way we can approximate arbitrary mathematical relationships between the features and the target variable. It is easy to see that there needs to be balance in the complexity that we introduce otherwise we can find ourselves with an overfitting model that fails to generalize.</p><h3>Regularization</h3><p>It is often the case that the model overfits on the training data. That is, the model is learning by memorizing the data. This is of course something undesirable since we want our model to be able to generalize well to unseen data. In other words, we want our model to perform relatively well even at the expense of a reduced performance, on a range of different feature values. This is a common problem when the model is overly complex or we have very little data examples to train on compared to the number of features. In an intuitive way, having a lot of features puts pressure on a model to find the specific combination of the <strong><em>w </em></strong>components that minimize the loss. The system is under-determined which means that it has more unknowns (the components of the w vector) than equations (the training examples that satisfy the linear equations). An under-determined system can have multiple solutions (specific combinations of values for the components of w).</p><p>Regularization techniques come to the rescue! The idea behind this is to penalize the vector of the unknowns in some way by adding an extra term to the loss function that the algorithm tries to minimize. Usually that penalization is an L² or L¹ norm, meaning simply that we either try to minimize the euclidean norm of the w vector, or the sum of the absolute values of its components. The important thing to remember is that the penalization is basically a restriction on the possible w-vectors that we can have which stems from the need to keep the total loss at an optimal value.</p><p>In the normal equation approach, overfitting can occur due to linearly dependent features, which can cause the Gram matrix to be non-invertible. The L² regularization manifests itself as an additional term including the identity matrix. Without getting too much into the mathematics, this makes the inversion of the Gram matrix always possible, which means that we can always find a solution.</p><pre><strong>def</strong> train_linear_regression_reg(X, y, r<strong>=</strong>0.0):<br>    ones <strong>=</strong> np<strong>.</strong>ones(X<strong>.</strong>shape[0])<br>    X <strong>=</strong> np<strong>.</strong>column_stack([ones, X])<br>    XTX <strong>=</strong> X<strong>.</strong>T<strong>.</strong>dot(X)<br>    reg <strong>=</strong> r <strong>*</strong> np<strong>.</strong>eye(XTX<strong>.</strong>shape[0])<br>    XTX <strong>=</strong> XTX <strong>+</strong> reg<br>    XTX_inv <strong>=</strong> np<strong>.</strong>linalg<strong>.</strong>inv(XTX)<br>    w <strong>=</strong> XTX_inv<strong>.</strong>dot(X<strong>.</strong>T)<strong>.</strong>dot(y)<br>    <br>    <strong>return</strong> w[0], w[1:]</pre><h3>Tuning the model</h3><p>Fine-tuning the model requires us to tune the hyperparameters of the model. In our case, the hyperparameter (externally modified by us) is the regularization coefficient <strong><em>r </em></strong>with which we multiply the identity matrix.</p><p>Our job here is to find that value of <strong><em>r</em></strong> that leads to the best performance of the model. Since it would be impossible to test all possible values, we will select a few and compare the performance of the corresponding models.</p><pre>for r in [0, 0.000001, 0.0001, 0.001, 0.01, 0.1, 1, 5, 10]:<br>    w0, w = train_linear_regression_reg(X_train_zero, y_train, r)<br>    y_pred = w0 + X_val_zero.dot(w)<br>    print(f&#39;{r:10.6f} {RMSE(y_pred, y_val):8.4f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*X7ebqLodA8lab66rPpixoA.png" /><figcaption>regularization parameter ‘r’ with the corresponding RMSE</figcaption></figure><p>We can see that the regularization strength can affect the RMSE of the model as calculated on the validation set. Based on that we can pick the best model and eventually test it on the test data. This will be the last trial before we finalize our project.</p><h3>Using the model</h3><p>We are finally ready to put the model in good use! We simply insert the feature values in the linear equation.</p><pre>y = w0 + X @ w</pre><p>This gives us the predicted value of the house once we are given its other characteristics as contained in the vector X.</p><h3><strong>Conclusion</strong></h3><p>This concludes this lengthy article on a simple Linear Regression problem. Linear Regression is perhaps the simplest, but many times, a well-performing algorithm and can be certainly used as a first approach for a baseline model. One of the advantages of the algorithm is its interpretability and the low computational complexity and power that it requires for its training.</p><p>I hope you found that useful.</p><p>Stay tuned for more ML articles!</p><p>Happy Machine Learning!</p><p>LinkedIn: <a href="https://www.linkedin.com/in/marios-kokmotos/">Marios Kokmotos | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86b853c349c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autodidact’s path to AI/Machine Learning (part 1)]]></title>
            <link>https://medium.com/@marioskokmotos2/autodidacts-path-to-ai-machine-learning-part-1-48e0f665ec90?source=rss-a988d8b4ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/48e0f665ec90</guid>
            <category><![CDATA[self-taught]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[masters-degree]]></category>
            <category><![CDATA[curriculum]]></category>
            <dc:creator><![CDATA[Marios Kokmotos]]></dc:creator>
            <pubDate>Sat, 10 Sep 2022 14:48:29 GMT</pubDate>
            <atom:updated>2022-09-20T13:07:33.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QZ7z6FhVTzpk8xg9tHn1g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tomhermans?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tom Hermans</a> on <a href="https://unsplash.com/s/photos/books?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Beyond the hype of Machine Learning and Artificial Intelligence that we have witnessed the past decade, lies something truly remarkable; the ability of machines to think, or rather our ability to devise techniques and make them ‘think’. To make them think fast and in scale, serving us in ways that the human insight might not be able to wander or comprehend.</p><p>It has been deemed the “hottest job of the 21st century”. I am sure a lot of enthusiasts out there would want to work for big companies such as FAANG (Facebook, Amazon, Apple, Netflix, Google) each one of them major players and pioneers in their respective domains, wouldn’t they? And more importantly… who has ever thought ‘If only I had that MSc in Artificial Intelligence from<em> -insert university’s name here-</em>...that would pave the way for me to land a job in one of those firms.</p><p>Well...I for one, definitely have thought about it. It is not a secret that some of those companies — if not all — no longer consider a MSc a major requirement to assign you to their roaster, however it is no secret either that many aspiring ML/AI engineers would happily acquire a MSc that would boost their confidence to apply for a job like this.</p><p>There comes the catch however… not everyone has the resources, economical or otherwise to chase that goal. Being unable to allocate time to a formal course in a university due to time and funding limitations, I thought I should give it a try by ‘copying’ the curriculum of a very prestigious university programme on AI. Being a resident in the UK, what better candidate than the <em>UCL’s (University College London) Data Science and Machine Learning MSc</em> course? UCL is one of the most renowned and prestigious institutions (see rankings), more importantly, this specific programme seems — at least to my eyes — a quite deep and broad approach to a plethora of subsects pertinent to classical and modern AI.</p><p>So, why not try and follow their curriculum then? Well, I am in no way affiliated with UCL, hence I have no access to their exact class material, so I thought I would build up my own curriculum with theirs as a guide. This in itself is a disclaimer that stresses the fact that unavoidably the curriculum I’ll be presenting is ONLY INSPIRED BY UCL and by no means strictly equivalent.</p><p>This will be part of a post series revolving around the huge domain of Artificial Intelligence. We will attempt to build a complete Master’s level curriculum that would surely boost the confidence of an AI enthusiast or prospective engineer/scientist. Roughly speaking, part 1 will be all about the core ML, part 2 about Deep Learning, part 3 about Reinforcement Learning, part 4 Miscellaneous, part 5 Robotics and modern applications.</p><p>We will try to provide a time schedule and cost of all the recommended resources as well as a rough outline for various scenarios.</p><p>As an extra disclaimer, that will probably act as a ruler to measure what I feel is an adequate background, I hold a MEng in Electrical Engineering and Computer Science with a fairly strong background in mathematics and an intermediate grasp of Programming and Computer science. That translates into good grasp of Linear Algebra, Calculus, Probabilities and an intermediate exposure to Python and C++. After all, who can claim to be an expert? What defines perfection? It’s all a constant struggle…</p><p>First things first. I will assume a beginner/intermediate level of knowledge in Python. If an absolute beginner and in need of an introduction to the language, I would definitely recommend freeCodeCamp (an excellent endeavour for which we all should be grateful) whose videos can be found online.</p><p>Without further ado..</p><h3><strong>Basics of ML</strong></h3><p>Goals:</p><p>Starting with the basics of ML and given a good understanding of Python under our belt (see OOP etc) we can move to Applied Machine Learning. At this stage deep understanding of the mechanics of sophisticated algorithms is not required at all. It is sufficient to understand the high-level way that 5 to 10 major algorithms work and how to tune their hyperparameters. How to set-up a simple ML pipeline for your personal projects will come in very handy and understand basic but foundational methods of data pre-processing.</p><p>Resources (increasing difficulty):</p><p><strong>1.</strong><a href="https://github.com/alexeygrigorev/mlbookcamp-code/tree/master/course-zoomcamp"><strong>ML Zoomcamp</strong></a> — A very well structured and broad online bootcamp-style course that is available for free and has been developed <em>by Alexey Grigorev, </em>and it is based on his book<em> </em><a href="https://mlbookcamp.com/">Machine Learning Bookcamp (mlbookcamp.com)</a></p><p>2. <a href="https://www.mikegelbart.com/"><strong>Mike Gelbart’s</strong></a><strong> </strong>lectures of various UBC (University of British Columbia) courses. The undergraduate courses are exactly what you need to get you started in Applied ML while their graduate (UBC Master of Data Science courses) counterparts will get you going to the next level. A lot of the materials are available on Github while most of the lectures are available on YouTube.</p><p>3. <a href="https://www.cs.columbia.edu/~amueller/comsw4995s20/schedule/"><strong>Applied ML</strong></a><strong> by Andreas C. Müller — </strong>A master’s level course from Columbia University and one of Scikit-learn’s core developers. A very interesting course with a lot of insights. A tad bit more advanced than the previous entry in the list.</p><p>4. <a href="https://sebastianraschka.com/teaching/"><strong>Sebastian Raschka’s lectures</strong></a><strong> </strong>contain a bit more mathematical theory regarding the inner workings of ML algorithms but are definitely a joy to watch. Still at the undergraduate level, they can be a very helping hand to get you to the starting MSc level. Sebastian has made available online both the lectures and his notes and we couldn’t be more grateful about that!</p><p><strong><em>Bonus:</em></strong><em> Andrew Ng’s Machine Learning specialization on Coursera (this will be analysed in a future post). This couldn’t be absent from the list. The course has received a full make-over recently and has become even more accessible to beginners. You will learn next to one of the ‘celebrities’ of the ML community and one of the first that started making ML education accessible to the masses back in 2012. If you feel you’d like it more rigorous then the next one is for you.</em></p><p>5. <a href="http://cs229.stanford.edu/syllabus-summer2019.html"><strong>Stanford’s CS229</strong></a><strong>.</strong> The original course that Andrew Ng taught (this instance is taught by another instructor) including detailed notes and lectures. With the mathematical rigor you’d expect from a Stanford graduate course this makes it a very strong candidate for bringing you to that coveted MSc level.</p><p>Bits and pieces of the above would be in close alignment to UCL’s <em>‘Introduction to Machine Learning (COMP0088)’</em>. Of course, 100% overlap is not to be expected and perhaps at this level the mathematical rigor with which the concepts are presented is not sufficient to be considered a Master’s level approach. However, it is a major first step into Applied ML and surely, the resources presented above set a strong foundation to delve further into the theory at a later stage.</p><p>Concepts that are covered in the resources above include:</p><blockquote>########## Introduction to Supervised Learning</blockquote><blockquote>- Linear models for regression and classification: least squares, logistic regression.</blockquote><blockquote>- Concepts of overfitting and regularisation, L1 and L2 regularisation.</blockquote><blockquote>- Boosting, Decision Trees, Random Forests.</blockquote><blockquote>- Support Vector Machines.</blockquote><blockquote>- Deep Learning: Neural Networks for regression and classification, Convolutional Neural Networks, Recurrent Neural Networks.</blockquote><blockquote>########## Introduction to Unsupervised Learning</blockquote><blockquote>- K-means, Principal Components Analysis, Embeddings</blockquote><blockquote>- Deep Autoencoders, Generative Adversarial Networks.</blockquote><h3>A bit more theory</h3><p>When we get a good grasp of how to apply various ML algorithms and how to set-up our problems and data, we can dive a little bit more into the mechanics of the algorithms. Before starting reading research papers (we’ll get there) you can have a look at some free books that introduce a more mathematical approach to various algorithms:</p><p><a href="https://www.microsoft.com/en-us/research/publication/pattern-recognition-machine-learning/"><strong>1.Pattern Recognition by Christopher Bishop</strong></a> — An ‘oldie’ but valuable resource to any aspiring ML engineer’s library. Definitely one of the best expositions of the subject out there, heavy in mathematics but… purely awesome!</p><p>2. <a href="https://www.statlearning.com/"><strong>An Introduction to Statistical Learning (statlearning.com)</strong></a> — A more easily digestible attempt than the previous item in the list, now in its 2nd edition, it has also become a classic. It provides a smoother introduction and perhaps less mathematical rigor than Bishop’s text, but remains enjoyable and with a lot of clarity on some of the most important ML algorithms</p><p><strong>3.</strong><a href="https://probml.github.io/pml-book/book1.html"><strong>Probabilistic ML by Kevin Murphy </strong></a>— If you feel the above items are light on mathematics and want to see a Bayesian approach of ML, then Kevin Murphy’s book might be exactly what you were searching for. Note of caution, it requires a pretty good grasp of mathematics at the graduate level (something that we’ll come back to in a future post).</p><h3><strong>Practicing</strong></h3><p>But, because you don’t learn how to ride a bike just by reading a book or watching your friends doing it…</p><p><strong>Datacamp and Kaggle:</strong></p><p>Are the go-to places to practise your newly acquired skills on toy datasets or even — why not? — competitions. Additionally, Kaggle provides free mini-courses that give an introduction and the necessary tooling to dive into some practical projects.</p><p><strong>Personal Projects</strong></p><p>Just get out there and start analysing datasets foraging for insights or building some projects on these datasets that could be used by a layperson. The projects could range from simple models to predict a person’s proneness to a disease or the probability that they would like a particular movie… Or if you feel extravagant, build some models that predict stock prices (although that is believed to be somewhat impossible!) or other business related issues.</p><p>At this stage, it is not about building the next high-performing model that will achieve 99.99% accuracy and will save a company billions… the idea is rather to start developing projects according to your interests. This will be proven invaluable in your next career interview! Just make it happen, build an end-to-end system that would perform well even if the approach or code would never find its way to production.</p><p>A plethora of interesting datasets can be found both on <a href="https://www.kaggle.com/datasets">Find Open Datasets and Machine Learning Projects | Kaggle</a> and the <a href="https://archive-beta.ics.uci.edu/ml/datasets">UCI Machine Learning Repository</a>. The additional advantage of Kaggle is that a lot of times you’ll be able to find notebooks with other people’s solutions or approaches to specific datasets. This can be a powerful tool in your development as an AI/ML Engineer.</p><p>Whether you are after applied knowledge or a more mathematical approach (or even philosophical!) to Machine Learning, the resources presented here will surely keep you busy and entertained!</p><p>Get out there and enjoy what ML has to offer!</p><p>Stay tuned for the next parts of the Autodidact’s curriculum…</p><p>I would be happy to know your thoughts below and whether you’ve used these resources yourself!</p><p>Let’s connect: <a href="https://www.linkedin.com/in/marios-kokmotos">https://www.linkedin.com/in/marios-kokmotos</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48e0f665ec90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Linear Algebra resources for Data Scientists and ML Engineers.]]></title>
            <link>https://medium.com/@marioskokmotos2/5-linear-algebra-resources-for-data-scientists-and-ml-engineers-2c6a75c0f98b?source=rss-a988d8b4ddd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c6a75c0f98b</guid>
            <category><![CDATA[linear-algebra]]></category>
            <dc:creator><![CDATA[Marios Kokmotos]]></dc:creator>
            <pubDate>Sat, 03 Sep 2022 17:41:39 GMT</pubDate>
            <atom:updated>2022-09-03T17:46:23.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQ19-d_afVzDOuYqYwFbzw.jpeg" /><figcaption>credit: author</figcaption></figure><p>Linear Algebra is considered as a distinct branch of mathematics. It has a tremendous impact both on other branches of pure mathematics as well as the more applied branches, especially engineering. Its beauty and power stem from its ability to seamlessly tread through dimensions and help the practitioner (in this case, a Data Scientist or Machine Learning engineer) to extract information and value from their data.</p><p>It is considered a standard course in every engineering and science curriculum as the techniques and frameworks presented in it can be utilised to solve problems ranging from optimization and control systems to probabilistic models. Even the infamous Quantum Theory makes heavy use of the Linear Algebra tools. It is hard to overstate its importance and yet it is frequently ignored in one’s journey in Data Science and Machine Learning. Ready-to-go frameworks and software packages, albeit important and helpful to abstract away many of the details, sometimes steal a bit from the glory of mathematics and of such a beautiful mathematical theory.</p><p>While admittedly it is not everyone’s cup of tea, it definitely deserves a chance to let it fascinate us.</p><p>As happens with almost everything nowadays, there is a plethora of resources, videos, courses and books that can be found online and cover a broad range of topics and at various levels of difficulty. This post is my approach to highlight 5 of these resources, that helped me through my university years and continue to do so in my career. Although some of them are not freely available on the web, there are free related resources to each one of these that can be used as supplementary material.</p><h3><strong>1)</strong>Introduction to Linear Algebra<strong>, by Gilbert Strang</strong></h3><p>By now a classic from one of MIT’s top professors. It has already been through numerous editions and reprints, and it still is one of the recommended textbooks in every syllabus around the world. As the recommended textbook for my 1st year’s university course, it not only helped me achieve a great grade but more importantly professor Strang taught me a lot about the applicability of a mathematical subject in real-life scenarios. The applications are entertaining (not an easy achievement for a maths textbook) and it doesn’t cease to fascinate me how simple structures and relative straightforward maths construct the baseline of modern methods that are used in research and production. Network Graphs, Markov Chains, Linear Regression, Fourier Series..you name it, can be expressed as a Linear Algebra problem.</p><p><strong><em>Bonus:</em></strong> The accompanying lectures of Professor Strang’s courses at MIT are freely available on the institute’s Open Courseware platform or the corresponding YouTube channel.</p><h3>2) Linear Algebra Done Right, by Sheldon Axler</h3><p>A book for the more mathematically-inclined. It presents theorems and applications in a more abstract approach. It sets the framework in more rigorous mathematics and includes a lot of notions and concepts that would not really interest an Applied Data Scientist or Machine Learning Engineer. Despite this, knowing the foundations can be really helpful if you want to deep-dive into the mechanics of ML algorithms, or if your role contains the word ‘Research’ within it.</p><p>Bonus: On the author’s website (or YouTube channel) you can find some supplementary videos for the book as well as a free abridged version.</p><p>Bonus 2: For the even more hardcore math lovers (or Research Scientist), the author has made available his other book <em>Measure, Integration &amp; Real Analysis </em>free for download.</p><h3>3) Linear Algebra and Optimization for Machine Learning: A Textbook, by Charu C. Aggarwal</h3><p>Although not freely-available, it couldn’t be left out of the list. As the title suggests, it has a Machine Learning focus and covers (almost) all the Optimization and Linear Algebra knowledge you will need for a role in Data Science or Machine Learning if you want to really understand the algorithms you are using or even go as far as reading research papers. It contains a lot of exercises and insights that transcend to the applications of ML and is not just a theoretical textbook.</p><p>It’s winning feature is the combination of Linear Algebra and Optimization, two of the pillars of modern ML. It really is a gem of its time!</p><h3>4) Introduction to Applied Linear Algebra: Vectors, Matrices, and Least Squares, by Stephen Boyd and Lieven Vandenberghe</h3><p>Another one of my favourites, especially if it is your first contact with Linear Algebra. Professors Boyd (from Stanford) and Vandenberghe (from UCLA) (also well known for their textbook on Convex Optimization and its accompanying material among others) have written an exceptional undergraduate textbook that introduces the student to all the major concepts of Linear Algebra, always with a data-oriented Machine Learning or Control Systems flavour in mind. Huge bonus of the book is that it is freely-available for download from <a href="https://web.stanford.edu/~boyd/vmls/">Introduction to Applied Linear Algebra — Vectors, Matrices, and Least Squares (stanford.edu)</a>.</p><p>Whether it is your first encounter of Linear Algebra or you want a refresher during a couple of weekend trips, this is my most highly-recommended entry of the list.</p><p><strong><em>Bonus</em></strong>: On the same website, you can find accompanying lecture videos, slides, additional exercises as well as code implementation.</p><h3>5) Elementary Linear Algebra: Applications Version, by Howard Anton, Chris Rorres, Anton Kaul</h3><p>A very interesting undergraduate book following the same approach as that of Strang’s and with a similar style of writing. Quite a bit comprehensive at the level it treats the subject, it includes a rather lengthy chapter on applications (compared to Strang)…it is in the name after all. If you want to see some simple but very interesting examples of Linear Algebra in action, this would be a good start.</p><p><em>Conclusion:</em></p><p>If you are an aspiring Data Science or ML Engineer, I am sure that the above 5 suggestions along with their supplementary material will be more than enough to get you started or even bring you at the MSc level where you would be able to understand a huge portion of mathematics present in research papers.</p><p>Enjoy reading!</p><p><em>Disclaimer: No links are affiliate</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c6a75c0f98b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>