<?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 Harry Cheng on Medium]]></title>
        <description><![CDATA[Stories by Harry Cheng on Medium]]></description>
        <link>https://medium.com/@harrychengz?source=rss-883fba0aad4e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BYDz68Q5IsewrSYJEMwkOw.jpeg</url>
            <title>Stories by Harry Cheng on Medium</title>
            <link>https://medium.com/@harrychengz?source=rss-883fba0aad4e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:30:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harrychengz/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[How data science can help you play Clash Royale better]]></title>
            <link>https://harrychengz.medium.com/how-data-science-can-help-you-play-clash-royale-better-517fb840168d?source=rss-883fba0aad4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/517fb840168d</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clash-royale]]></category>
            <category><![CDATA[sports-analytics]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Harry Cheng]]></dc:creator>
            <pubDate>Tue, 19 Apr 2022 09:41:49 GMT</pubDate>
            <atom:updated>2022-05-04T12:12:40.572Z</atom:updated>
            <content:encoded><![CDATA[<h4>E-Sports analytics</h4><h4>Use EDA, statistical model, and machine learning model to up your Clash game</h4><p><em>For video representation of the project, click </em><a href="https://www.youtube.com/watch?v=ZFEcL9qFinQ&amp;t=3813s&amp;ab_channel=%E9%84%AD%E7%9A%93%E5%B9%B3"><em>here</em></a><em>.</em></p><p>Clash Royale is one of the most successful mobile games. Came out 6 years ago, the game is still popular. It is a game where players (typically 1 vs 1) use their customized deck of 8 cards to battle each other. They will use their cards at the expense of “elixir”, and try to destroy their opponents’ towers. (Gameplay shown below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*-Vxdz6Un0offX8rWCK0f9w.gif" /><figcaption>Source:<a href="https://tenor.com/view/clash-royal-gif-7410796">https://tenor.com/view/clash-royal-gif-7410796</a></figcaption></figure><p><a href="https://www.youtube.com/watch?v=_hNxfiXmeAE&amp;ab_channel=ClashRoyale">Here is a video introduction of Clash Royale</a>.</p><p>Combining my passion for data science and Clash Royale, I decided to do a Clash Royale analytics project where I make use of the power of data to help answer some of the most important questions to understand/play the games better.</p><p>This article serves as an abstract for the project, where I explain the high-level overview of the project in plain English, mainly focusing on the methodology used and the result of analysis. If you are interested in the details of the project, you can check out <a href="https://www.youtube.com/watch?v=ZFEcL9qFinQ&amp;t=3813s&amp;ab_channel=%E9%84%AD%E7%9A%93%E5%B9%B3">this YouTube video</a>.</p><p>The entire project is written in Python. All of my code can be found in this <a href="https://github.com/Harry-py/ClashRoyaleAnalytics">Github repository</a>.</p><p>Now without further ado, lets get down to business!</p><h3>Problem definition</h3><p>The core problem we need to solve here is:<em> “How do we play Clash Royale better?”</em></p><p>It is a very broad issue with countless possible approaches, some supported by data some not. To organize our thoughts and possible solutions for the problem, it helps to break the topic down and generate an issue tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDq5DrswE16Y_Oznz7Gpmw.png" /><figcaption>Created by author</figcaption></figure><p>The first thing I do with the issue tree is to cut off the “Techniques” branch, as there is no data available to support that analysis, although it could be very relevant.</p><p>With only the “Decks” branch left, I narrowed down the scope of the question to: <em>“How to play Clash Royale better by picking better decks?”</em>. To answer that, I describe a deck with three dimensions— <strong>Card Level(players can upgrade their cards level in the game), Deck Stats(Attack, speed, hit-points, etc.), and Deck Composition(# of melee, sky units, tanks, etc.)</strong>. I will do some exploration among these features before putting all of them into the model.</p><p>After some further breakdown of the three dimensions and brainstorming, as well as taking into consideration data availability, I listed out the 4 key questions to answer for this project:</p><ul><li><strong>Q1: </strong>How much does cards level contribute to winning?</li><li><strong>Q2:</strong> What’s the meta? <br> — Is there a super OP/broken champion?<br> — What are the popular cards?<br> — How do people usually pair up champions?</li><li><strong>Q3: </strong>What’s the countering/synergetic relationships between champions?</li><li><strong>Q4:</strong> How do we predict the outcome of a game based on players’ decks?<br> —What are the relevant features?<br> — Given two decks, who will win?</li></ul><p>After answering all the questions above, hopefully we will have a clear guidance as to what champions to choose, what to pair it up with, what are the countering champions, and actually test out our deck with the predictive model.</p><p>Now I will walk you thru the approaches I used to answer the above questions and the results I got. In plain English, of course :)</p><h3>Data Gathering</h3><p>Given the scope of the questions, I need <strong>match level data</strong> with information regarding deck composition, cards level, as well as match result (win/lose).</p><p>The perfect data source to get such data is Clash Royale’s official API. I chose it because it is very reliable and up to date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSjP63ADwEXSoJ4zk8MzeQ.png" /><figcaption>Clash Royale API</figcaption></figure><p>I used Python’s request library to interact with the API. More on this in <a href="https://www.youtube.com/watch?v=ZFEcL9qFinQ&amp;t=3813s&amp;ab_channel=%E9%84%AD%E7%9A%93%E5%B9%B3">my YouTube video</a>.</p><p>I ended up gathering~2M rows of data (accidentally), but only used~20,000 samples for EDA, and ~12,000 samples for model training, validating and testing.</p><h3>Q1: How much does Card Level contribute to winning?</h3><p><strong>Answer first:</strong> A lot, but the effect lower as your trophy number (think ranking) increases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*fjxDon8tVHUk-cjZn-ot1w.png" /><figcaption>Strong linear association</figcaption></figure><p>After running a logistic regression on <strong>average cards level difference</strong> and <strong>winning</strong>, I found that: if your <strong>cards are on average 1 level higher</strong> than your opponent, <strong>your chance of winning that match is 97% higher</strong> than without the cards level advantage. This is crazy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*lvcShheeVNhRnCY4r84LGg.png" /></figure><p>However, most of us don’t have such crazy advantage, and correlation does not imply causation.</p><h3>Q2: What’s the meta?</h3><p>Meta here refers to the common practice/popular usage of cards.</p><p><strong>Answer first:</strong> The game is pretty well balanced (No exceptionally strong champions), but some cards are more popular than others. It is also common practice to put specific cards together.</p><p>In this part I segmented all cards into 17 detailed categories, and used informative charts as well as association rule mining to find insights that describe the current meta. Some of the outputs are as below: (All of them come from random sample of 20,000 matches)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*a54lhk0xDXSUEIpriGZpWw.png" /></figure><p>Above we can see that win rate is pretty much the same for all cards, but some cards are extremely popular and others rarely used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*ehWswA2ZpAiludlc_DxJIA.png" /><figcaption>Popularity of melee units</figcaption></figure><p>Valkyrie is all time meta for sure…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*gN6laLeJ60Pv_3l26vLY4g.png" /><figcaption>association rule mining</figcaption></figure><p>Above is the top 5 result of associate rule mining for advanced players. The higher the “Lift” column, the stronger the association of the two cards. We can see that <strong>Goblin Barrel</strong> and <strong>Princess</strong> are extremely popular together (I also have a deck with them together and I didn’t even notice). Other pairs here are also popular combinations since people think they could create synergies. But we can find out whether they ACTUALLY have synergies in the next part.</p><h3>Q3: What’s the countering/synergetic relationships between champions?</h3><p>I define <strong>countering relationship</strong> as: <em>If X has lower win rate when faced with Y, then Y counters X.</em> Likely, <strong>synergetic relationship</strong> is defined as: <em>If X and Y together has higher win rate than X alone, then X and Y creates synergy.</em></p><p>And to test if the lower/higher win rate is significant, I used the famous Chi-Square Test of Independence.</p><p>That is, given a champion, I would run the test on every possible pairs of cards and list out the most significant countering/synergetic cards for the given champion.</p><p>Take one of my favorite champion, <strong>Golem</strong> for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*z4Uklg1k5UEnQjFx" /><figcaption>Golem (source: <a href="https://clashofclans.fandom.com/wiki/Golem">https://clashofclans.fandom.com/wiki/Golem</a>)</figcaption></figure><p>Using my methodology, I generated the following tables describing Golem’s top 5 counters and synergetic cards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sC_FbaZTJooR-XeVVfi0sw.png" /><figcaption>Counter table</figcaption></figure><p>A is when Golem is played against the deck with countering champion, B is when Golem is played against deck without countering champions. P-value is the result of Chi-Square test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZonQygRIEhcZ5BBQV25mg.png" /><figcaption>Synergy table</figcaption></figure><p>A is when Golem is played with the synergetic champion, B is when Golem is played without the synergetic champion.</p><p>If you play Clash, you might find the result a bit weird. While it’s no brainer that P.E.K.K.A and Inferno Tower counter Golem, how is Executioner the best counter for Golem?</p><p>This is because the table not only captures the <strong>direct counter</strong> of the champion, it also captures the <strong>indirect counters</strong>. P.E.K.K.A and Inferno Tower directly counters Golem, while Executioner counters cards that are usually paired with Golem (Usually flying units).</p><p>Same thing goes to Synergy tables. All types of synergies are captured.</p><h3>Q4: How do we predict the outcome of a game based on players’ decks?</h3><p>It is pretty obvious that this is a predictive modeling question. The model needed is a typical binary classification machine learning model.</p><p><strong>ML algorithm used:</strong> Many were tested, but ultimately landed on Logistic Regression!</p><p><strong>Features used:</strong> Deck’s stats (Avg. hit-point, Avg. damage, Avg. attack radius, Avg. cards level, etc. ) , narrowed down from 60+ to just 10 features</p><p><strong>Performance:</strong> ~60% accuracy in predicting match result. ~0.68 AUC.</p><p>Below is a simple summary of the model building process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbgagOEaPJnyvecIzyFB1w.png" /><figcaption>Chart created by author</figcaption></figure><p>As you can see from the chart above, a lot of experiments and decision making went into the process of building the model. For the purpose of this article, let’s just focus on the result. Follow my upcoming <strong>model building article, </strong>where I explain every step of the model building process in fine detail.</p><p>Below is the confusion matrix of the model when tested with test data. (I split the data into train, validation and test.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*ZBzHbClHkZlarGfiAiVS1w.png" /></figure><p>From the matrix, we can calculate some metrics:</p><ul><li><strong>Accuracy: 59%</strong>,<strong> </strong>meaning 59% of the predictions are correct.</li><li><strong>Precision:</strong> <strong>73%</strong>, meaning within those matches model classified as “Won”, 73% are correct.</li><li><strong>Recall: 24%</strong>, meaning the model only correctly identified 24% of all winning matches.</li></ul><p>In other words, the model has pretty strict standard on identifying winning matches. If the model tells you “you are winning”, you very likely will. But expect the model to tell you a bunch of times that you’re losing, and 44% of them will be false alarm.</p><p>This kind of unbalanced result usually comes from unbalanced samples, but the training and validation samples I used were perfectly balanced(50% win, 50% lose). Also, since the purpose of the model is to identify winning decks, it helps to be a bit more strict on the result.</p><p>However, I still plotted out a ROC curve, and messed with the probability band a little bit to see other possibilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*DKflq8IL8K1h_jVsSpBeIA.png" /><figcaption>ROC Curve, a bit right skewed as expected</figcaption></figure><p>I found out that if I lower the probability threshold to 0.25, meaning the model classifies a sample as “won” when the winning probability predicted is just over 25% (default is 50%), the accuracy can be elevated to <strong>62%</strong>, but precision will drop to <strong>62%</strong>.</p><p>Now lets take a look at what does the model say about the strongest deck! For the below sample, the model predicted probability of winning is equal to 98.5%…and indeed it won.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*Met3tOjVxkFSL4gaMgXkOQ.png" /></figure><p>You can see that the winning deck has ridiculously high card level advantage, champions are generally faster (speed diff = 5), and it has units that deals high damage to tower.</p><p>So if you have this kind of deck, there is basically no way you can lose.</p><h3>Conclusion</h3><p>I hope this project provided some useful insight for Clash Royale, both at a macro level and micro level.</p><p>Again, this article only represents a snapshot of the entire project. Check out <a href="https://www.youtube.com/watch?v=ZFEcL9qFinQ&amp;t=3813s&amp;ab_channel=%E9%84%AD%E7%9A%93%E5%B9%B3">my YouTube Video</a> if you want to know more!</p><p>And although I tried to be as unbiased and exhaustive as possible, this project is still far from perfect. All comments are welcomed!</p><p>Give me some claps and click follow if you want to see more original side-project like this :)</p><p>If you are also passionate about data science and business analytics, or if you are a recruiter in the field, or you just want to talk to me, you are welcomed to connect with me on <a href="https://www.linkedin.com/in/harry-hao-ping-cheng-aab38a193/">Linkedin</a>.</p><p>See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=517fb840168d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[海外留學到底值不值得花費大筆經費？一個模型告訴你]]></title>
            <link>https://harrychengz.medium.com/%E6%B5%B7%E5%A4%96%E7%95%99%E5%AD%B8%E5%88%B0%E5%BA%95%E5%80%BC%E4%B8%8D%E5%80%BC%E5%BE%97%E8%8A%B1%E8%B2%BB%E5%A4%A7%E7%AD%86%E7%B6%93%E8%B2%BB-%E4%B8%80%E5%80%8B%E6%A8%A1%E5%9E%8B%E5%91%8A%E8%A8%B4%E4%BD%A0-1b8e90908624?source=rss-883fba0aad4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b8e90908624</guid>
            <category><![CDATA[graduate-school]]></category>
            <category><![CDATA[financial-model]]></category>
            <category><![CDATA[npv]]></category>
            <category><![CDATA[study-abroad]]></category>
            <dc:creator><![CDATA[Harry Cheng]]></dc:creator>
            <pubDate>Sat, 29 Jan 2022 15:21:45 GMT</pubDate>
            <atom:updated>2022-01-30T05:47:06.035Z</atom:updated>
            <content:encoded><![CDATA[<h3>海外留學到底划不划算？一個模型告訴你</h3><h4>用淨現值模型估算海外留學價值</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctt87LYT252nN-9UVj9pNQ.png" /></figure><p>海外留學是許多人的夢想，但是對於出身平庸的人（e.g. 我）來說，動輒一兩百萬的留學費用可不是隨隨便便就掏得出來的。精打細算如我，當然會希望每一分錢都花的值得。</p><p>但是難題就在此：<strong>如何確保每一分錢都花的值得？</strong></p><p>要回答這個問題，必須要考慮一大堆量化與質化的因素。量化的例如：學費、獎學金、生活費、畢業後起薪、獎金、薪水成長幅度等等。質化的則是：生活舒適度、自我成長、語言學習、自我實現等等。這麼多東西，實在很難全部都考慮到，尤其在比較不同program的時候，更讓人頭疼。</p><p>因此我建了一個淨現值（NPV）模型，希望能把所有的量化因素都納入一個模型中計算，並且得出一個明確的數字。這個數字就是申請海外留學計劃的價值，可以拿這個數字跟其他的留學計劃、生涯規劃作比較。</p><p>在量化的部分得出一個結論後，再加上一些質化考量，想必一定能夠快速且正確地判斷出海外留學的價值。</p><p>接下來這篇文會講述三個部分：</p><p>一、模型運作原理（Input、Output、結果解釋）</p><p>二、模型使用流程</p><p>三、模型注意事項</p><p><strong>歡迎大家透過</strong><a href="https://drive.google.com/drive/folders/1vtfPPE4pnnuMZG7PGeY87ULJGvCelcG7"><strong>這個連結</strong></a><strong>下載我的模型，在看文章的時候可以一邊玩玩看，之後也可以直接使用模板搭自己的模型！</strong>（連結中有三個文件，一個是我用UCLA MSBA做的範例，兩個是模板。1year代表一年計劃，2year是兩年計劃。）</p><h3>模型運作原理</h3><h4>淨現值（NPV）是什麼？</h4><p>淨現值其實是一間公司在判斷一個投資案是否值得的時候所使用的指標。主要考慮的因素有：投資案的成本、未來可能產生的現金流、借貸成本等等，並且會用這些因素計算出一個價值。（若想要更深入了解，<a href="https://wiki.mbalib.com/zh-tw/%E5%87%80%E7%8E%B0%E5%80%BC%E6%B3%95">請點此</a>）</p><h4>模型的Input</h4><p>若是把海外留學也想成一個投資案，也能夠算出海外留學的淨現值：</p><ul><li>投資案的成本 →學費、生活費</li><li>未來可能產生的現金流 →未來薪水、扣除所得稅</li><li>借貸成本 →留學貸款利率</li></ul><p>而以上這幾點也確實是我的模型的input。（以下解說皆以UCLA MSBA為例，因為那是我想申請的program之一哈哈）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meYKAgyoOgx2EKxzF-GQ3Q.png" /><figcaption>模型截圖</figcaption></figure><p>但是為了讓每個input值都更加精確，我加上三個考量：</p><ul><li><strong>拆解Input：</strong>把每一個值拆解成很多小單位，以求更精準的估算。（e.g. 生活費拆成租金、伙食、交通等等）</li><li><strong>Input變化：</strong>加上變化因素。（e.g. 薪資成長比率）</li><li><strong>情境分析：</strong>根據不同情境調整input數字。這邊分成兩個部分：職涯（樂觀、悲觀），以及生活品質（節儉、奢華）。</li></ul><p>晚點會詳細解釋如何使用各項考量。</p><h4>模型的Output</h4><p>當Input都填完了之後，模型會跑出以下結果（紅色的數字為負數值）：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*tKVdQSfQ-asOsqDVP43Aig.png" /><figcaption>模型結果截圖</figcaption></figure><p>我對以上結果的解釋方法是：在海外待X年，這個計劃值XXX元。</p><p>以上圖為例，在美國待兩年（2 year NPV），這個計劃值-$38,313元，因為第一年才剛付昂貴的學費。但若是在美國待到3年，這個計劃就值$16,155元了。若是待了10年，計劃就值$463,081元。</p><p>這個結果的用法有兩種：</p><ul><li><strong>比較不同計劃：</strong>分別把多個留學計劃放進模型，比較哪一個計劃的NPV最大，就是最有“錢途”的計劃。</li><li><strong>思考何時計劃會回本：</strong>看哪一年NPV由負轉正，判斷應該要在海外待幾年才划算。（同時可以考慮工作簽證等因素，判斷究竟是否可行）</li></ul><p>從上面的例子來看，UCLA的MSBA計劃三年就能回本了。美國提供3年工作的簽證，是綽綽有餘。就算簽證到期必須回台灣，這個計劃還是值得的。</p><h3>模型使用流程</h3><h4>三步驟</h4><p>要使用這個模型，只有簡單的三個步驟：</p><p>一、輸入資料（薪資、學費、生活費等等）</p><p>二、設定假設（成長率）</p><p>三、情境調整</p><h4>輸入資料</h4><p>整個模型分成四個工作表，一個是分析的（NPV analysis），另外三個是輸入資料的。在輸入資料的環節只要碰後面三個工作表就行。</p><p>第一個工作表是借貸成本。只要輸入留學貸款的利率就行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*k6nrEbaaP3CsnsCtXzgKgg.png" /></figure><p>第二個工作表是薪水及稅收。薪水的部分許多program會出自己的職涯報告，從裡面能夠得到比較精確的數字。稅收的資料也是很透明，很好取得。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-G5VQEhQA0XWC04niUndhQ.png" /></figure><p>第三個工作表是生活費及學費。學費能夠得到很精確的數字，生活費則是比較困難。我這邊分別估算了在LA正常、節儉、奢侈的三種不同生活費。</p><p>使用的時候可以根據自己個人的需求再對小單位的資料做客製化（增加個人藥物開銷、回家的機票錢等），同時每個program長度也可能不同，可能會有year 2、year 3 的tuition。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*QCEqf6Jp9sOfCIMuT4rs6A.png" /></figure><p>在資料全部輸入完畢之後，可以再透過一些外部資料、學長姐的訪問來檢查自己的數字是否合理。因此，如果你是MSBA的學長姐或是在LA住過的人，拜託你跟我講講你的想法，我會很感激~可以直接透過<a href="https://www.linkedin.com/in/harry-hao-ping-cheng-aab38a193/">Linkedin</a>聯繫我！</p><h4>設定假設</h4><p>這一部分要回到分析的工作表，並且為所有藍色的數字輸入自己的假設。綠色的數字是從先前輸入的資料拉過來的，可以不用動。黑色的數字則是根據綠色以及藍色數字算出來的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7u4tlQBgzJcSyxitYdWRA.png" /></figure><p>這邊使用的時候有兩點要注意：</p><ul><li><strong>藍色數字的設定最好還是有根據。</strong>可以問問學長姐、查查就業報告，看看每年15%的薪資成長合不合理。同時，我這邊假設每年的薪資成長幅度都一樣，但是這個假設根據不同的產業、公司都會有不一樣的答案。如果有大神能夠回應我在這邊做的假設，我會十分感激！</li><li><strong>有個黑色數字也有參數可以調。</strong>Year 1的生活費中的黑色數字公式裡面有暗藏假設。我假設第一年的生活費為第二年的80%，因為第一年有學校住宿、學生優惠等等。這個可以根據自己的狀況做調整。</li></ul><h4>情境調整</h4><p>所有input數字都輸入好了之後，應該就會有NPV跑出來了。這時候可以到左上角調整情境，看看不同情境下的NPV長什麼樣。直接改“Assumptions”表格裡面的數字就行了，總共會有九種組合。</p><p>Career是職涯發展，有conservative、base、optimistic三種情境，會影響到薪資的成長率。Life Quality則是生活品質，有tough、normal、comfortable三種情境，會影響到生活花費。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*sMffssO9mhBOL9qMP3xu-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*OKjFbEHyshpkbVMI6GYMAw.png" /></figure><p>一個使用的例子是：在Career=1（職涯發展最糟糕）、Life Quality=3（生活最奢侈）的情況下，NPV若還是很好看，就代表這個計劃挺不錯的。</p><h3>模型注意事項</h3><h4>不要抓太久的時間</h4><p>兩個最主要的因素，薪水及生活花費，受到時間的影響也最大。尤其是生活花費，時間久了甚至還得考慮搬家、結婚生子等，實在是很難估。所以建議抓5年內的NPV會比較準。</p><h4>兩個留學計劃比較時，一定要使用相同的期數做比較</h4><p>NPV模型本身會偏重時間較長的project，所以必須用同樣的年數比較。</p><h4>模板有分一年以及兩年，注意計劃長度不要用錯。</h4><h3>結語</h3><p>感謝你看完這篇文章！希望有幫助。再貼一次<a href="https://drive.google.com/drive/folders/1vtfPPE4pnnuMZG7PGeY87ULJGvCelcG7?usp=sharing">模型連結</a>。</p><p>我自己很久以前就想要出國唸MSBA了，最近也要開始準備GRE了。歡迎各位同期要申請的戰友、申請上的學長姐來跟我交流！對於模型有任何的feedback也都非常歡迎（可以一起fine tune這個模型）！</p><p>可以加我的<a href="https://www.linkedin.com/in/harry-hao-ping-cheng-aab38a193/">Linkedin</a>跟我聯絡~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b8e90908624" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[大學生在想什麼？Netflix什麼最紅？Python 5分鐘告訴你！]]></title>
            <link>https://harrychengz.medium.com/%E5%A4%A7%E5%AD%B8%E7%94%9F%E5%9C%A8%E6%83%B3%E4%BB%80%E9%BA%BC-netflix%E4%BB%80%E9%BA%BC%E6%9C%80%E7%B4%85-python-5%E5%88%86%E9%90%98%E5%91%8A%E8%A8%B4%E4%BD%A0-f3b77baeb7?source=rss-883fba0aad4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3b77baeb7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[word-cloud]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Harry Cheng]]></dc:creator>
            <pubDate>Sat, 24 Jul 2021 04:57:03 GMT</pubDate>
            <atom:updated>2021-07-24T04:57:03.654Z</atom:updated>
            <content:encoded><![CDATA[<h4>Python實作</h4><h4>使用爬蟲以及NLP呈現訊息滿滿的文字雲</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_ibgffFV0GZD7mrkIy2kg.jpeg" /><figcaption>使用python跑出來的文字雲</figcaption></figure><p>在當今資訊爆炸的社會，資訊不斷增加，但一個人始終只有一天24小時，因此人類的注意力也變成了一種稀缺的資源。</p><p>在社群網路演算法的不斷變化之下，網友的注意力越來越難搶。FB的organic reach（未付費po文接觸到的人÷可能接觸到的人的總和）逐年下降，掉到了只有<strong>5%</strong>左右。</p><p>在這種情況之下，粉絲專頁就算有許多的follower還是沒有用。真正有用的，是更加客製化、更加貼近客戶生活的行銷內容。</p><p>那要如何知道客戶在想什麼呢？一個好方法是利用社群網路上的文本資料。也就是透過社群網路上各種文章、留言的文字集合體，來判斷社群整體的話題趨勢。</p><p>使用Python能夠很輕易的做到這件事。接下來的文章，我會以Dcard分析為例，帶你走過整個實作過程，並且附上我所有的<a href="https://github.com/Harry-py/Dcard_wordcloud">程式碼</a>。</p><h3>目錄</h3><ol><li>資料搜集 — Dcard API</li><li>資料處理 — 自然語言處理</li><li>資料視覺化 — 文字雲</li><li>結語</li></ol><h3>資料搜集 — Dcard API</h3><p>假設你今天是一個大學社團社長，或是大學附近的商店，你的TA就是大學學生。要搜集大學生的想法，一個很好的去處是專門給大學生的社群平台 — Dcard。Dcard有全台每一所大學的專屬看板，也有分不同話題的看板（穿搭、遊戲、Netflix等等）。</p><p>以我的學校政大為例，每天政大Dcard板平均有30篇左右的貼文。是一個很活躍的社群。</p><p>要搜集Dcard的文章有兩個方式。第一個是使用beautifulSoup，selenium等爬蟲套件。這個方式在大多數網站都可行。另一種是使用Dcard的API。這個方式比較方便，但因為並不是每個網站都有API，所以不一定都適用。本文使用的是<a href="https://blog.jiatool.com/posts/dcard_api_v2/">Dcard API</a>。</p><h4>Dcard API</h4><p>API(Application Programming Interface)，是一個用來幫助開發者快速完成某些事情的工具。API就像是7–11裡的ibon機器，你只要輸入你要做的事情（取票、退貨、影印），機器就會自動處理，並且吐出結果給你（車票、退貨單、自動啟用影印機）。在本文的例子當中，我們只要輸入一些參數（想抓的看板、文章），API就會吐回抓到的文章、看板等等。</p><p>workflow大概是這樣：使用request套件get API的網址、使用json decode、製作成dataFrame。同時，一次request只能抓100篇文章。如果還想要繼續抓，就要輸入上一次抓的資料中最後一篇文章的id，再發一次request。因此我寫了以下函式，只要輸入兩個參數，alias（想要抓的看板名稱）、x（想要抓的文章數量，無上限），python就會反復發出request抓資料並且最後合併，回傳一個dataFrame。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQFl1Vg7R-_cQp-1gyUorQ.png" /></figure><p>從程式中也可以看出，我設定回傳的的dataFrame只有【文章標題】跟【看板名稱】兩個欄位。但是API能抓到的東西遠遠不止於此，包括文章內文、留言、讚數、po文者學校科系等等，都可以抓到。我這邊只抓標題是因為標題通常就是文章的精華，能夠簡潔的呈現文章主題。若是抓了文章、留言，容易發生特定文章多次重複使用特定字眼的偏誤（有些人在內文反復提到某些字）或是內文空洞的偏誤（如下圖）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*_RSOBDIOKYBEu_grI_q8bw.png" /><figcaption>一篇隨機dcard文</figcaption></figure><h4>Requests太頻繁被擋怎麼辦</h4><p>另外，如果使用Dcard API發出的requests（抓文章的請求）太過頻繁，網站會跳出captcha來擋你。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T9p3pK9rOnnS_ew0CtWWRw.png" /><figcaption>Dcard跳出來的captcha</figcaption></figure><p>通常遇到這種問題，會使用python的套件來繞過captcha，像是<a href="https://github.com/venomous/cloudscraper">cloudscraper</a>。但是由於Dcard使用的是比較高級的Captcha2，一般免費的套件是無法繞過的，必須付錢買比較強的套件（背後使用人工幫忙解captcha的套件）。</p><p>但是經過無數的trial and error，我測出了一個可以不被captcha擋住的停頓區間。也就是每一次requests之間隨機停頓2~6秒（少一秒也不行！）。API每次request能夠抓100篇文章，所以程式的速度大概是平均4秒抓100篇文，還算可以！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*wPFbGwPzU6leX4QOo0o97w.png" /></figure><h4>回傳的資料</h4><p>根據Dcard顯示，政大板平均每天30篇po文。所以如果要抓最近一年的所有po文，就是11000篇。截至7/23/2021，抓到的貼文如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*sv9JgIBwdbkVdPl_HQ6u9g.png" /></figure><h3>資料處理 — 自然語言處理</h3><p>我們所搜集到的資料當然不能直接丟進文字雲產生器，要先經過一些<strong>自然語言處理</strong>的步驟。</p><h4>自然語言處理是什麼</h4><p>大家平時聽到資料，想到的大概是一行行的數字。但是文字其實也是一種資料，而且裡面蘊藏的資訊一點都不比數字少。不過文字的處理實在是比數字tricky許多，因此人類結合人工智慧以及語言學，發展出了<strong>自然語言處理（Natural Language Processing，以下簡稱NLP）</strong>這個分支。這門學科現在仍在不斷地有新突破，從最早期的bag of words，到word2vec，再到這幾年非常火紅的BERT，人工智慧處理文本資訊的能力已經相當驚人。</p><p>網路上大多數的資源都是集中在英文的處理，但是中文需要一套很不一樣的處理方式。最明顯的差異，就是中文獨特的處理步驟 — <strong>斷詞。</strong></p><h4>斷詞、標詞性</h4><p>英文每個詞中間都用空格隔開，但中文都是黏在一起的。所以，在處理中文最早期的步驟之一就是把黏在一起的字詞斷開成一個個單獨的字詞。</p><p>台灣中研院有開發出一個方便的套件，叫<a href="https://github.com/ckiplab/ckiptagger">CKIP</a>，在繁體中文的斷詞有極高的準確率（97%）。此外，該套件也提供詞性辨識以及實體辨識的功能。</p><p>我寫了一個函式幫助文字的清洗跟斷詞。這個函式會刪掉所有的標點符號、表情符號等等不必要的資訊，並且使用CKIP斷詞。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtB_DOh0x-B7-krBgyfh6Q.png" /></figure><p>我們把這個函式放到迴圈，處理所有dataframe的資料，並且標上詞性。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtZbc8CqtgrfnIdlvIz6Aw.png" /></figure><p>結果如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*vJQR7_JUAVrkaPFdPyXvPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*K9ZkVfENQ5QcJM0ADICUQA.png" /><figcaption>斷詞以及詞性</figcaption></figure><h3>資料視覺化 — 文字雲</h3><p>資料處理完了，終於到了做文字雲的時候了！</p><h4>詞性挑選</h4><p>首先我會根據CKIP標示的詞性挑選要使用的字詞。這麼做是因為許多頻繁出現的字詞其實是感歎詞、語助詞、動詞等等，並沒有任何的意義。如果要知道政大學生在紅什麼，名詞跟形容詞是最有意義的。</p><p>因此我抓了普通名詞、專有名詞以及形容詞。完整詞性列表<a href="http://ckipsvr.iis.sinica.edu.tw/papers/category_list.pdf">在此</a>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qha5lrzVYhiaYX8bbOJflg.png" /></figure><h4>產生文字雲</h4><p>選好詞性之後，直接把資料丟進文字雲看看結果。</p><p>這邊文字雲使用的是<a href="https://amueller.github.io/word_cloud/">wordcloud</a>套件。文字雲裡面有許多參數可以調，可以自定義形狀顏色等等，這邊就是用比較一般的。注意，中文還要特別下載字體，並且輸入參數（font_path那一行）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3ClrYEcfy5RsCMg1dbmCg.png" /></figure><p>結果如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jH3cBwBNQJTlcw1mkRkHg.jpeg" /><figcaption>政大文字雲</figcaption></figure><p>越常出現的字就會越大。能夠大概看出一些在政大十分火紅的話題。</p><h4>如何調整文字雲</h4><p>從上圖可以看出，許多最大的字詞其實並沒有太大意義，像是“問題”。幸好文字雲有一個參數叫stopwords，可以讓程式略過你標註出來的字詞。我隨意挑選了一些我覺得沒有太大意義的字詞。當然，這部分的挑選會依照不同的應用客製化。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kCr78xYAXueFnAM4XDhcw.png" /></figure><p>更新後的結果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZRWDGQpfatrv6a_B-ZA-w.jpeg" /></figure><p>這就清楚多了！有一些原本沒抓到的字詞也被抓出來了，例如“花花”（政大的校狗）跟“黃子銘”（政大教授）。</p><p>簡單整理一下圖片的insights：</p><p><strong>政大話題:</strong></p><ul><li>達賢、圖書館（政大最近蓋了一間超級霸氣的達賢圖書館）、健身房、總圖、莊九（學生宿舍）</li><li>遠距、防疫、確診、口罩</li><li>文山聯盟（校長主導的文山區大學聯盟）</li><li>雙輔、雙主修、分數、學程</li><li>雄鷹（UBA冠軍超屌校隊）</li></ul><p><strong>熱門科系：</strong></p><ul><li>商院（號稱政大的天龍院）、財管、金融</li><li>法律系（聽說很愛在網路上打嘴炮的一個系）、財政</li><li>歷史、哲學（偶爾被戰的系）</li><li>以上言論不代表本文立場</li></ul><p><strong>熱門課程：</strong></p><ul><li>財務管理（本人也很愛的一堂課）、商事法、貨幣銀行學</li><li>生命、文化（甜涼通識課的關鍵字）</li><li>程式設計、大學外文、英文、民法</li></ul><p><strong>課外話題：</strong></p><ul><li>男生、女生、妹子、帥哥、政大生</li><li>面試、薪水、出路、工作、計劃</li></ul><p>不同的商家、單位對於這些關鍵字會有不同的用法，但是無論是誰都能夠快速地看出現在在政大流行的事物。</p><p>隨便舉例，假設有個政大附近的酒吧的老闆，正要思考新的促銷活動，但是對於政大事物沒概念。老闆使用最近的100篇文章做出文字雲，發現這幾天大家都在講雄鷹，一查之下原來是雄鷹奪冠了。因此老闆推出“慶祝雄鷹奪冠！來店消費每人招待一杯shot”的促銷活動，大成功。</p><h4>其他的文字雲</h4><p>除了政大之外，我還做了一個清大的文字雲。這兩間學校正好是分別以文科、理科為主的頂尖大學，也正好是我（政大）跟我哥（清大）唸的學校，因此拿來比較一下會很有趣。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mV-M4vrq6GKz8PndHuP-A.jpeg" /></figure><p>非常的不一樣呢！一個對於這兩件學校完全沒有背景知識的人也能夠從這兩張圖片中萃取出<strong>“政大是文科學校，清大的理科學校”</strong>這樣的資訊。</p><p>此外，我也使用Dcard的netflix板做了一個文字雲，挖的也是近一年的文章：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_ibgffFV0GZD7mrkIy2kg.jpeg" /></figure><p>這邊可以非常清楚的得知哪些影集比較紅。這對於廠商的行銷、代言也都是很有利的資訊。</p><h3>結語</h3><p>其實做出了文字雲之後，還能夠搭配<a href="https://zh.wikipedia.org/zh-tw/%E6%96%87%E6%9C%AC%E6%83%85%E6%84%9F%E5%88%86%E6%9E%90">情感分析</a>，進一步地分析大眾對於特定議題的看法。目前情感分析python也有許多套件可以使用，只不過中文的偏少。有中文的套件也大部分是中國大陸開發的，例如百度的Senta。台灣似乎只有中研院開發的<a href="http://rportal.lib.ntnu.edu.tw/bitstream/20.500.12235/80604/1/ntnulib_ja_A1021_4401_024.pdf">CSentiPackage</a>，但是該套件還沒有開放下載，我寄信跟他們要但他們不理我，所以我就算了。不過這邊要說的是，情感分析不難做，各種語言都有意見詞詞典，套件只是把文字根據詞典打分數（正負）而已（當然還是可以根據use case fine tune）。</p><p>除了情感分析之外，現在NLP能做到的事還很多很多。在人們發現把文字轉換成向量的技術之後，現在的模型已經可以做問答、剋漏字、語義判讀等等的事情。有興趣的人可以看看<a href="https://zh-tw.coderbridge.com/series/2ec9cf0af3f74ed99371952f4849ae33/posts/e2e46480d185435680609a40997644be">BERT</a>。</p><p>最後，如果喜歡這篇文章，請幫我拍手（按住可以拍很多下）~也歡迎follow我的medium以及在<a href="https://www.linkedin.com/in/harry-hao-ping-cheng-aab38a193/">Linkedin</a>上跟我聯絡！我們下回見：）</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3b77baeb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use machine learning to predict the crowd flow of Taipei Metro — Random Forest]]></title>
            <link>https://harrychengz.medium.com/use-machine-learning-to-predict-the-crowd-flow-of-taipei-metro-random-forest-e2ab195491ca?source=rss-883fba0aad4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2ab195491ca</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Harry Cheng]]></dc:creator>
            <pubDate>Sat, 10 Jul 2021 10:14:31 GMT</pubDate>
            <atom:updated>2021-07-10T12:44:12.205Z</atom:updated>
            <content:encoded><![CDATA[<h4>Supervised Regression Problem</h4><h3>Use machine learning to predict the crowd flow of Taipei Metro — Random Forest</h3><h4>Use Random Forest to predict the crowd flow of Taipei MRT on any given day/time/station in the future.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EHqtRc_NJrFmeOoUBkmBQ.jpeg" /><figcaption>Source: Internet</figcaption></figure><p>Like most of the big cities in the world, Taipei has a very well-structured metro system called the <strong>MRT</strong>. People can get around the city with ease by just taking the MRT, no scooter or car is needed.</p><p>Hypothetically, the general crowd flow of Taipei MRT would follow some specific patterns, making it an ideal time-series data for prediction. In addition, the government publishes MRT operation data as <a href="https://data.taipei/#/">Open Data</a>. Looks like it’s a sign for me to build a forecasting model with it :)</p><p>In this article, I will walk you through my entire project and all of my code can be found <a href="https://github.com/Harry-py/MRT_Prediction">here</a>. First the outline:</p><h3>Outline</h3><ol><li>Problem definition</li><li>Data preprocessing</li><li>Exploratory Data Analysis</li><li>Feature Engineering</li><li>Modeling</li><li>Next Steps</li></ol><p>Without further ado, let’s get started!</p><h3>Problem Definition</h3><p>I define the problem as “How to predict the crowd flow (Both people coming in and out) of Taipei MRT on a given day/time/station in the future?”</p><p>e.g. How many people were coming in/out of Taipei Main Station on August 2, 2021?</p><p>If this model is built successfully, it might be able to create significant business/social impact. If we look at it from the perspectives of different stakeholders:</p><ol><li><strong>Uber/Taxi company: </strong>can build a more solid dynamic pricing model.</li><li><strong>The government:</strong> can build a more efficient transportation system with bus and Ubike (Public shared bike in Taiwan) timetables.</li><li><strong>Merchants/shops around MRT:</strong> can generate better business/operation strategies based on the model results.</li></ol><h3>Data Preprocessing</h3><h4>Downloading data</h4><p>The first step is to get the raw data, which can easily be found <a href="https://data.taipei/#/">here</a>.</p><p>In my project, I only used data from 2018 and 2019 due to the disruption of COVID in 2021. Of course, we cannot rule out the possibility that similar disruptive events will happen in the future, and frankly, the MRT is constantly changing year by year, with the establishment of new stations. I will address these problems at the end of the article.</p><p>After downloading the data (One…Eternity…Later…), I read the data into Jupyter Notebook. As you can see below, the data has 170 million rows and 5 columns. Glad that my laptop survived…</p><p>The 5 columns are: [Date], [Hour], [Come in station], [Come out station], and [Crowd flow].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*pyftwgDDTV-M6oA2.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*BGuxsWGDRK9mjzbe.png" /><figcaption>What the data looks like</figcaption></figure><h4>Process data</h4><p>The first thing I do is to split the problem into “predict the people <strong>coming in</strong>” and “predict the people <strong>coming out</strong>”, and focus on “coming in” first(Dropping “coming out”). By doing so, the data will immediately shrink about 100 times without repercussions since the two aspects are identical. The same features and model should work for both “coming in” and “coming out”. My article today will only focus on the prediction of “coming in”, and the code for “coming out” can be found on my <a href="https://github.com/Harry-py/MRT_Prediction">GitHub</a> (I used the same features and model, and the result was identical).</p><p>The data after processing looks a lot lighter than before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*cA1oXtAZgU1kSwnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*IKZuOohwqoUk-yA9.png" /><figcaption>Data after preprocessing</figcaption></figure><h3>Exploratory Data Analysis</h3><p>In this part, I conduct the EDA with my own knowledge of Taipei MRT.</p><h4>Relation between [Date] and [CrowdFlow]</h4><p>Many traits can be found here. Take 2018 as an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*kXARE3MIbxvBqhm_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*TgJzXpB-nZ73CVnY.png" /></figure><ol><li><strong>Every spike is a week</strong>, with weekdays being the top of the spike and weekends being the bottom.</li><li>Different months demonstrate a different pattern — <strong>some months are busier than others</strong>.</li><li><strong>Special holidays also matters</strong>, with an example being the Chinese New Year (the lowest point in the graph).</li></ol><p>→Add new features: [DayofWeek],[Month],[Special](holiday).</p><h4>The relation between [Station] and [CrowdFlow]</h4><p>Obviously, there will be busy stations and idle ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*yU5qC4t8FeGNbN9G.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*mr8LG4b93DBlOO0P.png" /><figcaption>Chinese station names cannot be shown here</figcaption></figure><ol><li>BIG difference between busy and idle stations!</li></ol><p>→We should choose a model that won&#39;t be influenced by outliers much.</p><p>→We decide what to do with the [Station] feature after we have chosen a model</p><h4>Model Choice</h4><p>Through EDA, I believe that <strong>Random Forest</strong> is the best model for this set of data.</p><p>Random Forest is simple but calculation-heavy. It is simple because the mechanism behind it is relatively easier to understand compared to a neural network, which is often referred to as a “Black box”. However, it is calculation-heavy due to the fact that it is an ensemble model consisting of many decision trees.</p><p>If you want to understand how Random Forest works, I suggest you watch <a href="https://www.youtube.com/watch?v=7VeUPuFGJHk&amp;t=902s">this video about Decision Trees</a> and <a href="https://www.youtube.com/watch?v=J4Wdy0Wc_xQ">this video about Random Forest</a>. Nobody can put it better than Josh Starmer!</p><p>But why is Random Forest suitable for this particular dataset? Here are the reasons:</p><ol><li><strong>Random Forest is not easily swayed by outliers.</strong> The model split data into nodes and leaves, and most outliers will end up in small leaves.</li><li><strong>Random Forest handles non-linear relations well.</strong> The features in this model are not linear to crowd flow.</li><li><strong>Extrapolation is not a problem with this dataset. </strong>One weakness of Random Forest is extrapolation — it cannot handle new data that appear out of the realm of old data. This is not likely going happen to MRT data, since there will always only be 24 hours and 12 months. There could be new stations, which we will discuss later in this article.</li></ol><h3>Feature Engineering</h3><h4>Add [DayofWeek], [Month], and [Special](holiday) features.</h4><p>[DayofWeek] and [Month] are easy enough — we just have to extract it from [Date] using pandas’ datetime features. For [Special], I hardcoded the whole thing from the calendar. 0 represents holiday, 1 is normal day, and 2 is extra work day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Wv9vT_UxMeko8NJ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-a8x0dFUHKhh3D8m.png" /></figure><h4>Use [Daily Average Crowd Flow] to substitute [Station]</h4><p>After trying different ways to engineer [Station](e.g. one hot encoding), so far this is the best way to do it.</p><p>[Daily average crowd flow] is calculated by “the sum of crowd flow in training data ÷ all days in training data”. The reason why it works so well is that it can fully represent the difference in “hotness” between different stations.</p><p>Before doing so, however, I have to split the data into Training, Validating, and Testing first in chronological order, so that I don&#39;t mistakenly use data in validation or test set to engineer the feature. I didn&#39;t use the typical random Train-Test Split because the MRT data is time-series data, so validating and testing data should be in the future compare to training data.</p><p>60% of the data will be train data. (The entire 2018 and Jan., Feb. in 2019)</p><p>20% of the data will be validation data. (2019 Mar. — Jul.)</p><p>20% of the data will be test data. (2019 Aug. — the end.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MGcdz2ZMawiQNpIQ.png" /></figure><p>Next, we extract the sum of crowd flow in each station, turn it into a dictionary, and divide it by total days (440).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ODo7s216xFJZhVtt.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*oX9Gi2Ed2cu6SQVu.png" /></figure><p>Finally, convert [Station] column into [Daily Average Crowd Flow], and the data is all set!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IHAWnUtcZfVMXpju.png" /></figure><h3>Modeling</h3><h4>Training Model</h4><p>Data was all cleaned up, so I fitted it to the model. Note that the hyperparameter choice here is the result of my own tuning, but a model with only default settings can also produce great results, which is a strength of Random Forest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5xudDrMYv1r4-N-1.png" /></figure><h4>Result</h4><p>The model actually performs pretty well! Let’s use some metrics to evaluate it.</p><p><strong>R Square</strong></p><blockquote>Represents the proportion of the variance for a dependent variable that’s explained by an independent variable or variables in a regression model.</blockquote><blockquote>— investopedia</blockquote><p>According to <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.html">sklearn documentation</a>: “The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get an R² score of 0.0.”</p><p>My model produced an R Square of <strong>0.986</strong>, which means that there are very strong relations between the chosen features and crowd flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VuVb-8Wx1JDKhwBy.png" /></figure><p><strong>RMSE（Root Mean Squared Error）</strong></p><p>You can think of RMSE as <strong>the average error per prediction</strong>. Note that it is a “mean”, which means it’s sensitive to outliers. Since the MRT data has many extreme outliers, the RMSE score is likely inflated.</p><p>My model has an RMSE score of <strong>162</strong>, which seems high at first glance, but let’s compare it to the baseline.</p><p>Baseline: A model that predicts crowd flow solely base on the average crowd flow of training data. The RMSE score is <strong>1306</strong>.</p><p>Wow, huge difference! Looks like our model is actually doing something.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*myq1o70wJMLbGbJP.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dn09fPBjDS0di6MC.png" /></figure><p><strong>Evaluate 20 random predictions</strong></p><p>You can see from here that, in 20 predictions, only 2 have errors above 162. Most are below 50, or lower. RMSE is indeed inflated by outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1hv8Q9YLtcatW4yu.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/0*P_M4Pg6WtC5G4WA1.png" /></figure><p><strong>Visualization</strong></p><p>Last but not least, I picked a random time in the future (validation set) and visualized the result. As you can see, the model predictions are very accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zjQmg63RY70tgfmq.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dxqOjmqfOtY6dqNQ.png" /></figure><p>The blue line is actual data, the red dots are predicted data. If the dot is on the line, it generally means the prediction is accurate.</p><h3>Next Steps</h3><h4>The practicality of the model</h4><p>As good as the model might seem like, this is partly due to the fact that Taipei MRT didn&#39;t change much during 2018 and 2019. If we use the data in 2021, my model will be way off because it cannot predict the effect of COVID. My model will also lose effect when new stations are built.</p><p>The best way to cope with these problems is to build a dynamic model that can always take in new data and adapt to any changes. Every day, the model should take in new data and retrain. Although the model might experience short-term adaptation pain when the change just happened, with correct adjustments, the model should be able to adapt pretty quickly.</p><h4><strong>Model Optimization</strong></h4><p>Can we make the current model better? One way to do it is through hyperparameter tuning, or changing a different model. Due to hardware constraints, I didn&#39;t do large-scale tuning. But I believe the effect of tuning would be limited due to the well-performing nature of Random Forest.</p><h4><strong>Model Deployment</strong></h4><p>After all the training and tuning, it is time to find an application for this model, customize it according to commercial need, and deploy it! (Uber plz sponsor me)</p><h3>Conclusion</h3><p>Although the model looks good now, it’s still a long way from deployment. After deployment, we will still need to create business strategies to make it valuable. Many things still need to be done.</p><p>Anyways, it’s been a fun journey :) Huge thanks to all my friends who provided me with advice and the government for publishing such awesome data.</p><p>If you have any thoughts on the project, feel free to discuss them with me below!</p><p>Give me some claps and follow if you like this! You can also connect with me on <a href="https://www.linkedin.com/in/harry-hao-ping-cheng-aab38a193/">LinkedIn </a>or <a href="https://www.facebook.com/HarryHaoPingCheng">FB</a>. See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2ab195491ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[機器學習預測北捷人流--隨機森林]]></title>
            <link>https://harrychengz.medium.com/%E7%94%A8%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E9%A0%90%E6%B8%AC%E5%8C%97%E6%8D%B7%E4%BA%BA%E6%B5%81-%E9%9A%A8%E6%A9%9F%E6%A3%AE%E6%9E%97-8ab1f0c0ed8a?source=rss-883fba0aad4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ab1f0c0ed8a</guid>
            <category><![CDATA[回歸]]></category>
            <category><![CDATA[資料分析]]></category>
            <category><![CDATA[隨機森林]]></category>
            <category><![CDATA[資料科學]]></category>
            <category><![CDATA[機器學習]]></category>
            <dc:creator><![CDATA[Harry Cheng]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 11:17:35 GMT</pubDate>
            <atom:updated>2021-07-10T10:20:14.777Z</atom:updated>
            <content:encoded><![CDATA[<h4>監督式回歸問題</h4><h4>使用隨機森林預測台北捷運每天、每時、每站的人流</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EHqtRc_NJrFmeOoUBkmBQ.jpeg" /><figcaption>來源：網路圖片</figcaption></figure><p>對住在台北的人來說，捷運是生活中不可或缺的一部分。但許多人可能沒想過，自己每天刷卡進站、出站，北捷其實都有把資料存下來。利用這些資料的預測性質，我們能夠預測未來任何一個時間點的捷運人流。</p><p>利用暑假的時間，我嘗試建了一個預測模型，結果還不錯！今天我會帶大家走過整個專案的過程，並且附上我所有的<a href="https://github.com/Harry-py/MRT_Prediction">code</a>。</p><h3><strong>大綱</strong></h3><ol><li>問題定義</li><li>資料處理</li><li>探索式資料分析</li><li>特徵工程</li><li>建模</li><li>下一步的討論</li></ol><h3>問題定義</h3><p>我們把問題定義為：<strong>如何預測北捷在未來某一日/某一時/某一站的人流（進站+出站）</strong></p><p>例如：多少人在2021年8/1，16：00 進出捷運市政府站？（預測時間以整點為單位）</p><p>這個模型如果成功建出，能夠產生很大的商業/社會價值。我們以不同Stakeholders的角度來探討：</p><ol><li><strong>Uber、計程車公司：</strong>能夠定出更精準的動態定價模型</li><li><strong>台北市政府：</strong>模型能夠結合公車班表、Ubike補缺系統，打造更完善的交通服務</li><li><strong>捷運商圈商家：</strong>透過人流預測決定更好的營運、行銷策略</li></ol><h3>資料處理</h3><h4>資料下載</h4><p>第一步要做的事就是抓資料。這個步驟很方便，因為市政府的<a href="https://data.taipei/#/">台北市資料大平台</a>都有開放資料可以使用。</p><p>在這邊我只使用2018、2019兩年的資料，為了避開肺炎的影響。當然我們不能保證未來不會再次發生足以影響北捷整體營運的大事件，而且捷運營運狀況也隨時在改變（例如2020年多了環狀線），這部分模型要怎麼適應，在文章最後我會提到。</p><p>下載完了資料之後，我把資料讀進Jupyter Notebook，顯示總共有一億七千萬筆，五個欄位，電腦差點一命嗚呼…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2H-ek2P11jgNMpUApq37rQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*oIcmZP7g4iUjlq19tWYOUg.png" /><figcaption>資料長相</figcaption></figure><h4>資料處理</h4><p>我做的第一件事，是把問題拆成“進站預測”以及“出站預測”，並且先為“進站”建模。這樣可以直接減少100倍的資料，而且“進站”與“出站”其實是一體兩面，可以使用相同的資料處理步驟以及模型。今天的專案我就先以“進站”為例，“出站”的程式可以在我的<a href="https://github.com/Harry-py/MRT_Prediction">GitHub</a>找到（模型結果與進站幾乎一模一樣）。</p><p>處理完之後，也順便換了欄位名稱，清爽多了！（還是有一百六十萬筆就是了…）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzTShMBjBaGkqU-oprxKlQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*0Q8_zHruvOhWaFftSJVDZg.png" /></figure><h3>探索式資料分析</h3><p>在這部分我根據自己對於北捷的既有認識，進行EDA。</p><h4>日期與人次之間的關聯</h4><p>根據我的假設，捷運的人流會依照星期、月份、假日而有所變化。假設也透過視覺化得到驗證。以2018年為例：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPNs43BIzh4uQcYxIbmXJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnw9HI_7kymd7cXl9qLm8w.png" /><figcaption>2018年資料，橫軸為時間，縱軸為人流</figcaption></figure><ol><li>每一顆鋸齒都是一個禮拜。一到五為高峰，六日為低谷</li><li>不同月份也有人流高低起伏。11、12月偏高</li><li>特殊節日也有影響。圖中最低的離群值為除夕</li></ol><p>→製造星期、月份、特殊節日的feature</p><h4>車站與人次之間的關聯</h4><p>這應該不用特別說了，直接看圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8WTPp-gM2wj_ZctKr5iiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f06IYdm77dXeBAlBBzM4gA.png" /><figcaption>中文顯示的時候有點問題，但是可以另外印出車站名稱，不影響判斷</figcaption></figure><ol><li>熱門車站與冷門車站之間差距極度懸殊（沒錯，最高的那個就是北車）</li></ol><p>→需選擇不會被離群值影響太多的模型</p><p>→等模型決定之後再決定如何處理【Station】feature</p><h4>模型選擇</h4><p>經過EDA，我認為最適合這個資料的模型是隨機森林。</p><p>隨機森林是一個簡單粗暴的演算法。簡單是在於它的運作模式相對好懂，不像是神經網路一樣是一個黑盒子；粗暴是在於它是一個Ensemble model，也就是說它是由許多決策樹所組成的，所以計算部分會比較重一點。</p><p>如果想要瞭解隨機森林的原理，可以看這支關於<a href="https://www.youtube.com/watch?v=7VeUPuFGJHk&amp;t=902s">決策樹的影片</a>，以及這支<a href="https://www.youtube.com/watch?v=J4Wdy0Wc_xQ">隨機森林的影片</a>。我覺得沒有人可以講的比Josh Starmer更清楚了！</p><p>那為什麼隨機森林會適合這組資料呢？原因有三：</p><ol><li><strong>隨機森林不容易被離群值影響，</strong>因為離群值常會被分到一片小樹葉中，不會對其他數值的預測造成影響。Model不會因為台北車站人特別多影響對於其他數值的判斷。</li><li><strong>隨機森林可以處理非線性的關係。</strong>這組資料feature跟人潮的關係都不是線性的，像是時段跟人潮之間就不是線性關係。</li><li><strong>這組資料不會有外推（Extrapolation）的問題。</strong>隨機森林比較怕的就是新資料跳出舊資料的範圍，但是這在北捷資料裡不會發生。唯一的可能就是新車站的產生以及新節日的出現。這我們在文末還會多加討論。</li></ol><h3>特徵工程</h3><h4>新增【DayofWeek】、【Month】以及【Special】（特殊節日）</h4><p>星期跟月份很簡單，直接從【Date】裡面取出就行了。特殊節日則是直接hardcode。以2018為例，0代表放假，1代表普通日，2代表補班。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97yWQiJRElKANPjLqrJh3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r57uRUStzu-3Kegj_H1vjQ.png" /></figure><h4>用【平均車站單日人流】取代【Station】</h4><p>這是我嘗試過不同處理方法（例如One Hot Encoding）之後選出來最好的方法。</p><p>平均車站單日人流就是在所有訓練資料當中，該車站的人流加總÷所有天數。用這個數來代表車站最能夠體現各車站之間的人流差距。</p><p>在做這件事之前，我們必須要先用時間分出訓練資料（Train data）、驗證資料（Validation data）跟測驗資料（Test data），並且只用Train data做【Station】的轉換。這邊不使用一般的Train Test Split是因為使用時間先後分資料的話，我們才是真正在使用過去的資料預測未來的資料，【Station】的轉換也不會誤用到未來的資料。</p><p>6成的資料會當做訓練資料。（整個2018年以及2019的一、二月左右）</p><p>2成的資料會當做驗證資料。（2019的三月到七月左右）</p><p>2成的資料會當做測驗資料。（2019的八月到年底左右）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUe0FcSPpeypo56-MZUlrw.png" /></figure><p>接著我們把Station整年的累計人次取出，轉換成字典之後，再除上訓練資料的日數（440）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWT58p5af09tIdtK8wqTOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*HL0YDXwjGMkXuB4qM4Jt4A.png" /><figcaption>非完整的list</figcaption></figure><p>最後，把字典的資料轉換到【Station】裡面，所有的特徵工程就大功告成嘍！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYBpTp75xcTSECw0hF4YGA.png" /><figcaption>完成之後的資料長相</figcaption></figure><h3>建模</h3><h4>模型訓練</h4><p>資料都洗乾淨了，所以就直接丟到模型裡面！圖中Hyperparameter的選擇是我經過測試後的最佳選項。但其實根據隨機森林的特性，通常使用預設的Hyperparameter表現也能夠很好。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIHBB2MfpUglliUKJZkZtA.png" /></figure><h4>訓練結果</h4><p>結果整體來說非常好！</p><h4>R Square</h4><p><strong>解釋方法：人流變異能夠被 Feature解釋的程度。</strong>滿分為 1，如果 Model完全不管 input feature隨便預測的話是 0分，如果 Model表現比隨機還差的話可以是負值。</p><p>我的Model結果是0.986！我選擇的Feature跟人流之間確實有很強的的關聯性。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwfTZMjO_4bdA6fUOaqZ4g.png" /><figcaption>最下方的數字為R Square</figcaption></figure><h4><strong>RMSE（Root Mean Squared Error）</strong></h4><p><strong>解釋方法：平均每次預測的誤差。</strong>注意！這個數值很容易被離群值影響，尤其北捷資料離群值很嚴重，這個數值應該被遠遠高估。</p><p>我的Model的RMSE是162！乍看之下有點大，但我們先看看它跟Baseline的比較。</p><p>Baseline：假設我們直接使用訓練資料裡面每一筆資料的人流平均進行預測，得到的RMSE會是1306。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWTf0uT_489i0cjt9YnUFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1ZKlhyJj9CfZgM1BlMHhA.png" /></figure><h4>隨機抓20筆資料來看</h4><p>從這邊就可以看出，其實大部分誤差根本不到162，而且母數越大誤差越大。RMSE確實是被離群值拉大了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSlF45R_JSTLrHaYcXdVvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*C9SZioFtkBHpbOB-It6qPQ.png" /><figcaption>大部分預測都很到位</figcaption></figure><h4>視覺化</h4><p>最後，我們直接隨機選擇一段時間的資料畫圖看看。從這裡就可以看出，模型的表現是很好的！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wbgVpDVzt-24g4D_PFCovw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vu5w03luzA02VC8UGJ3nEg.png" /><figcaption>藍線是實際值，紅點是預測值。紅點在線上基本上就代表預測準確。</figcaption></figure><h3>下一步的討論</h3><h4>模型的實用性</h4><p>雖然看起來模型表現不錯，但是這是因為2018年到2019年並沒有發生任何會嚴重擾亂大家搭捷運的事件。2021年的疫情爆發，這個模型就會不準。2020年環狀線開始營運，模型也會不準。這時候該怎麼辦？</p><p>最好的方式還是建一個Dynamic Model。模型必須能夠每天更新最新資料並且重新訓練，跟著大趨勢的變化一起調整，才能夠隨時準確的預測。當然，還是會有時間剛開始發生的一小段陣痛期！不過長遠來看這個方法是可行的。（北捷願意付錢的話我就做hehe）</p><h4>模型優化</h4><p>這個模型還能更好嗎？或許可以從Hyperparameter的調整來試試看。因為硬體設備限制，我沒辦法進行大動作的Tuning，但是我覺得其實效果還是有限，畢竟隨機森林通常預設Hyperparameter就會表現得很好了。</p><h4>模型部署</h4><p>最後就是選擇一個適合的應用，進行客製化，並且部署模型！（Uber請贊助我）</p><h3>結語</h3><p>模型雖然表現得不錯，但是離實際部署還是有一段距離，就算部署了，要產生商業價值還是要靠策略的輔助。從一整個專案的角度來看，這模型的建立不過是冰山一角。</p><p>如果你對於這個專案有任何想法，歡迎在下方留言！</p><p>也可以透過<a href="https://www.linkedin.com/in/harry-hao-ping-cheng-aab38a193/">LinkedIn</a>、<a href="https://www.facebook.com/HarryHaoPingCheng">FB</a>跟我connect！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ab1f0c0ed8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>