<?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 Ege Hosgungor on Medium]]></title>
        <description><![CDATA[Stories by Ege Hosgungor on Medium]]></description>
        <link>https://medium.com/@hosgungor?source=rss-e31e18aedeb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gczTsmYa1Y2txvhXypS-PQ.jpeg</url>
            <title>Stories by Ege Hosgungor on Medium</title>
            <link>https://medium.com/@hosgungor?source=rss-e31e18aedeb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:43:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hosgungor/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[Top 5 Books That Made Me Question My Career in 2024]]></title>
            <link>https://hosgungor.medium.com/top-5-books-that-made-me-question-my-career-in-2024-8c1baf20f16e?source=rss-e31e18aedeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c1baf20f16e</guid>
            <category><![CDATA[stem]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[careers]]></category>
            <dc:creator><![CDATA[Ege Hosgungor]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 15:52:16 GMT</pubDate>
            <atom:updated>2024-12-30T15:52:16.433Z</atom:updated>
            <content:encoded><![CDATA[<p>Here we are finishing 2024, and Data World is at an all-time high, in terms of innovations, weekly new models breaking SOTA records in benchmarks. Finally, data is receiving the recognition it deserves in different domains like Robotics, Biology, Chemistry, basically becoming mainstream.</p><p>Yet newcomers to the industry are disappointed. In one side we are truly started to feel the power of Data Science and on the other side it already started causing mass layoffs, cost cuts in core departments, and replacing many knowledge worker’s daily jobs. I have been feeling anxious about this for almost 4 years now, when I first tried the GPT-3 and the technology only kept getting better. As a Data Scientist who works in Robotics. With that in mind, here are the five books that had the greatest influence on me this year.</p><h3><strong>A Personal List:</strong></h3><h3>5. The Coming Wave by Mustafa Suleyman</h3><figure><img alt="The Coming Wave: Technology, Power, and the Twenty-first Century’s Greatest Dilemma" src="https://cdn-images-1.medium.com/max/263/0*U8rIE7_fFPB65YTl.jpg" /><figcaption>The Coming Wave: Technology, Power, and the Twenty-first Century’s Greatest Dilemma</figcaption></figure><p>Although I read this book on December 23rd (published on September 5, 2023), the author’s ideas stayed with me for a long time. Why is it ranked 5th? Because technology evolves so quickly that some ideas become obsolete within a year. Mustafa Suleyman discusses how technology comes in waves and is without bounds. He highlights how current advancements in AI and biology are on the rise, but they could be catastrophic if placed in the wrong hands.</p><p>It would have been easy to dismiss his ideas with a “yeah, right,” but this man was behind one of the most influential research companies (DeepMind), so his words carry extra weight. I can’t deny that this book gave me sleepless nights, as I pondered future job security, nuclear threats, biological risks, and more.</p><h3>4. The Book of Why by Pearl Judea</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*1_t0yKeXuX2nYl7x.jpg" /><figcaption>The Book of Why: The New Science of Cause and Effect</figcaption></figure><p>An eye-opening book for a Data Scientist, this one had been on my radar for a long time, ever since <a href="https://gordicaleksa.com/">Aleksa Gordić</a> mentioned that he enjoyed it many years ago. I finally gave it a go. How on earth did I miss an entire domain in Data Science? I still wonder. This book defied my expectations of Penguin Publishing, which often releases works like <em>Outliers</em> by Malcolm Gladwell — books that stretch 300 pages without saying much.</p><p>Beware, this book sits somewhere between a highly technical textbook and a bedtime read—if you can imagine such a thing. Why is it ranked 4th on my list? While it introduced me to the fascinating domain of &quot;Causal Inference&quot; and opened my eyes to new possibilities, it doesn’t dive deeply into the details. Instead, it offers a high-level overview of some key concepts. You’ll definitely need supplemental materials to fully grasp those ideas later.</p><p>That said, it was a wonderful introduction to a captivating field. The author is a pivotal figure in Causal Inference and the inventor of Bayesian Networks. However, I docked one star for the author’s evident ego. :) While you’ll certainly feel his passion for causation, his confidence can occasionally feel… overwhelming. That said, he’s probably right in most cases!</p><h3>3. The Lean Startup by Eric Rise</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*1JFwWPErTGf2-oCX.jpg" /></figure><p>It’s always good to nurture your entrepreneurial side, even when working in a big company. Most impactful changes come from challenging the status quo and being innovative. <em>The Lean Startup</em> taught me about “validated learning,” one of the most important concepts I learned this year.</p><p>Validated learning is essentially a systematic approach to determining whether a business idea is viable by testing hypotheses through real-world experiments and making data-driven decisions based on the results. There are two key aspects of validated learning:</p><ol><li><strong>A Feedback-Rich Environment</strong>: An environment where you can receive timely, accurate, and actionable feedback.</li><li><strong>Measurable Outcomes</strong>: Clearly defined metrics that guide decision-making.</li></ol><p>What makes this approach so powerful is that these two principles apply not only to building businesses but also to learning in general — whether for humans or machines operating through reinforcement learning. Math is incredible in this sense; it doesn’t discriminate between humans and robots — it works universally!</p><h3>2. Deep Work by Cal Newport</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/0*UOjPDS-rG8c9dFJ5.jpg" /></figure><p>For some, this book is as cheesy as it gets, merely stating things we already know. For others, it doesn’t belong in a top 5 list, let alone in 2nd place. While I agree that some of the content felt familiar, sometimes it’s invaluable to hear an outside perspective on what you’re doing wrong.</p><p>Lately, I’ve been struggling with a lack of motivation (probably influenced by the 5th book on the list, <em>The Coming Way</em>), and this book definitely lifted me up and helped reignite my drive. It discusses how we are addicted to dopamine, how routines can help us produce more valuable work, and how the meaningful work limit for most people is around 4 hours per day. The book emphasizes that pushing yourself beyond that limit can harm your motivation in the long run. Overdoing it today makes it increasingly harder to motivate yourself tomorrow.</p><p>Even writing this blog post was partially made possible thanks to this book, so I believe it deserves its spot on the list!</p><h3>1. Trustworthy Online Controlled Experiments: A Practical Guide to A/B Testing by Ron Kohavi, Diane Tang, Ya XU</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*NibpLwMYzGkqQcX-.jpg" /></figure><p>As I mentioned, this is a personal top 5 list, and if there’s one book that truly helped me in my work this year, it’s this one! I’ve been working on A/B testing projects and analyses that support critical decision-making. For the longest time, I thought A/B testing was simply about splitting data and testing a hypothesis. But thanks to “<em>The Book of Why” (4th Book)</em>, I realized there’s so much more to these questions than mere correlations. The harder, but more rewarding, challenges lie in understanding causation. How do you answer those? This practical book provides the tools to do just that.</p><p>Why is this book so influential? Because, as I noted earlier, the AI revolution is here. It’s already automating many white-collar jobs, and it will only improve from here. However, there are still aspects that large language models (for now) can’t replicate — particularly the social and contextual elements of these roles.</p><p>This realization left me with two career paths: one as a hardcore AI engineer, where I would build models, develop architectures, and work on cutting-edge technologies like transformers — a technically impressive but highly replaceable role. The other path is the more social side of Data Science: creating hypotheses, running experiments, making assumptions, and leveraging domain knowledge. This side focuses on understanding data and its generation, requiring expertise that’s harder to automate.</p><p>For now, I feel this second path is a better fit for me — not because it’s inherently better but because it allows me to shine, make a greater impact, and, most importantly, enjoy what I do.</p><h3>Conclusion</h3><p>As we wrap up 2024, the world of data science is thriving like never before, with groundbreaking innovation. Yet, the rapid pace of advancement brings challenges, including job displacement and shifts in industry dynamics. Amid this whirlwind, these five books profoundly impacted my outlook on data science and my career trajectory.</p><p>While many experiences, discussions, and challenges have shaped how I view my career, these five books stood out as the most impactful.</p><p>5. <em>The Coming Wave </em>by Mustafa Suleyman</p><p>4.<em> The Book of Why</em> by Judea Pearl</p><p>3. <em>The Lean Startup</em> by Eric Ries</p><p>2. <em>Deep Work </em>by Cal Newport</p><ol><li><em>Trustworthy Online Controlled Experiments: A Practical Guide to A/B Testing by </em>Ron Kohavi, Diane Tang, Ya XU</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c1baf20f16e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things That Made Me a Better Software Engineer]]></title>
            <link>https://hosgungor.medium.com/things-that-made-me-a-better-software-engineer-94257694d4de?source=rss-e31e18aedeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/94257694d4de</guid>
            <category><![CDATA[reccomendations]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[data-scientist-career]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ege Hosgungor]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 20:01:54 GMT</pubDate>
            <atom:updated>2023-08-23T20:07:48.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pkx9ubjtV8YkXH9re0L1nw.png" /><figcaption>A hardworking raccoon generated by Dall-E prompted by Me</figcaption></figure><p>Every individual’s path is unique, shaped by a multitude of experiences and choices. Yet, there exist certain principles and practices that can guide us, lighting our way as we navigate the unpredictable terrain of personal and professional growth. These are the 12 cornerstone recommendations I’ve woven into my professional and everyday life.</p><h3>1. Immersive Learning Experiences</h3><p>Attending hackathons, datathons, and game jams feels like packing a year’s worth of experience into a single weekend. And I don’t just mean the rush of intense coding, collaboration, looming deadlines, or the allure of cash prizes. Yes, those are thrilling parts of the deal, but really, they’re just cherries on top.</p><p>The best part of these social events lies in the rich tapestry of connections and insights they offer. Interacting with incredibly talented individuals from diverse backgrounds and learning from their approaches is a masterclass in itself. Observing their work ethic, gauging their ambitions, and understanding how they navigate challenges provide invaluable lessons.</p><p>And if you’re diving in with your own squad, it’s the perfect chance to assess how well you gel together. It’s like getting a real-time report card on your team’s dynamics. I will not forget in one such event where I met with a friend’s friend. We failed poorly in the hackathon but that connection later played a huge role in winning the <a href="https://www.youtube.com/watch?v=UaCITyHXu8I">‘Best Engineering Project Award’ at Koc University in 2019</a> and I got myself a bestfriend as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*mRMls1iu9Ak31iq3Iimj5g.png" /><figcaption>From the Hackathon that we failed poorly. (OzuHackathon 2018)</figcaption></figure><p>But there’s more. Paying attention to what gets others excited can give you a read on the latest trends and show you where your skills fit in the grand scheme of things. However, remember, it’s not just about the code or winning the prize; it’s a journey of personal growth, networking, and discovering yourself. And the best part? You don’t have to force any of it. Whether you’re lost in fixing a bug or brainstorming a solution, it all just happens organically. :)</p><h3>2. The Power of Kanban</h3><p>It’s quite surprising how many folks in the tech world aren’t leveraging the power of Kanban. I have to admit, I was one of them, even during my MSc days in the University of Sussex. I remember an entire weekend game jam where I learned how to use Kanban from a random top-tier game designer who was working for a small studio now AAA company!</p><p>So, what’s Kanban? Imagine a board that visually manages your workflow, broken down into sections like ‘To Do’, ‘Doing’, and ‘Done’. Personally, I spice mine up a bit, adding sections like ‘Blocked’, ‘Future Works’, and ‘Keep an Eye On’. The beauty of this system is how it emphasizes setting small, achievable goals, making tasks feel more manageable and progress more visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*I_t8R0B0D-4SEa7d.jpeg" /><figcaption>Image: ribkhan/Adobe Stock</figcaption></figure><p>While I may not use all the project management tools available today, I deeply invest in the ones I’ve integrated into my workflow, with <a href="https://trello.com/">Trello</a> (a Kanban Style Board) standing tall beside stalwarts like Version Control.</p><h3>3. Seeking Constructive Feedback</h3><p>Actively seeking feedback from peers I respect and deem more experienced than myself has been transformative in my growth journey. Their perspectives, gleaned from interviews or even casual conversations, have often provided clarity and helped hone my skills.</p><h3>4. Learning How to Learn</h3><p>Ever heard of the Pomodoro Technique? I discovered it with many other gems through a Coursera course titled “<a href="https://www.coursera.org/learn/learning-how-to-learn">Learning How to Learn: Powerful mental tools to help you master tough subjects</a>”. I wish I had come across these strategies earlier, especially during those grueling multivariable calculus exams in my mechanical engineering undergrad days! I had to chance to learn this from an ex- DeepMind <a href="https://www.linkedin.com/in/aleksagordic?miniProfileUrn=urn%3Ali%3Afs_miniProfile%3AACoAACYdwKsB9_xmm5toYADSzYyGuIusSRinIsQ">Aleksa Gordić</a> and helped me a lot. It’s enlightening to realize that there are far more efficient ways to assimilate knowledge and master tough subjects.<br>I use this basic <a href="https://chrome.google.com/webstore/detail/marinara-pomodoro%C2%AE-assist/lojgmehidjdhhbmpjfamhpkpodfcodef">pomodoro timer chrome extension</a>.</p><h3>5. Project-Based Learning</h3><p>I always preface my advice with a reminder: what works for me might not necessarily work for everyone. It’s not a one-size-fits-all approach. Depending on your profession or hobbies, you might not always have the luxury or relevance of project-based learning. But I’ve been fortunate; my interests align with current demands, making my projects not only enjoyable to create but also relevant and needed.</p><p>I embarked on a journey to create an SMS Chatbot that caters to areas with limited or no internet connectivity. Users can shoot questions via SMS and and get immediate responses, a game-changer in areas where the internet is more of a luxury. Curious? Dive into it at <a href="https://smsbotu.com/">SMSBOTU</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*grVsR2u59Zq85JMOjbK30Q.png" /><figcaption><a href="https://smsbotu.com/">smsbotu.com</a></figcaption></figure><h3>7. Embrace Iterations</h3><p>In the world of engineering and tech, agility is a virtue. I’ve learned that sometimes the bravest thing you can do is to press ‘delete’ on your hard work and start afresh. This isn’t about being indecisive, but recognizing that multiple iterations — when done meaningfully — can lead to a more refined and effective end product.</p><p>However, there’s a cautionary note here: the pursuit of perfection can be endless. It’s essential to strike a balance. Like the exploration-exploitation dilemma, while it’s pivotal not to remain fixated on a singular solution, it’s equally important to recognize when to pause, consolidate, and optimize what you have. I highly recommend <a href="https://www.amazon.com/Algorithms-Live-Computer-Science-Decisions/dp/1627790365">“Algorithms to Live By: The Computer Science of Human Decisions”</a>. The first section is the exploration-exploitation algorithm and It’s not just a book for tech enthusiasts but a guide that finds relevance in our daily decisions.</p><p>In essence, it’s crucial to set clear expectations for each iteration. Know what you aim to achieve, be prepared to adapt, and always, always be ready to learn and grow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/0*sQTxJauzU9iR4VDf.jpg" /><figcaption><a href="https://www.amazon.co.uk/Algorithms-Live-Computer-Science-Decisions-ebook/dp/B015DLA0LE/ref=sr_1_1?adgrpid=58614581972&amp;hvadid=606223071998&amp;hvdev=c&amp;hvlocint=9044962&amp;hvlocphy=1012782&amp;hvnetw=g&amp;hvqmt=e&amp;hvrand=398547437895747500&amp;hvtargid=kwd-300531550968&amp;hydadcr=15241_2305087&amp;keywords=algorithms+to+live+by&amp;qid=1692650751&amp;sr=8-1">Algorithms to Live By Cover</a></figcaption></figure><h3>8. Document Your Journey</h3><p>Maintaining a Devlog is more than just record-keeping. It’s a reflection of your growth, challenges, and achievements. I keep a simple Devlog.md file and just stack each day&#39;s notes on top of the previous ones, with a catchy title and date to keep things organized.</p><pre># A new week, a new hope (10/07/2023)<br>- Added a new service for WeatherApi<br><br>## TODO<br>~~- Finish polishing the API endpoint~~</pre><p>I also add a “TODO” section at the end. So, when I come back, I know what’s next, and there’s a certain satisfaction in striking things off once they’re done!</p><h3>9. Stay Motivated</h3><p>We all need that kick to keep pushing forward. For me, taking a look at my growing portfolio and the new skills I’ve picked up does the trick. But hey, it’s crucial to remember that ‘perfect’ is always out of reach — there’s always something new to learn, a skill to refine, or an idea to explore. So while it’s great to take pride in your growth, always be ready for the next challenge.</p><p>On that note, feel free to check out my journey so far: <a href="https://hsgngr.github.io/hosgungor/">My Portfolio</a>.</p><h3>10. Stay Curious but Be Discerning</h3><p>Being curious is great, but what you feed that curiosity matters. Not every flashy headline or trending topic deserves your attention. Stick to reputable newsletters and follow genuine accounts on platforms like Twitter. Sure, sometimes you might stumble upon content like “30 CHATGPT Facts You’ve Never Heard!” and wonder if it’s worth your time mostly it is not. But hey here’s a tip: always dig a little deeper before diving in. Don’t just follow the hype; make sure it’s worth your curiosity.</p><h3>11. Build Good Habits</h3><p>It’s all about the small steps. You can’t transform your life overnight, but you can definitely take steps every day to make a difference. I’m always on the lookout for good habits to adopt. With time and consistency, even the tiniest changes can snowball into big results. Think of it as the compound interest of personal development.</p><p>But let’s be real for a sec: I can’t stand those “I wake up at 5am, run a marathon, work for 26 hours, and still have time to socialize” stories. We all have those zero-productivity days. What really counts is showing up consistently. Whether it’s jotting down in your devlog or updating your Y Combinator Startup School status every week — just keep at it. That’s the real game-changer.</p><h3>12. Enjoy the Journey</h3><p>Trust the process and find joy in it. If you’re not vibing with the journey, the end goal might leave you feeling hollow.</p><p>And let’s be honest, not every task is going to be fun. Some aspects might feel like they’re sucking the life out of you. But amidst all that, there should be moments or aspects you genuinely enjoy — whether that’s in your main gig or a side hustle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bDxuxQ7C7krsFhUBs6tYw.png" /><figcaption><a href="https://bookpalace13.com/product/ikigai-the-japanese-secret-to-a-long-and-happy-life-hardcover/">Ikigai: The Japanese secret to a long and happy life (hardcover)</a> back side</figcaption></figure><p>You’ve probably heard of Ikigai — that sweet spot of purpose you feel when you’re deeply engaged in something. It’s not just about those big “aha” moments. Sometimes, I find my Ikigai groove when I’m dancing, coding, or even doing something as mundane as washing dishes.</p><p>Embrace those moments. Cherish them. And remember, it’s not about the destination but the journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94257694d4de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get started with Hyper-parameter Optimization]]></title>
            <link>https://hosgungor.medium.com/how-to-get-started-with-hyper-parameter-optimization-2738004fbf84?source=rss-e31e18aedeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2738004fbf84</guid>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <dc:creator><![CDATA[Ege Hosgungor]]></dc:creator>
            <pubDate>Fri, 31 Dec 2021 20:52:15 GMT</pubDate>
            <atom:updated>2021-12-31T20:52:15.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u2n1tOaFcPptzIkG.jpg" /><figcaption>Fasten your seat belts cause traveling through <strong>hyperspace</strong> ain’t like dusting crops 😎 (Got the Han Solo reference 😏 ? No ? okay…)</figcaption></figure><p>Any end-to-end machine learning project can be divided into several stages:</p><ol><li>Get the Data</li><li>Exploratory Data Analysis and Visualization</li><li>Preprocessing and Cleaning the Data</li><li>Select and train a model</li><li><strong>Hyper-parameter Optimization (HPO)</strong></li><li>Present your solution</li><li>Launch, monitor, and maintain your system.</li></ol><p>In this post, I will walk you through the following hyper-parameter optimization approaches in details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3xEiMqLQ4kmk2xFCrliUQ.png" /></figure><h3>Introduction</h3><p>Let’s assume you understood your data well, preprocessed &amp; made it ready for training. At this stage in a machine learning project you have some shortlist of promising models (Neural Network, Random-Forest, SVM, XgBoost) and you would like to optimize their hyper-parameters in order to see which model would be the best for your task. But first, <strong>what is hyper-parameters ?</strong></p><p>A hyper-parameter is a parameter whose value is used to control the traning process by contrast with model parameters which are learned during the process. Another words the difference between hyper-parameter optimization of a model and training a model is as follows:</p><p><strong>Model parameters</strong> are learned during model training. For example weights in a neural network changes in a training with every iteration.</p><p><strong>Hyper-parameters</strong> are independent variables from the training. These parameters are specific to the algorithm that has been chosen and users can arbitrarily set these parameters. (eg. learning rate of a neural network, number of estimators in a Random Forest).</p><p>Hyper-parameter optimization happens on top of model training and this optimization is needed in order to get the best result out of a model. In the next chapter we will see different approaches to optimize these parameters.</p><h3>Hyper-parameter Optimization Approaches</h3><p>In this chapter I explained most of the methods in detail from simplest to the edge of technology ones, how they work and where to use them. Since there are many practical posts about how to code these approaches in python, I felt like it is better to give a high-level overview of HPO. I also recommend watching Andrew Ng’s amazing content about <a href="https://www.youtube.com/watch?v=AXDByU3D1hA">Tuning Process</a>.</p><h3>Manual Search</h3><p>One option for optimizing your model’s hyper-parameters would be <strong>manual search. </strong>Trying different values till you find a great combination of them. This is mostly likely to be failed and will be counted as a self-torture if you try to do it with multiple parameters. Why ?</p><p>Because it is not a linear process to understand which value is better for a certain parameter so you cannot iterate it easily. If you have multiple parameters than it’s even much more complex space that you need to scan. Without a decent strategy manual search is literally looking for a needle in a haystack.Data Scientists like automation. The whole purpose of teaching models how to behave in a certain ways is to get rid of element of repetitive work.</p><h3>Parallel Search</h3><p>The simplest automation that you can do is a parallel search. The idea is training number of different models on parallel and comparing their performance with each other instead of guessing what should try next. This is called <strong>grid search</strong>. When you find a range of values that works for your model, you can zoom in to that range and try different values in a smaller space. This can be an iterative process where you tune your parameters till they don’t affect the performance anymore. This only requires the time for one training run, but requires the use of more computational resources to train many models in parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*bs6AkP6yAbz2dszLkZT2_w.png" /><figcaption><a href="https://arxiv.org/pdf/1711.09846.pdf">Parallel Search</a></figcaption></figure><p>A better version of grid search is called<strong> random search </strong>where you tweak the values a little bit each time randomly so you don’t try the exactly same values twice. This works better than grid search. On the picture below the green area with the peak shows the best combination of these two features. As can be seen random search’s best trial is much closer to the peak than the best trial of grid search. <a href="https://www.youtube.com/watch?v=cSoK_6Rkbfg">This video of Andrew Ng</a> might be helpful to understand better how to choose these random values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*JsZXzA9KNhnbGalfpsvC3g.png" /><figcaption>With Grid Search, nine trials only test three distinct places. With Random Search, all nine trails explore distinct values.</figcaption></figure><p>Why we are not satisfied with this technique ? Let me give you an example:</p><p>If we want to try 3 different values for <em>parameter_1 </em>then we can try all of them and compare their results. If we want to try 3 different values for <em>parameter_1</em> and 3 different<em> </em>values for<em> parameter_2</em> then we will have 3x3 = 9 different trials. I think you got the idea, the number of trial counts will exponentially increase with number of parameters and values.Trying all of them one by one is not efficient. (Although parallel search is the most common hpo approach because of its simplicity.)</p><h3>Sequential Search</h3><p>Till now we didn’t use any mathematical approach, we were just up all night to get lucky (pun intended), but there are better ways. As we just mentioned the parallel search was inefficient because you need to try all of the values, instead we should be more clever and train the least number of models while we look for the best hyper-parameter combination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5DH525ENc5-l0QuuxDFRQ.png" /><figcaption><a href="https://arxiv.org/pdf/1711.09846.pdf">Sequential Search</a>. In every iteration hyper-parameters are getting updated by comparing the results of the training.</figcaption></figure><p>Sequential search is a way to train a model at each step, using a specific set of parameters. The algorithm uses the information from all the previous steps to define the set of parameters that will be tested in the next step/iteration. By doing this, the algorithm focuses the search on the most promising parameters.</p><p><strong>Bayesian optimization</strong> is a global optimization method for any <strong>black-box</strong> system.(a system for which we can only observe the inputs and outputs, but not the internal workings itself) In the context of hyper-parameter optimization of machine learning models, Bayesian optimization is of particular relevance as the computational costs for evaluating model variations is high and often <strong>objective function</strong> is complex, does not have accessible derivatives, or when the problem at hand is non-convex. (objective function is the function that you want to minimize or maximize in your problem. e.g minimizing of cost function, maximizing reward function)</p><p>In contrast of parallel search methods, Bayesian Optimization provides a principled technique based on <a href="https://machinelearningmastery.com/bayes-theorem-for-machine-learning/">Bayes Theorem</a> to direct a search of a global optimization problem that is efficient and effective. It works by building a probabilistic model of the objective function, called the <strong>surrogate function</strong>, that is then searched efficiently with an acquisition function before candidate samples are chosen for evaluation on the real objective function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*A1uDgkT3DicFeIKZ_Wt6kQ.png" /><figcaption>Surrogate function: It is an approximation of the objective function and can be used to estimate the cost of different candidate samples that we may want to evaluate.</figcaption></figure><p>The surrogate is much easier to optimize than the objective function and Bayesian methods work by finding the next set of hyper-parameters to evaluate on the actual objective function by selecting hyper-parameters that perform best on the surrogate function. The sequential search gives you the advantage of</p><ul><li>Reduced running time of hyper-parameter optimization</li><li>Better scores on the testing set</li></ul><p><strong>Gradient Descent: </strong>For specific algorithms (neural networks, SVMs and logistic regression etc.) it is possible to compute the gradient with respect to hyper-parameters and then optimize the hyper-parameters using<strong> gradient descent.</strong> <a href="https://link.springer.com/article/10.1007/s10479-019-03286-z">The experimental results</a> show that the gradient-based algorithms are also significantly more effective than parallel search-based algorithms when the number of hyper-parameters is large. Being applicable on neural networks make gradient descent algorithms a popular choice in deep learning.</p><h3>Evolutionary Search</h3><p>The evolutionary search consist of genetics algorithms make use of basic concepts from <em>evolution by natural selection. </em>Genetic algorithms have wide use cases just like Bayesian Theorem however they are quite overlooked in the context of hyper-parameter optimization.</p><p>I always get fascinated by <a href="https://rednuht.org/genetic_cars_2/">2D Box Car simulations</a> where you can understand how genetic algorithms works in a much more practical sense. The simulation have ground rules like every car will have 2 wheels, they must be connected by a chassis etc. Then there are some parameters such as size of the wheels, shape of the chassis. These are the parameters that we would like to optimize for the best car. The simulation starts with random population and by the end of each run best candidates transfer their genes (parameters) to the next generation. Random parameter mutations are introduced in the population, and cars with a higher fitness score outlive others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*KfbNP2-CxlOzf_MYdE_DPg.png" /><figcaption><a href="https://rednuht.org/genetic_cars_2/">Genetic evolution of a wheeled vehicle with Box2d</a></figcaption></figure><p>We can use this natural selection concept for hyper-parameter optimization of our machine learning models. Lets say we have a population of N Machine Learning models with some predefined parameters. We can then train these models and decide to keep half of the models with the best score. From these <em>N/2 </em>models we can generate new population of<em> N</em> ML models with similar hyper-parameters. I’m saying similar not exact because than whats the point of generating a new population. One flaw that genetic algorithms has that as mutations are purely random the consequences are also random just as evolution. I would again recommend reading <a href="https://towardsdatascience.com/genetic-algorithm-to-optimize-machine-learning-hyperparameters-72bd6e2596fc">this amazing blog post</a> for more.</p><h3>Population Based Search</h3><p><strong>The Population Based Training</strong> <strong>(PBT)</strong> is an ML hyper-parameter optimization method developed by <a href="https://deepmind.com/">DeepMind</a>. This method combines both parallel and sequential search methods I will tell you how:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*CLbdNnONQL_3qO8KvJ0uCA.png" /><figcaption><a href="https://arxiv.org/pdf/1711.09846.pdf">Population Based Training</a></figcaption></figure><p>The diagram above shows how PBT works. Training starts like parallel search, randomly sampling hyper-parameters and weight initializations. However, each training run asynchronously evaluates its performance periodically. If a model in the population is under-performing, it will exploit the rest of the population by replacing itself with a better performing model, and it will explore new hyper-parameters by modifying the better model’s hyper-parameters, before training is continued. This process allows hyper-parameters to be optimized online, and the computational resources to be focused on the hyper-parameter and weight space that has most chance of producing good results. The result is a hyper-parameter tuning method that while very simple, results in faster learning, lower computational resources, and often better solutions.</p><p>It is most analogous to evolutionary search but rather than evolving parameters, PBT train models partially with standard optimization methods such as gradient descent. also the main purpose of PBT is to provide a way to optimize both model parameters θ and the hyper-parameters h jointly on the actual metric Q that we care about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1J7FFQLVdbEB_6Y9XQl5Q.png" /><figcaption>A Reward/Step Graph. PBT on a reinforcement learning task. 6 different samples running on parallel.</figcaption></figure><p>Here is a graph from an actual reinforcement learning task running with Population Based Training. Although each model is getting different rewards, overall all of them are getting improved. This is because periodically these models are sharing their parameters both model and hyper-parameters.</p><p>This combined training of a ML model can be used for any task but its especially popular within the reinforcement learning (RL) community. RL algorithms are known to be brittle to the choice of hyper-parameters therefore starting with an unlucky initialization may have an absolute effect on the end product since bad strategy means bad data generation. PBT increases the chance of success by having multiple simulations and strategies.</p><p>In 2020 Anyscale (a company known for their Python library <a href="https://www.ray.io/">Ray</a>) published a new method similar to PBT called <strong>Population Based Bandits (PB2). </strong>Similar PBT, <a href="https://docs.ray.io/en/master/tune/api_docs/schedulers.html#tune-scheduler-pb2">PB2</a> trains and optimizes a series of networks at the same time, allowing the optimal set-up to be quickly found. However, unlike PBT, <a href="https://docs.ray.io/en/master/tune/api_docs/schedulers.html#tune-scheduler-pb2">PB2</a> uses a <em>probabilistic model</em> to guide the search in an efficient way, making it possible to discover high performing hyper-parameter configurations with far fewer agents than typically required by prior work. <a href="https://www.anyscale.com/blog/population-based-bandits">For more details about PB2 checkout Anyscale’s own document.</a></p><h3>Bandit Based Search</h3><p>PB2 was a bandit based search as well as population based. But what is “bandit” means in the context of probability theory ? The <strong>multi-armed bandit problem</strong> (sometimes called the <strong><em>N</em>-armed bandit problem</strong>) is a problem in which a fixed limited set of resources must be allocated between competing (alternative) choices in a way that maximizes their expected gain, when each choice’s properties are only partially known at the time of allocation, and may become better understood as time passes or by allocating resources to the choice.</p><p><strong>Long story short</strong> we can think hyper-parameter optimization task as an infinite-armed bandit problem where a predefined resource like iterations, data samples, or features is allocated to randomly sampled configurations. HyperBand -a bandit based algorithm- aims to optimize with a method called successive halving. Hyperband implements hyper-parameter optimization by sampling candidates at random and “trying” them first, running them for a specific budget. The approach is iterative, promising candidates are run for a longer time, increasing the fidelity for their performance. While this is a very efficient racing approach, random sampling makes no use of the knowledge gained about the candidates during optimization. Therefore I would still prefer PBT over HyperBand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fc5t1Z4G_PIuPwsiB194FQ.png" /><figcaption>Mean Reward Distribution on Steps for Different Learning Rates (Example for Hyper-parameter Optimization on a Reinforcement Learning Task)</figcaption></figure><h3>Summary of Key Findings</h3><p>We talked about what is the hyper-parameter optimization and most common HPO approaches from simplest to the newest approach. The key is to know all of these approaches and use the most suitable one for you. As model selection doesn’t have one answer, HPO is also depends on the task and the resources itself. If parallel search enough for you and you can try combinations of parameter values as much as you want then go with it. We also see the advantages and disadvantages of all the approaches. This is important since you will choose your approach by considering these facts.</p><p>I personally like PBT since I specialized on reinforcement learning and most of my time I use Population Based Training for the simulations however it does take time and also it can only be used with same neural network architectures. Therefore for trying new architectures I try basically parallel search methods.</p><p>I quite enjoyed my time while writing this post and reading papers about hyper-parameter optimization. Thanks for your patience and being all along with me throughout the post. Also any feedback is welcome on comments.You can also <a href="https://www.buymeacoffee.com/hosgungor">buy me a coffee!</a>😎</p><h3>References</h3><p><strong>Sequential Search Related</strong></p><ul><li><a href="https://link.springer.com/article/10.1007/s10479-019-03286-z">Comprehensive analysis of gradient-based hyper-parameter optimization algorithms</a> — Comparison of gradient-based algorithms vs random search.</li><li><a href="https://towardsdatascience.com/a-conceptual-explanation-of-bayesian-model-based-hyperparameter-optimization-for-machine-learning-b8172278050f">A blog post for detail explanation of Bayesian Optimization</a></li><li><a href="https://machinelearningmastery.com/what-is-bayesian-optimization/">A Hands-On Bayesian Optimization implementation in Python from Scratch</a></li><li><a href="https://towardsdatascience.com/a-conceptual-explanation-of-bayesian-model-based-hyperparameter-optimization-for-machine-learning-b8172278050f">Conceptual Explanation of Bayesian Optimization</a></li><li>I would also recommend you to read this <a href="https://medium.com/riskified-technology/from-sequential-to-parallel-a-story-about-parallel-bayesian-hyperparameter-optimization-f124ed29f556">case study article</a> of a Credit Card Fraud company which uses <strong>Bayesian Optimization</strong> on their models.</li></ul><p><strong>Population Based Related</strong></p><ul><li><a href="https://arxiv.org/pdf/1711.09846.pdf">Population Based Training (PBT)</a></li><li><a href="https://arxiv.org/abs/2002.02518">Population Based Bandits (PB2)</a></li></ul><p><strong>Bandit Based Related</strong></p><ul><li><a href="https://arxiv.org/abs/1603.06560">Hyperband: A Novel Bandit-Based Approach to Hyper-parameter Optimization</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2738004fbf84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to maintain your Linux System “Clean”]]></title>
            <link>https://hosgungor.medium.com/how-to-maintain-your-linux-system-clean-654b4193ccc1?source=rss-e31e18aedeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/654b4193ccc1</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[cleaning]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Ege Hosgungor]]></dc:creator>
            <pubDate>Mon, 23 Aug 2021 13:18:16 GMT</pubDate>
            <atom:updated>2021-08-23T13:45:21.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8GC9qLfkJFP_80Hb-7ETg.jpeg" /><figcaption>Photo by Me, Aladağlar Turkey</figcaption></figure><p>Hi, I’m Ege Hosgungor a Data Scientist &amp; Machine Learning Engineer at Dcipher Analytics. I had to learn how to use Linux in hard way (while doing my job) that’s why I’m trying to make this transition easier for others by creating these essential tutorials for beginners.</p><h3>Why Linux?</h3><p>Whether you are an ML Engineer, Data Scientist or a Researcher soon or later you will have to use an UNIX System for your daily job. As a born and raised Windows user I was avoiding to use any Linux distribution or MacOS when it is possible. <strong>But shocking news,</strong> <strong>you cannot escape. </strong>If you want to be agile and move fast at your job you have to use a distribution which is developer friendly rather than an average-user friendly system.</p><p>“It is your job to make your job easier.”</p><h3>Up-to-Date</h3><p>You will want to keep your system up-to-date not just because of the security reasons but also bug fixes, getting the most updated versions of software and new features of Linux. Also from a ML Engineer perspective, having an outdated version of OS can cause many problems which might be hard to detect when you want to try a new technology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*ZfYP8CLD6cGWXgbCTyeDcg.png" /></figure><h3>Literally Cleaning</h3><p>Having this much freedom and flexibility on your OS comes with a trade-off: It is much easier to break it. It is important to cleaning out old packages as you install them because they can bloat up your system. Unlike Windows, which comes with built-in defrag and disk clean-up tools, Linux doesn’t make it <em>immediately</em> obvious how you go about trying to free up space. Luckily it is not that hard to get over with it. The only thing that you need to do is: Once in a while don’t forget to flush and clean caches.</p><pre>$ sudo apt-get clean</pre><p>It is also recommended to remove old kernels. You can also do that from command line:</p><pre>$ sudo apt-get autoremove --purge</pre><pre><strong>0 to upgrade, 0 to newly install, 50 to remove and 53 not to upgrade.<br>After this operation, 2,504 MB disk space will be freed.</strong></pre><p>These commands might save the day but the real cleansing comes with using a graphical disk usage analyzer. If you are familiar with WinDirStat in Windows there is a similar lightweight software that I use for Linux called QDirStat. It is pretty easy to use and highly effective.</p><pre>$ sudo apt-get install -y qdirstat</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*9L9rXESqeJJuM462WXf6FA.png" /></figure><p>As I dual-boot my local machine with Windows and Ubuntu I always keep things sorted and clean. Here I downloaded a zip file for an example Reinforcement Learning Task and after 1 hour my job is finished but look how huge is the rubbish data. You can use terminal to download the qdirstat and then remove the unnecessary files.</p><p>Take a detailed look into your anaconda folder especially. If you use your instance more than 1 month surely there will be outdated libraries or even environments which you don’t need anymore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*h4XKXhmNHKriCTtE6yVSuw.png" /></figure><p>To also remove conda environments from past projects use command line:</p><pre>$ conda env remove --name oldenvironment</pre><h3>Terminal</h3><p>Lastly, Terminal is the best way to use Linux since it minimizes the user error. This can come odd to a Windows User since it’s command line is a disaster however you will feel very secure and fast if you get comfortable with the terminal. And that doesn’t mean you need to know thousands of different commands, on daily average I’m using 20–30 of them and others are all depends on the application that I’m doing. For example if I use Google Cloud Platform (GCP) I don’t memorize the commands, I note them to somewhere and I change the structure a little bit every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*4hwJExTmizUrVpYVlXz6rw.png" /><figcaption>One of the commands that I use in my GCP instance</figcaption></figure><h3>Conclusion</h3><p>These are the small tips I do with every Linux install as a ML Engineer from local machine dual boots to Rasperry Pi Setups or GCP instances just to make sure its running in tip-top shape. Doing these routines will keep your system light and help you to avoid crashes in unwanted times.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=654b4193ccc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle Imbalance Data and Small Training Sets in ML]]></title>
            <link>https://medium.com/data-science/how-to-handle-imbalance-data-and-small-training-sets-in-ml-989f8053531d?source=rss-e31e18aedeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/989f8053531d</guid>
            <category><![CDATA[resampling]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ege Hosgungor]]></dc:creator>
            <pubDate>Wed, 28 Oct 2020 00:30:48 GMT</pubDate>
            <atom:updated>2025-01-17T16:02:00.519Z</atom:updated>
            <content:encoded><![CDATA[<p>Imbalanced data refers to where the number of observations per class is not equally distributed and often there is a major class that has a much larger percentage of the dataset and minor classes which doesn’t have enough examples.</p><figure><img alt="Image by Author" src="https://cdn-images-1.medium.com/max/403/1*CkItiHtZWN5MBAs0VPlwdw.png" /><figcaption>Graph by Author</figcaption></figure><p>Small Training Sets also suffer from not having enough examples. Both of the problems are very common in real-world applications but luckily there are several ways to overcome this problem. This article will walk through many different techniques and perspectives to combat Imbalance data. In particular, you will learn about:</p><ul><li>Sampling Techniques (Upsampling &amp; Downsampling, SMOTE)</li><li>Weighted Loss</li><li>Data Augmentation Techniques</li><li>Transfer Learning</li></ul><h3>How imbalanced data affects your model?</h3><p>Imbalanced data is a common problem in data science. From image classification to fraud detection or medical diagnosis, data scientists face imbalanced datasets. Having an imbalanced dataset decreases the sensitivity of the model towards minority classes. Lets put this on with simple maths:</p><p>Imagine you have 10000 lung X-Ray images and only 100 of them are diagnosed with Pneumonia which is an infectious disease that inflames the air sacs in one or both lungs and fills them with liquid. If you train a model that predicts every example as healthy you will get 99% accuracy. Wow, how awesome is that? <strong>Wrong</strong>, you just killed many people with your model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*ZxquEZcxNNJRvpH5WeiNMQ.png" /><figcaption>Image by Author</figcaption></figure><p>Usually, we look at accuracy to measure our model’s performance but imbalanced data can mislead us like the example above. This article is focused on how to handle these kinds of situations and I am not going into details of how to measure your model but bear in mind to change the measurement metrics from Accuracy to <strong>Precision, Recall, F1</strong> Score. But even they are not actually that great. I would recommend going for:<strong>AUC Curves,</strong> <strong>Average Precision</strong> while dealing with imbalance data. Here is an amazing github repository which goes into very details of these metrics by talking about a particular imbalance dataset example: <a href="https://fraud-detection-handbook.github.io/fraud-detection-handbook/Chapter_4_PerformanceMetrics/Introduction.html">credit card frauds</a>.</p><p>Let’s say, we have an imbalanced dataset and we do not have access to more data. So we should create our own data. The following chapter will present techniques on a high abstract level and I also added some great references for implementing each of them in Python.</p><h3>Sampling Techniques</h3><p>You can balance your data by resampling them. The followings are two different techniques for resampling:</p><ul><li>Upsampling (increase your minority class)</li><li>Downsample (decrease your majority class)</li><li>SMOTE (Synthetic Minority Over-sampling Technique): Generate synthetic samples for the minority class</li></ul><h4>Upsampling &amp; Downsampling</h4><p>For the first two techniques, we will use the Sklearn Resample function. Let’s import the libraries and define our data as df:</p><pre># Importing the libraries<br>import numpy as np<br>import pandas as pd<br>from sklearn.utils import resample</pre><pre># Importing the dataset<br># Read dataset<br>df= pd.read_csv(&#39;data.csv&#39;)</pre><p>In this example, we have a binary classification problem where the majority is represented as 1 and the minority class is represented as 0. Let’s separate them:</p><pre># Separate majority and minority classes<br>df_majority = df[df.iloc[:,4608]==1]<br>df_minority = df[df.iloc[:,4608]==0]</pre><p>We can downsample the majority class, upsample the minority class or we can do both. You should try them to find which one is the most suitable for you. One other hyperparameter that you can tune is n_samples which is the number of samples that you resample.</p><pre># Separate majority and minority classes<br>df_majority = df[df.iloc[:,4608]==1]<br>df_minority = df[df.iloc[:,4608]==0]<br> <br># Downsample majority class<br>df_majority_downsampled = resample(df_majority, <br>                                 replace=False,    <br>                                 n_samples=1000)</pre><pre>#Upsample minority class<br>df_minority_upsampled = resample(df_minority, <br>                                 replace=True,     <br>                                 n_samples=1000)</pre><pre># Combine minority class with downsampled majority class<br>df_up_down_sampled = pd.concat([df_majority_downsampled, df_minority_upsampled])</pre><p>Lastly display new class counts with:</p><pre>df_downsampled.prediction.value_counts()</pre><h4>Synthetic Minority Oversampling Technique (SMOTE):</h4><p>Unlike traditional <strong>upsampling</strong>, which duplicates minority class samples, <a href="https://imbalanced-learn.org/stable/references/generated/imblearn.over_sampling.SMOTE.html">SMOTE</a> <strong>generates synthetic data points</strong> by interpolating between existing instances. This technique helps prevent overfitting and improves the generalization ability of machine learning models. You can use SMOTE like the others in Python:</p><pre>!pip install imbalanced-learn # If you already not install.<br>from imblearn.over_sampling import SMOTE<br><br># Define features (X) and target variable (y)<br>X = df.drop(columns=[&#39;target&#39;])  # Replace &#39;target&#39; with your actual column name<br>y = df[&#39;target&#39;]<br><br># Apply SMOTE<br>smote = SMOTE(sampling_strategy=&#39;auto&#39;, random_state=42)<br>X_resampled, y_resampled = smote.fit_resample(X, y)<br><br># Convert back to DataFrame<br>df_resampled = pd.concat([pd.DataFrame(X_resampled, columns=X.columns), <br>                          pd.Series(y_resampled, name=&#39;target&#39;)], axis=1)</pre><h4>When would you use which technique ?</h4><p>You can always combine SMOTE with Upsampling &amp; Downsampling to create a<strong> more balanced and representative</strong> dataset while reducing the risks of overfitting.</p><p><strong>Note:</strong> Beware of the data leakage that these sampling techniques can cause. Applying resampling <strong>before</strong> splitting the dataset leads to information from the test set influencing the training set. So always and always split the dataset to train/test before applying these methods.</p><pre>#First, split the original dataset<br>X_train, X_test, y_train, y_test = train_test_split(df.drop(columns=[&#39;target&#39;]), <br>                                                    df[&#39;target&#39;], <br>                                                    test_size=0.2, <br>                                                    stratify=df[&#39;target&#39;])<br># Then do all the sampling:<br>...</pre><p>Congratulations, you brought balance to the power. 🎉</p><p>But sometimes resampling doesn’t enough on its own. The article continues with more advanced techniques.</p><p><strong>Edit:An interview question which I got asked lately: </strong><em>How would you make sure that your upsampled &amp; downsampled data comes from a good distribution/ how would you measure the performance of these methods ?</em></p><p>One easy way to measure the performance of these methods are getting the test results for your new model which is trained with this additional data. Most of the time while upsampling you might first see an increase on the performance and then plateau or even decrease afterwards. I would pick the least number of upsampled data with the top performance.</p><h3>Weighted Loss</h3><p>One other way to avoid having class imbalance is to weight the losses differently. To choose the weights, you first need to calculate the class frequencies.</p><pre><em># Count up the number of instances of each class (drop non-class columns from the counts)</em><br>class_counts = df_classes.sum()</pre><pre>#print the class frequencies<strong><br>for</strong> column <strong>in</strong> class_counts.keys():<br>    print(f&quot;The class <strong>{</strong>column<strong>}</strong> has <strong>{</strong>df_classes[column].sum()<strong>}</strong> samples&quot;)</pre><p>Changing the weights in the loss function allows data scientists to balance the contribution of each class. One way of doing this is by multiplying each example from each class by a class-specific weight factor so that the overall contribution of each class is the same.</p><p>Thanks to the Sklearn, there is a built-in parameter called class_weight in most of the ML algorithms which helps you to balance the contribution of each class. For example, in the Sklearn’s <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">RandomForestClassifier</a> you have options as balanced, balanced_subsample or you can give weights for each class manually as a dictionary.</p><pre>#Fitting RandomForestClassifier<br>from sklearn.ensemble import RandomForestClassifier</pre><pre>model = RandomForestClassifier(n_estimators=1000, class_weight={0:0.10, 1:0.90})</pre><p>Amazing🥳, now you learned a very common technique that you can apply almost every kind of data with every ML algorithms. Let’s dive in even more advanced techniques.</p><h3>Data Augmentation</h3><p>From now onwards, the techniques that I’m going to mention are suitable mostly for Computer Vision and images. There are ways to generate data when you are working with images.</p><p>Data Augmentation is known as a very powerful technique used to artificially create variations in existing images to expand an existing image data set. This creates new and different images from the existing image data set that represents a comprehensive set of possible images. Here are several ways that you can do to increase your dataset.</p><ul><li>Flipping</li><li>Zoom</li><li>Rotating</li><li>Shearing</li><li>Cropping</li><li>And lastly generating new images with Generative Adversarial Networks.</li></ul><p>Note: Sometimes using these techniques can harm your model more than helping it. Let’s assume the same Lung X-Ray dataset case where we have many different X-rays. If you flip the images you will have a heart in the right which can be seen as a cist. Again you killed people =( So be careful about using these augmentation techniques.</p><p><a href="https://towardsdatascience.com/data-augmentation-techniques-in-python-f216ef5eed69">You can learn more about this here</a></p><h3>Transfer Learning</h3><p>If you don’t have enough data to generalize your model you can use pre-trained models and tune them for your own task. This is called Transfer Learning and it is very common in the Computer Vision field. Since the training, huge models take so much time and resources, and people are getting pre-trained models like DenseNet and use them. The approach is as follows:</p><ul><li>Find a model which suits your requirements</li><li>Re-use the model. This may involve using all or parts of the model or the first layers of the neural network. Since the complexity of features increases with the number of layers, the first layers always have more generic features that can be used successfully.</li><li>Fine-tuning: By going deeper, the neural network gets specialized on the task so you may want to tune the last couple of layers for your own task which is called Fine-tuning.</li></ul><p><a href="https://machinelearningmastery.com/transfer-learning-for-deep-learning/">You can learn more from here</a></p><h3>Summary</h3><p>We learned 4 different techniques that you can apply to your imbalanced data / small training set. Now you know how to increase your model’s performance with:</p><ul><li>Sampling Techniques</li><li>Changing the Class Weights of Loss Functions</li><li>Data Augmentation Techniques (For CV)</li><li>Transfer Learning</li></ul><p>The last two of them are more specific to Computer Vision. I hope this article helps you to understand how to overcome imbalance data problems with different techniques. Congratulations on finishing this article and thanks for reading all along.</p><h3>References:</h3><ul><li><a href="https://machinelearningmastery.com/resample-interpolate-time-series-data-python/">https://machinelearningmastery.com/resample-interpolate-time-series-data-python/</a></li><li><a href="https://towardsdatascience.com/data-augmentation-techniques-in-python-f216ef5eed69">https://towardsdatascience.com/data-augmentation-techniques-in-python-f216ef5eed69</a></li><li><a href="https://machinelearningmastery.com/transfer-learning-for-deep-learning/">https://machinelearningmastery.com/transfer-learning-for-deep-learning/</a></li><li><a href="https://machinelearningmastery.com/tactics-to-combat-imbalanced-classes-in-your-machine-learning-dataset/">https://machinelearningmastery.com/tactics-to-combat-imbalanced-classes-in-your-machine-learning-dataset/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=989f8053531d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-handle-imbalance-data-and-small-training-sets-in-ml-989f8053531d">How to Handle Imbalance Data and Small Training Sets in ML</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Pandemic Simulation with Unity III: Adding Artificial Intelligence]]></title>
            <link>https://hosgungor.medium.com/create-a-pandemic-simulation-with-unity-iii-adding-artificial-intelligence-3c1377c1fb16?source=rss-e31e18aedeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c1377c1fb16</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[ml-agent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[socialdistancing]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Ege Hosgungor]]></dc:creator>
            <pubDate>Mon, 05 Oct 2020 23:06:53 GMT</pubDate>
            <atom:updated>2020-10-05T23:06:53.503Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@hosgungor/create-a-pandemic-simulation-with-unity-8eb37ca816f1">In the last two article</a> we have created an epidemic simulation within Unity and analyze the spread of epidemic disease. In this part we will convert our epidemic simulation to a reinforcement learning environment and train artificially intelligent agents both in single-agent scenario and multi-agent scenario. In the end, agents will learn how to do social distancing. This article series is based on my MSc dissertation at University of Sussex for Advanced Computer Science and it is called “Simulation-Based Reinforcement Learning for Social Distancing”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*r0G5bfwITk2NZmSP6cpZAw.gif" /><figcaption>Multi-agent scenario. Blue cubes are controlled by AI they try to avoid red ones.</figcaption></figure><p>The source of the project is available on github. <a href="https://github.com/Hsgngr/Pandemic_Simulation,">You can download or clone from here</a>.</p><h3>Getting Started</h3><p>Since we have already created our epidemic simulation we can start adding up AI and spice up things even more. We will use Unity ML-Agents Toolkit Release-6 to create our environment and train agents with reinforcement learning techniques. if you didn’t have done the first two tutorials I would strongly recommend you to take a look and then return to this tutorial back.</p><ol><li><a href="https://medium.com/@hosgungor/create-a-pandemic-simulation-with-unity-8eb37ca816f1">Create an Epidemic Simulation in Unity I: Simulating an epidemic spread</a></li><li><a href="https://medium.com/@hosgungor/create-a-pandemic-simulation-with-unity-ii-analyzing-sir-graphs-1a0078933406">Create a Pandemic Simulation with Unity II: Analyzing SIR graphs</a></li></ol><h3>Background: Reinforcement Learning</h3><p>Reinforcement Learning (RL) is an area of Machine Learning where an agent learns the best behavior by interacting with the environment. Creating these complex environments and artificially intelligent agents that solve complex human-relevant tasks has been a life-long challenge for RL researchers. The environment is a crucial component of RL and determines broadly the task that the agent has to solve. Agents and environments cannot be considered separately, and it is only a design choice for the researcher to determine where the environment starts and the agent ends. Most of the time the environment is defined as anything that an agent cannot have direct control over. The agent perceives its environment through sensor observations and acts upon that environment through effectors. For each action selected by the agent, the environment provides a reward, and the agent aims to maximize the total rewards that it gets. In every step, the agent performs an action by following a strategy which is called policy. The agent starts with a random policy, and as the training continues the policy is optimized by a learning algorithm.</p><h3>Unity ML-Agents Toolkit</h3><p>The Unity Machine Learning Agents Toolkit (<a href="https://github.com/Unity-Technologies/ml-agents">ML-Agents</a>) is an open-source project that enables Unity scenes to serve as environments for training intelligent agents. Agents can be trained using reinforcement learning, imitation learning, neuroevolution, or other machine learning methods through a simple-to-use Python API. In this article we utilize standard reinforcement learning techniques to train our agents. In this part, we will create one script called PandemicAgent.cs and update one of the previous script called PandemicArea.cs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*xklLrAmlOgmHOjGnpp2Gsg.png" /><figcaption>PandemicAgent.cs and PandemicArea.cs</figcaption></figure><p>We will create two different scenarios: single-agent and multi-agent. In single-agent scenario, agent will be trained to avoid infected bots and at the same time try to catch rewards as much as possible. In multi-agent scenario there will be many agents in the same environment and they will all try to avoid each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*cLcCGFFfCBe0axnoqKZ_9Q.png" /><figcaption>Single-Agent Scenario</figcaption></figure><p>Lets start with a single-agent scenario since it will be easier to iterate and clean the code, also there is literally a few change between two scenarios.</p><p>ML-Agent Toolkit make it extremely easy to create agents by inheriting abstract class “Agent”. An agent is an entity that can observe its environment, decide on the best course of action using those observations, and execute those actions within its environment. In order to use the mlagents package you need to download Window&gt;Package Manager &gt;ML Agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*5VoLiT7lXjsROCS8RBORBA.png" /></figure><h3>PandemicAgent.cs</h3><p>After adding the needed packages we are ready to use ML-Agents Toolkit .Agents can be created in Unity by inheriting the Agent class. There are some methods that needs to be implemented in order to use Agent class. We will define each method as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*Bv3eSM1xBbWfwZ4j0StEXQ.png" /></figure><p>Create a new script called PandemicAgent.cs and change its monoBehavior type to “Agent”</p><ul><li>Agent.OnEpisodeBegin() — Called at the beginning of an Agent&#39;s episode, including at the beginning of the simulation. This will be called in Pandemic Area script inside of the resetPandemicArea() method.</li><li>Agent.Initialize() — Called when agent is created. Inside of this method, we initialize the needed objects that we will communicate during the training such as area, agent’s rigidbody etc.</li><li>Agent.CollectObservations(VectorSensor sensor) — Called every step that the Agent requests a decision. For our agents there will be 4 observations: local velocity in x and z, and hot encoded health status which can be represent with 2 binary in total 4.</li><li>Agent.OnActionReceived() — Called every time the Agent receives an action to take. Receives the action chosen by the Agent. It is also common to assign a reward in this method. We created another method as MoveAgent() inside of this function.</li><li>Agent.Heuristic() - When the Behavior Type is set to Heuristic Only in the Behavior Parameters of the Agent, the Agent will use the Heuristic() method to generate the actions of the Agent. As such, the Heuristic() method writes to the array of floats provided to the Heuristic method as argument.</li><li>AddReward() — Adding reward mostly comes as a design choice. Important thing to remember for the designer is</li></ul><p><strong>Here is the script: </strong><a href="https://gist.github.com/Hsgngr/e3a798b7c57dcaa86abddfad9bacea65">PandemicAgent.cs</a></p><h3>Designing an Agent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*hdlN5l9u6zQiGsivY1ffzA.png" /></figure><p>In this tutorial we used the same model of dummyBot for Agent with only change in color. Create a new dummyBot remove the dummBot.cs component and add PandemicAgent.cs. After the addition you should see that a script called Behavior Parameters automatically added into your model. We should also add <strong>DecisionRequester.cs</strong> This script will decide which action our agent should take. If you forget to put this script agents are not gonna take any actions.</p><p>Lastly add <strong>Ray Perception Sensor 3D </strong>script<strong>.</strong>This script creates vector observations for our agent to see the area. We used 16 rays per direction but you can optimize it to a lower number of rays.With the help of rays and other observations that we define in Pandemic Agent script,we created our RL agent and it is ready for an epidemic outbreak.</p><h3>PandemicArea.cs</h3><p>Most of the parts are the same with the first two article, but as an extra we added reset function for agents at the start of every episode. The spawning of agents are also similar to dummyBots() but with one difference. We decided to put agents before running the simulation so PandemicArea.cs do not create new agents, instead it finds all agents and store them in a single list where we can control all of them easily.</p><p><strong>Here is the updated script: </strong><a href="https://gist.github.com/Hsgngr/751e42b2117e6950ca3cffd085425f21">PandemicArea.cs</a></p><h3>Training the environment</h3><p>We finished the implementing part in Unity. Lets train our first agent using a terminal.</p><ol><li>Open a command or terminal window.</li><li>Navigate to the folder where you cloned the Pandemic_Simulation repository. Note: If you followed the default <a href="https://github.com/Unity-Technologies/ml-agents/blob/release_6_docs/docs/Installation.md">installation</a>, then you should be able to run mlagents-learn from any directory.</li><li>Run following code block:</li></ol><pre>mlagents-learn config/PPO/trainer_config_MVP.yaml --run-id=firstRun</pre><ul><li>config/ppo/trainer_config.yaml is the path to a default training configuration file that we provide. The config/PPO folder includes training configuration files for all many different configuration for epidemic simulation</li><li>run-id is a unique name for this training session.</li></ul><ol><li>When the message <em>“Start training by pressing the Play button in the Unity Editor”</em> is displayed on the screen, you can press the Play button in Unity to start training in the Editor.</li></ol><p>If mlagents-learn runs correctly and starts training, you should see some similar messages on terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*7FOC4IWrTEfZPOqzdYtUFg.png" /></figure><p>Congrats you just started your first training for epidemic simulation in Unity👏 Now from another terminal you can open and see the results of your simulation with tensorboard.</p><ol><li>Open an another command or terminal window.</li><li>Navigate to the folder where your configuration file is. You should see a new folder called “results” appeared in the config folder.</li><li>Run following code:</li></ol><pre>tensorboard --logdir results</pre><p>Then navigate to localhost:6006 in your browser to view the TensorBoard summary statistics as shown below. For the purposes of this section, the most important statistic is Environment/Cumulative Reward which should increase throughout training and eventually converge to some value. In your local host you should see the following graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_lW871n3tnmP8snaIE2lwQ.png" /></figure><h3>Next Steps</h3><p>Fantastic, you succeed to create your own reinforcement learning environment! From now on, you can try to optimize the hyperparameters of PPO and our deep neural network by changing the values in the configuration file. This was the last article of Series “Create a Pandemic Simulation with Unity”. I learned many things while doing the project both practical and theoretical. I hope I was able to share some of my know-how.and make someone’s life a little bit easier who follows this tutorial series. I know the path is tough but I always remind myself: Success comes with hard work. See you next time 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c1377c1fb16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Pandemic Simulation with Unity II: Analyzing SIR graphs]]></title>
            <link>https://hosgungor.medium.com/create-a-pandemic-simulation-with-unity-ii-analyzing-sir-graphs-1a0078933406?source=rss-e31e18aedeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a0078933406</guid>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[plot]]></category>
            <category><![CDATA[sir-model]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Ege Hosgungor]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 17:49:56 GMT</pubDate>
            <atom:updated>2020-07-29T12:06:50.931Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@hosgungor/create-a-pandemic-simulation-with-unity-8eb37ca816f1">In the last article</a> we have created the simulation environment with unity. By the end of this article we will have an analysis of our outcomes from our Pandemic Simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*JGFUOvPjvQgX194y" /></figure><h3>Getting Started</h3><p>Creating the simulation was a huge step. But without analyzing the outcomes of the simulation it is only a cute graphics. In this article I will continue from <a href="https://medium.com/@hosgungor/create-a-pandemic-simulation-with-unity-8eb37ca816f1">where we left</a> and implement the data collection&amp;plotting mechanism for the simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*2oXlvkv5z8VI_e9h.gif" /></figure><p>The source of the project is available on github. <a href="https://github.com/Hsgngr/Pandemic_Sim">You can download or clone from here</a>. We only need the data in order to analyze it.</p><h3>What is a SIR Model ?</h3><p>The SIR model is a simple model, due to Kermack and McKendrick, of an epidemic of an infectious disease in a large population. We assume the population consists of three types of individuals, whose numbers are denoted by the letters S, I and R (which is why this is called an SIR model). All these are functions of the time t, and they change according to a system of differential equations.</p><p>S is the number of <strong>susceptibles</strong>, who are not infected but could become infected.I is the number of <strong>infectives</strong>. These individuals have the disease and can transmit it to the susceptibles. R is the number of <strong>recovered </strong>or <strong>removed</strong> individuals.</p><p>The article will consist of two parts. First part will be about exporting the game-data to csv, we will write a simple script called <em>“Export Csv.cs”</em> and update <em>“PandemicArea.cs” </em>For the second part, we will analyze the csv data and create <em>“SIRGraph.py” </em>in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*7ZiV7sw3TtLUgUhLz5MiiA.png" /><figcaption>Scripts that we will create/update for exporting the data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*yBFOFoORYJnr8iPMUfgvSg.png" /><figcaption>SIRGraph.py and the exported csv data</figcaption></figure><h3>Exporting the data from Unity</h3><p>Unity doesn’t have any built-in function to export data except for monetization called <a href="https://unity3d.com/unity/features/analytics">Unity Analytics</a>. We will create our own code to simply record the data when it changes and write on a csv file. The file will be called <em>export.csv.</em> <em>record() </em>function will add a new line to our file each time when we call it. <em>addHeaders()</em> will be called once in <em>Awake() </em>function of Pandemic Area after we established the area object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/242bc6785d522488f90e6213f3a9ec2f/href">https://medium.com/media/242bc6785d522488f90e6213f3a9ec2f/href</a></iframe><p>In <em>pandemicArea.cs</em> there were basic counters for healthy, infected, recovered individuals. We changed them by adding get set accessor to have full control on these variables. Therefore we don&#39;t need to check every frame for “is there any change ?” with a function like <em>Update().</em> it is basically very inefficient to use like that. To understand why this is necessary I will recommend you this youtube video tutorial : <a href="https://www.youtube.com/watch?v=ZjoVSAcf63w">Get And Set Accessors</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbc3e0c79e7bfee25d688df2a62b6a62/href">https://medium.com/media/fbc3e0c79e7bfee25d688df2a62b6a62/href</a></iframe><p>We will also slightly change the function on the dummyBot.cs. The important part in this function is the variables first letters. When you call a variable with its capital letter you call its <strong>get accessor</strong>. For example in the below we decrease the <em>healthyCounter</em> as previous. On the other hand, increasing <em>InfectedCounter </em>calls the get-set accessor which leads to record the data. The purpose of using both of them in the same code is to prevent duplicate records in the csv.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9af337b15e7b16ad5b3ceed48bc5a055/href">https://medium.com/media/9af337b15e7b16ad5b3ceed48bc5a055/href</a></iframe><p>When you run the simulation it will collect the data for you. Here is the example of the csv file. I started with 2000 healthy cube with 10 infected ones. I’m using real time after the simulation started in seconds. Congrats you just exported your simulation data from Unity to csv👏</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*hZDiO66v4sTT18wFgt7FLw.png" /></figure><h3>Plotting the data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*qImbzjnWRIrVUujj91W9oQ.png" /><figcaption>20 groups of</figcaption></figure><p>After the hard and mysterious part of the tutorial, we came to the fun part. This python script helps us play with the data we just exported. It is basic plotting except the Kmeans part. <strong>K-means clustering</strong> is used to group the points so that I can avoid noise. This helped me to smooth my curves and decrease the points and get more generalized curve. I had over 300 points for 100 individuals in the data. I grouped them into 20 groups. Then I draw the lines between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*BO8ADf033gu827DU-DUBlA.png" /></figure><p>Compare to libraries like <strong>scipy</strong> and <strong>csaps</strong>, K-means clustering worked like a charm for smoothing my curve. The best result after K-means was Interpolation() function of scipy and you can see how it looks edgy compare to K-means</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*YyZtL9E7AefG9OVQ4WlTSQ.png" /><figcaption>Smoothing comparison<strong> Left</strong>: scipy.Interpolate()<strong> Right</strong>: Kmeans-Clustering are used</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b2d18865c5cd1a48660be3e8a085cbf/href">https://medium.com/media/3b2d18865c5cd1a48660be3e8a085cbf/href</a></iframe><h3>Results</h3><p>Seeing your simulation with graph visualizations helps to understand how your model behave, how it is close to the real world data. By playing with the infectious rate, numbers of healthy and infected individuals at the start, recovery time, infectious radius, one can learn a lot about how SIR Models work. You can also check from here that the results are pretty close to actual SIR models. <a href="https://kx.com/blog/dynamic-modeling-of-covid-19/">Dynamic modelling of covid-19</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*34FWdyFIKInD0T7XqmSW7A.png" /></figure><h3>Next Steps</h3><blockquote><em>I have been doing this series for my Master Dissertation: </em>“Simulation-based Reinforcement Learning for Social Distance” <em>the first two parts of the series were about setting the environment for the simulation and analyzing how environment behaves including this tutorial. Next I will integrate Artificial Intelligence into the project and convert the simulation into a learning environment for agents. Here is an example gif from the project. Blue agent is controlled by a neural network. The aim is to get the reward without getting sick.</em></blockquote><blockquote><em>To be continue…</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*wJnpd214y_Let7AY" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a0078933406" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Pandemic Simulation with Unity]]></title>
            <link>https://hosgungor.medium.com/create-a-pandemic-simulation-with-unity-8eb37ca816f1?source=rss-e31e18aedeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eb37ca816f1</guid>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[pandemic]]></category>
            <dc:creator><![CDATA[Ege Hosgungor]]></dc:creator>
            <pubDate>Sat, 04 Jul 2020 00:27:51 GMT</pubDate>
            <atom:updated>2020-09-13T20:07:14.514Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create an Epidemic Simulation in Unity I: Simulating an epidemic spread</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ARXmKUKhDzyy8HodSs6suQ.gif" /></figure><h3>Motivation</h3><p>After the Covid-19 Outbreak, many wonderful articles have been written about simulating an epidemic spread. One of them was in <a href="https://www.washingtonpost.com/graphics/2020/world/corona-simulator/">Washington Post</a> and other was on<a href="https://www.youtube.com/watch?v=gxAaO2rsdIs"> 3Blue1Brown</a> Youtube channel. These are wonderful simulations and it pushed me to create my own. This simulation is inspired from SIR Model which is an epidemiological model that computes the theoretical number of people infected with a contagious illness in a closed population over time. <a href="https://medium.com/@hosgungor/create-a-pandemic-simulation-with-unity-ii-analyzing-sir-graphs-1a0078933406">Next article is going to be about how to plot these simulations and compare them.</a></p><h3>Why Unity ?</h3><p>There are many advantages of using a game engine. First of all the physics of the simulation can get exponentially get complex when you want to add something new. I tried to create one of my own, and I did however it wasn’t suitable to scale. There are many resources on the internet for Unity so you don’t have to create everything from scratch. In addition I would like to use Unity mlAgents after creating the simulation. <a href="https://github.com/Unity-Technologies/ml-agents">mlAgents</a> is a package of Unity for creating Reinforcement Learning environments which you can train your own AI but this topic is for another article.</p><h3>Getting Started</h3><p>The source of the project is available on github. <a href="https://github.com/Hsgngr/Pandemic_Sim">You can download or clone from here</a>. We only need the scripts in order to create the simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*whFoBWZl-DYYYED28ESM-Q.png" /><figcaption>DummyBot and Pandemic Area Scripts</figcaption></figure><p>First one is called PandemicArea.cs and this is going to be the interface between you and your pandemic simulation. There are plenty of different settings here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*ubk6vwp3cnHazMT9JEOfww.png" /><figcaption>PandemicArea.cs in Editor</figcaption></figure><p><strong>Range :</strong> defines the area that your dummyBots can reach in environment.</p><p><strong>Bot Settings: </strong>You can choose what kind of bot are you going to use and how many infected-healthy at the start.</p><p><strong>Infection Settings: </strong>This will provide you total control on your infection spread. Bots are using an infection mechanism with their sphere colliders which provides them some probability of getting infected. You can change this by playing infection coefficient. It is inversely proportional to how infection is the disease. With the exposure radius you can change the collider radius of the bots. The last one gives the recover time which bot needs to wait before it can recover from the infection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb240c04c0853dea48c5e4a3b58203ab/href">https://medium.com/media/cb240c04c0853dea48c5e4a3b58203ab/href</a></iframe><h3><strong>DummyBot Prefab</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQEDSxdQ5TkfWMf7wQQEkQ.png" /><figcaption>Healthy-Infected-Recovered</figcaption></figure><p>Now it is time to create dummyBots. I am calling this “dummy” because it will act randomly. In the next article we will have an agent who does actually take decisions with a neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*YUTndei3qKnfabLm1l282Q.png" /></figure><p><strong>Different Materials: </strong>It helps us to distinguish healthy agents from others and visualize how infection spread.</p><p><strong>Probability: </strong>Is the infection probability which is overriden by PandemicArea.cs However it provides a great visualization for how infection mechanism works.</p><p><strong>Infection Status: </strong>is an enum with 3 different states. Healthy, Infected and Recovered.</p><p>I would like to mention how <strong>MoveRandomTarget()</strong> function works. When the bot is initialized it will calculate a random position and needed time to go that spot inside the area. The time is defined as <strong>nextActionTime </strong>and<strong> </strong>when its finished (when it comes to that position) It will choose another random position.</p><p><strong>exposeInfection(GameObject Infector) </strong>takes the potential infector which is colliding with this dummyBot’s sphere collider. While the distance decrease between the bots the probability of getting infection is increasing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95bbf008b33933877df391a836bbb830/href">https://medium.com/media/95bbf008b33933877df391a836bbb830/href</a></iframe><h3><strong>Next Steps</strong></h3><p>Once you have created your base simulation, you can add many interesting stuff on top of it and play with it. In the next article I will convert this simulation into a learning environment for an AI agent. In the GIF above you can see blue colored agents .The agent’s purpose is going to learn“how to social distancing” with Reinforcement Learning. Even now I am getting excited about it. I hope this also helps your project. I would be glad to answer if you have any questions, Stay safe!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*6y4GugPO9lokTFFjtYfVMQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eb37ca816f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>