<?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 Yunrui Li on Medium]]></title>
        <description><![CDATA[Stories by Yunrui Li on Medium]]></description>
        <link>https://medium.com/@yunrui-li?source=rss-5a78e6b0d45f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*joO--VxUcOo07FsAtMUNvQ@2x.jpeg</url>
            <title>Stories by Yunrui Li on Medium</title>
            <link>https://medium.com/@yunrui-li?source=rss-5a78e6b0d45f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:03:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yunrui-li/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[Leetcode-Binary Tree Traversal]]></title>
            <link>https://yunrui-li.medium.com/leetcode-binary-tree-f82f23562083?source=rss-5a78e6b0d45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f82f23562083</guid>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Yunrui Li]]></dc:creator>
            <pubDate>Sun, 17 Oct 2021 12:55:02 GMT</pubDate>
            <atom:updated>2021-10-17T13:15:59.023Z</atom:updated>
            <content:encoded><![CDATA[<p>For recursion, it’s too easy. 3 BT traversals using stack(iterative way to solve it).</p><ul><li><strong>就記得pre-order和in-order用幾乎百分之99一樣的模板, 差別是一個 root node first另外一個是left order first</strong></li><li><strong>post-order最tricky, 就記得我們最後會reverse postorder, 所以root node就直接給他放進去postorder.</strong></li></ul><p>Code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f05e0d9195883bbaee2b35c55b47ba1a/href">https://medium.com/media/f05e0d9195883bbaee2b35c55b47ba1a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f82f23562083" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode-Combination Series]]></title>
            <link>https://yunrui-li.medium.com/leetcode-combination-series-3dd7df4959c3?source=rss-5a78e6b0d45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dd7df4959c3</guid>
            <category><![CDATA[dfs]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Yunrui Li]]></dc:creator>
            <pubDate>Wed, 06 Oct 2021 12:19:57 GMT</pubDate>
            <atom:updated>2023-11-19T13:29:11.538Z</atom:updated>
            <content:encoded><![CDATA[<p>Usually, when it comes to combination problems, the most naive way to solve the problem is generate all possible solutions. And, we use depth-first-search(DFS) or called backtracking technique.</p><p>For backtracking, when we do time and space complexity analysis, they follow a certain pattern:</p><p>T: <strong>O(n**m)</strong>, n raise to power of m, where n represents at most we have n branches can search for current state and m is maximum depth of recursion tree.</p><p>Note: O(<strong>n**m) </strong>will be upper bound of time complexity<strong>. </strong>For some cases, if we generate all possible combinations or partitions , given an integer or a string, running time will be O(<strong>2**n</strong>), lower than upper bound.</p><p>S:<strong>O(m)</strong>, where m is maximum depth of recursion tree. (if we don’t consider space of storing answer)</p><ul><li>39. Combination Sum</li><li>131. Palindrome Partitioning</li><li>291. Word Pattern II</li></ul><p>Using recursion + cache for time complexity analysis typically follows the pattern:</p><ol><li>Maximum Number of States in Cache:Identify the maximum number of states your cache can hold. In the example of Word Break, which is a 1D DP problem, it can have up to n states.</li><li>Number of Paths for Each Node in Decision Tree: Determine the number of paths for each node in the decision tree. In Word Break, it’s m paths.</li><li>Operation at Each Node: the operation performed at each node. In <a href="https://leetcode.com/problems/word-break/">139. Word Break</a>, the operation is string matching, which takes O(k) operations.</li></ol><p>Taking <a href="https://leetcode.com/problems/word-break/">139. Word Break</a> as an example:</p><ul><li>Maximum number of states in cache (n).</li><li>Each node in the decision tree has m paths.</li><li>Each node performs a string matching operation, taking O(k) operations.</li></ul><p>Therefore, the total time complexity is O(n * m * k).</p><p>In other problems, if the exploration paths are constant, and each node operation is O(1), the time complexity can be simplified to O(n).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dd7df4959c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode-Basic Calculator Series]]></title>
            <link>https://yunrui-li.medium.com/leetcode-basic-calculator-series-fcfd4cf0103d?source=rss-5a78e6b0d45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcfd4cf0103d</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Yunrui Li]]></dc:creator>
            <pubDate>Fri, 10 Sep 2021 07:59:25 GMT</pubDate>
            <atom:updated>2021-09-10T07:59:25.356Z</atom:updated>
            <content:encoded><![CDATA[<p>Given 一個string expression, 我們要去計算result of expression.</p><p>有三個題型:</p><p>最基本的計算機題型</p><p>1.是string裡面只有+-(), 沒有乘除. (See LC 224)</p><p>2.再來是有+-*/但沒有() (See LC 227)</p><p>3.最難版本是+-*/和()都有(See LC 772)</p><p>Note:</p><ol><li>上面這些題型都可以假設沒有leading negative integers. For example, “-3+2” or “(-3+2)”</li><li>只要是有括號的題目, 我們都會再遇到右括號(close parentheses)的時候, 需要<strong>先計算括號內的res_in_paren</strong>再把這個<strong>res_in_paren</strong>和左括號(open parentheses)<strong>左邊的re</strong>s做合併.</li><li>這是經典的<strong>string parsing</strong> 算法題, 我們都是用<strong>stack</strong>來破題, 時間複雜度是<strong>O(n</strong>), 因為我們算法只需要掃過一遍字串,空間複雜度是O(n) 因為我們用了stack.</li></ol><p>Related Problems in LC:</p><p>224. Basic Calculator</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/216e79f498d8f7c3330083ef58c7e35b/href">https://medium.com/media/216e79f498d8f7c3330083ef58c7e35b/href</a></iframe><p>227. Basic Calculator II</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c2c4a5e3045176a03d66b802f343511/href">https://medium.com/media/3c2c4a5e3045176a03d66b802f343511/href</a></iframe><p>772. Basic Calculator III</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1a8272e5a40c1e1396a1e749b37e462/href">https://medium.com/media/a1a8272e5a40c1e1396a1e749b37e462/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcfd4cf0103d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to practice LeetCode efficiently?]]></title>
            <link>https://yunrui-li.medium.com/how-to-practice-leetcode-efficiently-df0841461afb?source=rss-5a78e6b0d45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/df0841461afb</guid>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Yunrui Li]]></dc:creator>
            <pubDate>Tue, 24 Aug 2021 05:08:51 GMT</pubDate>
            <atom:updated>2021-09-09T06:34:58.800Z</atom:updated>
            <content:encoded><![CDATA[<p>2021–2022刷題重點:</p><p><strong>一道题多做</strong></p><ul><li>多总结</li><li>做related的题目</li><li>重复做了之前做过的题目</li><li>总结是王道</li><li>另外我没有遇到原题所以刷那么多题没有用</li><li><strong>关键是做过了的就会</strong></li><li>我都是<strong>一道题刷几遍</strong>最后我面之前</li><li>我只要做过的题目我能<strong>bugfree</strong>或者只有<strong>typo</strong>的写出来</li><li>為了增加coding 速度和實際面試一樣, 有個初步想法就可以開始尻code, 在做dry run 的動作.</li></ul><p>重溫經典系列:</p><ul><li>題號前400題</li><li>刷高頻提升<strong>會考的知識點</strong>的<strong>覆蓋率(廣度)</strong></li><li>刷tag提升會<strong>考的知識點</strong>的<strong>熟練度(深度)</strong></li><li>週末做contest or mock interview, 有計時, 增加臨場感, 且也可以查漏補缺知識點.</li><li>每兩週換一個topic</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df0841461afb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML system design interview-Feed Based System]]></title>
            <link>https://yunrui-li.medium.com/ml-system-design-interview-feed-based-system-8119208c8908?source=rss-5a78e6b0d45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8119208c8908</guid>
            <category><![CDATA[machine-learning-systems]]></category>
            <dc:creator><![CDATA[Yunrui Li]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 13:06:47 GMT</pubDate>
            <atom:updated>2021-08-13T15:50:51.872Z</atom:updated>
            <content:encoded><![CDATA[<p>什麼是Feed Based Feed System?<br>經典的就是Tweeter’s Feed, Facebooks Timeline, IG’s story.</p><p><strong>Problem Statement</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g_NBX0y2gAgSskz3hBjY_g.png" /></figure><p>和一般的推薦系統相比, 除了given user的資訊, 我們多了user的social graph(一種relationship between others)! Followers and Following!</p><p><strong>Model</strong></p><p>Rule-Based:把given user的所有follower的tweet根據時間反向排序(reverse chronological order)</p><p>轉成Ranking 問題</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2pFZRA92JrmJ11BkZ6qZw.png" /></figure><p><strong>Problem Formulation</strong></p><p><em>“Given a list of tweets, train an ML model that predicts the probability of engagement of tweets and orders them based on that score”</em></p><p><strong>Problem Scale</strong></p><ol><li>每天平均有多少active users</li><li>平均一個user登入平台幾次</li></ol><p>可以推算出平均一天會有多少call to our ranking model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAMskymoD0qliG0GuoPwWw.png" /></figure><p>Metrics</p><p>基本上不管是search ranking, reccomendation system, 我們的目標都是提升user engagement, 所以我們都要先分析user actions有哪些</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlY0Ba3H0hrRGFNNEn1PLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbBXjEHhuSU1CZmqnOSgaQ.png" /></figure><p>System Architecture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbBXjEHhuSU1CZmqnOSgaQ.png" /></figure><p>注意我們的ranker model, given a tweet and user, we want to give a score of user will engage with this tweet. The higher score is, The more engagement is.</p><p>在這裏有兩種方式train model來代表ranker</p><ol><li>只train一個model</li><li>不同的action有不同的models, 最後在weighted output from all of distinct models.</li></ol><p>注意第二種方式, 我們可以彈性的根據business objective來調整model不同之間的weight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkpmxGbU2oCSrYJMlMehDg.png" /></figure><p>For feature engineering, we always think about what actors we have</p><p>使用者和author of tweet有很高相關性, 他的tweet就很容易被user點開</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8119208c8908" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML-Evaluation Metrics]]></title>
            <link>https://yunrui-li.medium.com/ml-evaluation-metrics-85b49d8193d8?source=rss-5a78e6b0d45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b49d8193d8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[evaluation-metric]]></category>
            <dc:creator><![CDATA[Yunrui Li]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 21:18:19 GMT</pubDate>
            <atom:updated>2021-08-08T21:18:32.675Z</atom:updated>
            <content:encoded><![CDATA[<p>Why do you need to be familiar with evaluation metric?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wp_MMuCF_AVd0qtaXfjBtw.png" /><figcaption><a href="https://www.1point3acres.com/bbs/thread-783674-1-1.html">https://www.1point3acres.com/bbs/thread-783674-1-1.html</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3BSOO5eqJ1RjGc30F4pYQ.png" /><figcaption>example question1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdA3OyE0pNCvc4MpX2HYKA.png" /><figcaption>example question2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2G2CmbWvY-B3uUx6aAOwQ.png" /><figcaption>example question3</figcaption></figure><p>Evaluation metrics for <strong>classification</strong>/<strong>ranking/recommendation problems</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b49d8193d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode-subarray]]></title>
            <link>https://yunrui-li.medium.com/leetcode-subarray-524cedd13024?source=rss-5a78e6b0d45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/524cedd13024</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[subarray]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Yunrui Li]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 11:38:10 GMT</pubDate>
            <atom:updated>2021-08-24T05:07:10.464Z</atom:updated>
            <content:encoded><![CDATA[<p>Some pattern about <strong>continuous subarray</strong> related problem. Usually, naive solution is generate all possible subarray, which takes O(n²) times at least. And optimal solution is the one with special data structure such as<strong> prefix sum</strong>, <strong>monotone stack</strong>, in most of cases. And, this is tricky. So, I try to summarize what I learned in this post.</p><p>Note</p><p>1.包含當前element cur, 有多少個subarray的公式?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnublixvXNc16HFWGH03rQ.png" /></figure><p>2.做subarray要注意的edge case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRq6uiJalbSwffDLIiReHQ.png" /></figure><p>Related Problems in LC</p><ul><li>907. Sum of Subarray Minimums</li><li>1856. Maximum Subarray Min-Product</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=524cedd13024" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML system design interview-Recommendation System]]></title>
            <link>https://yunrui-li.medium.com/ml-system-design-interview-recommendation-system-637df3a31eb0?source=rss-5a78e6b0d45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/637df3a31eb0</guid>
            <category><![CDATA[machine-learning-systems]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Yunrui Li]]></dc:creator>
            <pubDate>Wed, 28 Jul 2021 09:16:43 GMT</pubDate>
            <atom:updated>2021-08-26T11:52:22.638Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Problem scope:</strong></p><p>Q1:What’s the total number of subscribers on the platform?</p><p>Q2:How many daily active users?</p><p><strong>Problem Formulation</strong></p><p>Hence, you have to build a system for a large number of users who require good recommendations on a daily basis.</p><p><em>“Given a user and </em><strong><em>context (time, location, and season)</em></strong><em>, predict the probability of engagement for each movie and order movies using that score.”</em></p><p><strong>和search ranking system 最大的差別的沒有利用使用者輸入query的資訊!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilusuu0PLJUafbaixmIdbg.png" /><figcaption>problem scope</figcaption></figure><p>一個推薦系統的問體大概可以根據以下High-Level 框架想成</p><p>我們有一堆用戶信息, 物品信息, 和場景訊息(context)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pN5kcoOAX-QfSk9CaxGkZg.png" /><figcaption>抽象的推薦系統邏輯框架</figcaption></figure><p>在面試的時候, 可以基於這個框架, 對各模塊進行細化(low-level)和擴展, 匹如說如下:</p><p>跟面試官勾通想要深入討論哪些部分</p><p>針對</p><ul><li>數據和訊息相關的部分</li><li>推薦系統模型和算法相關的部分</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ewKLQkbdCT6vlLIgTQRfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VahKZNFM4CwHJWfdgyFvnA.png" /></figure><p>可以跟面試官溝通, 想要針對哪塊深入討論!</p><p><strong>Generate Training Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9DZ1aN4csTMvd7fs02Lkg.png" /></figure><p>為什麼通常選擇用implicit data 去建立recommendation system instead of explicit ?</p><ol><li>Amount of training data we can collect to build recommendation system</li><li>Explicit data 在 data collection會有MNAR(非隨機缺失的問題)</li><li>通常低分的電影人們不會較少評估, Therefore, we won’t get much information on the kind of movies that a user does not like.</li><li>Also, movies with fewer ratings would have less impact on the recommendation process.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4H_NwfR58DUNy-WhgynraQ.png" /></figure><p><strong>Metrics</strong></p><p>What online and offline metrics play in recommendation system?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ucIDgfwGYTXBobks0ZCH3g.png" /></figure><p>Driving <strong>online metrics</strong> in the right direction is the ultimate goal of the recommendation system. On the contrary, the purpose of building an <strong>offline measurement</strong> set is to be able to evaluate our new models quickly. Offline metrics should be able to tell us whether new models will improve the quality of the recommendations or not.</p><p>For online metrics:</p><ul><li>engagement rate</li><li>video/show/item watched</li><li>session watch time</li></ul><p>Engagement rate算是最簡單的metrics, 直接就是計算推薦的項目中有多少是真的比使用者點擊過! 但他有的缺點就是有些推薦項目, 即使user clicked 了但馬上關掉, 這種情況其實user沒有真的喜歡我們的推薦, 所以不能算是成功的推薦. 所以我們多了video watched</p><p>Video watched 就是多了時間的限制, 我們只考慮user觀看超過2分鐘以上的電影, 舉例來說, 算作一個成功的推薦. 但這也有一個問題, 我們很難評斷一些case就是使用只看了一個episode但卻沒有再繼續看下去完成整個season. 所以我們改成直接measure 這個電影user看多久, 這就是session watch time</p><p>session watch time就是我們去計算總共user花費在我們推薦的電影上面的時間. 這個為什麼是更好的metric來評斷一個session? 舉例來說現在有兩個使用者, user A 和 user B. user A 看了3個推薦電影但每個只看10分鐘, user B看了兩個推薦電影， 但一個看了15分鐘一個看了90分鐘, 明顯user B’s session更好</p><p>Note:</p><ol><li>一個session會有多個推薦的電影.</li><li>有關把watch time當作考慮的model, 考慮Youtube推薦系統</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wimvfMFWyPyVyTgIy4q0Mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*puYwQIhiD5f9YU25KI-EKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NH9rbHViHsZSq5Ok0-thAw.png" /></figure><p>For offline metric:</p><p>有考慮推薦序列的metric/可作為ranking metric</p><ul><li>mAP@N</li><li>mAR@N</li><li>f1-score@N</li><li>RMSE</li></ul><p>Note:</p><p>1.mAP@N, mAR@N 和 f1-score@N 的ground truth都是<strong>binary(該文章/推薦的電影相關rel=1，如果該文章/推薦的電影不相關rel=0)</strong>. 和query-based ranking system用的NDCG不同的地方在於, 不同文章的ground truth 會有不同的相關程度(匹如說, 0–5</p><p>2.RMSE for optimizing regression problem/explicit feedback</p><p>3.</p><p>Precision@N, 和AP@N, mAP@N是三個不同定義的指標.</p><p>atN 代表要除以<strong>length of recommended list(N)</strong></p><p>Average代表要除於total number of positive case in<strong> a certain user(m)</strong>!</p><p>Mean代表要除於total number of <strong>whole users</strong> in a large dataset!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VAUe2bQQYnjW4QHogQPygg.png" /><figcaption>average precision@N, P(K)=precision at K</figcaption></figure><p>補上code implementation for evaluation metric[2]</p><p><strong>Feature engineering</strong></p><p>To understand the feature engineering process, we will first identify the main <strong>actors</strong> in the movie/show recommendation(ML system ) process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jMYixzj_-2nesSQC4xIlg.png" /><figcaption>recommendation system</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBd_gDI_lRIdes0gqmniqw.png" /><figcaption>search ranking system</figcaption></figure><p>All the features we mentioned earlier can be used both in candidate generation and ranking model.</p><p><strong>Candidate Generation</strong></p><p>目標就是針對一個user在他沒看過的電影中(unseen movies/items)去評分, then我們可以根據這些評分在排序當作returned candidate的依據</p><ul><li>Collaborative Filtering(CF): 主要是使用其他使用者的偏好, 來判斷active user的偏好, 而具體有兩種方式!</li></ul><ol><li><strong>Nearest neighborhood</strong>: to select top k similar users/nearest neighbors to this user.</li><li><strong>Matrix factorization</strong></li></ol><p>For Nearest neighborhood, 通常有兩種方法<strong>user-based approach和item-based approach</strong></p><p>底下以user-based approach的formula來解釋:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*tDblZbQd1aZIHEuxJKWzEg.png" /><figcaption>user-based CF(Find nearest neighbor)</figcaption></figure><p>Similarity是用來定義user和user或是item和item之間相關性的function.</p><p>f_ij: user i’s feedback for unseen movie j</p><p>v: 從KNN挑出來的user v</p><p>Here, the feedback by the nearest neighbor is weighted by their similarity with user <em>i</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*MATHB3l2moAhE81cGJVTuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulgZlhkI6d5E-KiKTX35Sg.png" /><figcaption>pseudo code for UserCF/ItemCF[1]</figcaption></figure><p>Note:</p><ol><li>候選物品集: unseen items for given user A.</li><li>item_h: the item user A has watched before</li><li>用戶A對item_h的的評分就是/similar user 對item 的評分就是 feedback</li><li>/= similarity sum 是做 normalisation</li></ol><p>然而user-based有兩個缺點</p><ol><li>計算複雜度遠大於item</li><li>用户对物品的兴趣点比较分散和稀疏, 在找相似使用者準確率不高</li></ol><p>For matrix factorization</p><ul><li>Content-based Filtering:</li><li>Generate Embedding</li></ul><p>Core Idea of candidate generation is</p><p>To generate recommendations for user <em>i</em>, you need to predict their feedback for <strong>all the movies they haven’t watched(below empty cell instead of 0).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*Pj-_eH02lPN0ee-IHEYRLQ.png" /><figcaption>user-item matrix又稱co-occurrence matrix/共現矩陣</figcaption></figure><p>For <strong>Nearest neighborhood</strong> method, we follow below formula, where similarity can be based on user or item. (借助商品的关系或者用户的关系)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbWGX6qnfZ3jwCOSh3GWhg.png" /><figcaption>weighted average of feedback that the top k similar users gave to movie <em>j</em></figcaption></figure><p>Item-based vs User-based:</p><p>?</p><p>For <strong>matrix factorization</strong> method, As explained above, you need to represent the <em>user-media interaction matrix</em> in a way that is scalable and handles sparsity. <strong>Here, matrix factorization helps us by factoring this matrix into two lower dimensional matrices</strong>:</p><p>空間複雜度從O(m*m) or O(n*n) reduced to O((m+n)*k), where k is dimension of latent vector.</p><p>為什麼用gradient descent來分解而不是SVD?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1b7kCA4D1vxoKIjLa-6zQ.png" /></figure><p>梯度下降法是矩阵分解的主流方法</p><p>Content-based</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jsav0e3sb_Gq8DS7T4vcEA.png" /><figcaption>making tf-idf vector of each movie</figcaption></figure><ul><li>Each term is manually extracted from director, genre, and descriptive tags(text).</li><li>Each movie considered as a document.</li><li>IDF: to get a score for each term, to describe how unique this term is across whole movies. 某一個term只出現在一部電影一次, IDF很大. 某一個term出現在很多部電影, IDF很小. 所以分母是DF而分子是total number of movies(fixed)</li></ul><p>We have two options for recommending media to the user with tf-idf vector of each movie: (目標就是given a user, to find candidate from his/her unseen movie)</p><p><strong>1.Similarity with historical interactions</strong></p><p>Given a user A, 把他那些沒看過的電影跟他那些看過的電影去計算similarity,把最相似的當作candidate</p><p><strong>2.Similarity between media and user profiles</strong></p><p>Given a user A, 用他過去看過的電影去obtain user profile(in the below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vt-5S4hQ0fgAN22CnYVFA.png" /></figure><p>然後再利用這個user profile, 和那些這個user A沒看過的電影去計算similarity, 從高到低來選出candidate</p><p>Now, instead of using past watches to recommend new ones, you can just compute the similarity (dot product) between the user’s profile and media profiles of unseen movies to generate relevant candidates for user A’s recommendations.</p><p><strong>Generate using neural networks/deep learning</strong></p><p>This method is similar to generating latent vectors, that you saw in matrix factorization but is much more powerful because using NNs <strong>allows us to use all the sparse and dense features in the data </strong>to generate user and movie embedding.</p><p><strong>Training Data Generation</strong></p><p>weighting training data based on their contribution to session time.<br>權重on different training data的原理?</p><p>Train/Test Split</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GvED0uddG9-i_rltfweHUQ.png" /></figure><p>This will give you a more accurate picture of how your model will perform in a real scenario.</p><p><strong>Ranking Model:</strong></p><p>rank the content based on the probability of a user watching a media <strong>given a user and a candidate media</strong>, i.e., P(watch|(User, Media))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qb3FRLDlP_GAhvomHPDuA.png" /><figcaption>ranking model</figcaption></figure><p>Q1:怎麼存放user 和 media features?</p><p>Q2:怎麼存放user 和 media features?</p><p>Reference:</p><p>[1].<a href="https://zhuanlan.zhihu.com/p/263832671">https://zhuanlan.zhihu.com/p/263832671</a></p><p>[2].<a href="http://sdsawtelle.github.io/blog/output/mean-average-precision-MAP-for-recommender-systems.html#MAP-for-Recommender-Algorithms">http://sdsawtelle.github.io/blog/output/mean-average-precision-MAP-for-recommender-systems.html#MAP-for-Recommender-Algorithms</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=637df3a31eb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML questions]]></title>
            <link>https://yunrui-li.medium.com/ml-questions-%E4%B8%80%E5%A4%A9%E4%B8%80%E9%A1%8C-7a4a2eed19d8?source=rss-5a78e6b0d45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a4a2eed19d8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Yunrui Li]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 09:53:23 GMT</pubDate>
            <atom:updated>2021-08-14T10:22:51.749Z</atom:updated>
            <content:encoded><![CDATA[<p>This posts focus on those ML fundamentals.</p><p>There’re two steps to prepare for ML interview.</p><p>Step1: Understanding those fundamentals and theories to ensure we can answer those questions very well in the interview</p><p>Step2: To implement those code to ensure we can explain in detailed way!</p><p><strong>Q1: Could you explain dropout?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3SNruVqoOfdKb4kLfI2gAQ.png" /><figcaption>Dropout[1]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pb1Jd2DZ1jCSKztVAw-rbA.png" /><figcaption>Dropout in training mode[2]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRFz_CNCyGziML4Z8EUQMQ.png" /><figcaption>Dropout in testing mode[3] but in Pytorch, we do identify function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CVSqQ2F9YsTTqsDAqSERA.png" /><figcaption>Code snippet implemented with torch[4]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zc1eMQ5LwqtgvSRo9l2sBw.png" /><figcaption>Code snippet implemented with numpy[5]</figcaption></figure><p>Note:</p><ol><li>Dropout is applied on output of previous layer, which will be multiply with bias and wight to get input of current layer. Then, it will pass into activation function to get output of current layer. 簡言之, dropout is applied before activation.</li><li>Dropout在訓練和測試的時候表現不一樣, 在training時, dropout可以達到regularization的作用(讓weights 有shrink的作用) so that we prevent from overfitting。在testing時，我們需要更穩定的結果，在implementation的時候不會使用丟棄法, 因為如果隨機zero out一些neurons，这会带来结果不稳定的问题，也就是给定一个测试数据，有时候输出a有时候输出b，结果不稳定，这是实际系统不能接受的，用户可能认为模型预测不准。那么一种”补偿“的方案就是每个神经元的权重都乘以一个p，这样在“总体上”使得测<strong>试数据和训练数据是大致一样的</strong>。</li><li>Dropout probability is a hyper-parameter needed to be tune.</li><li>During testing, the module simply computes an identify function. 指的就是什麼input進來, 原封不動出去, 等效於乘以identity matrix. 所以在training的時候才要對值做放大(rescale), 這樣理論上, 丢弃法不改变其输入的期望值。</li><li>Given dropout probability p, 我們來計算輸出的期望值:<br>(1-p)x + p0 = (1-p)x<br>解釋: 有1-p的機率被保留參與訓練輸出是x, 有p的機率被丟棄, 輸出是0. 最後, 這個layer輸出的期望值是(1-p)x. 那我們只要把輸入在training時除以(1-p)做個縮放, 在testing時, 不做任何事, 只輸出x. 則等效於在訓練和測試的時候輸出的期望值都是相同, 維持一樣x, 符合我們希望<strong>试数据和训练数据是大致一樣的需求.</strong></li></ol><p>[1].<a href="https://www.jianshu.com/p/15ce88117075">https://www.jianshu.com/p/15ce88117075</a></p><p>[2].<a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.388.797&amp;rep=rep1&amp;type=pdf">http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.388.797&amp;rep=rep1&amp;type=pdf</a></p><p>[3].<a href="https://zhuanlan.zhihu.com/p/38200980">https://zhuanlan.zhihu.com/p/38200980</a></p><p>[4].<a href="https://colab.research.google.com/notebooks/intro.ipynb?utm_source=scs-index#scrollTo=2LEv1Cgu_O0g">https://colab.research.google.com/notebooks/intro.ipynb?utm_source=scs-index#scrollTo=2LEv1Cgu_O0g</a></p><p><strong>Q2: Could you explain k-nearest neighbor (k-NN)</strong></p><p><strong>Q3: Could you explain ROC curve?</strong></p><p><strong>Q4: Could you explain bagging? [5]</strong></p><p><strong>Bagging</strong>, shortened for <strong>b</strong>ootstrap <strong>agg</strong>regat<strong>ing</strong>, is designed to improve the stability and accuracy of ML algorithms. <strong>It reduces variance and helps to avoid overfitting.</strong></p><p>Given a dataset, instead of training one classifier on the entire dataset, you sample <strong>with</strong> replacement to create different datasets, called bootstraps, and train a classification or regression model on each of these bootstraps. <strong>Sampling with replacement ensures each bootstrap is independent of its peers.</strong></p><p>If the problem is classification, the final prediction is decided by the majority vote of all models. For example, if 10 classifiers vote SPAM and 6 models vote NOT SPAM, the final prediction is SPAM.</p><p>If the problem is regression, the final prediction is the average of all models’ predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFBGWteBoG-nEUoEC-KXQg.png" /></figure><p>A <strong>random forest</strong> is an example of bagging. A random forest is a collection of decision trees constructed by both <strong>bagging</strong> and <strong>feature randomness</strong>, each tree can pick only from a random subset of features to use.</p><p>Due to its ensembling nature, random forests correct for decision trees’ overfitting to their training set.</p><p><strong>Q5: Could you explain boosting? [5]</strong></p><p>Boosting is a family of iterative ensemble algorithms that convert weak learners to strong ones. <strong>Each learner in this ensemble is trained on the same set of samples but the samples are weighted differently among iterations.</strong> Thus, future weak learners focus more on the examples that previous weak learners misclassified.</p><ol><li>You start by training the first weak classifier on the original dataset.</li><li>Samples are reweighted based on how well the first classifier classifies them, e.g. misclassified samples are given higher weight.</li><li>Train the second classifier on this reweighted dataset. Your ensemble now consists of the first and the second classifiers.</li><li>Samples are weighted based on how well the ensemble classifies them.</li><li>Train the third classifier on this reweighted dataset. Add the third classifier to the ensemble.</li><li>Repeat for as many iterations as needed.</li><li>Form the final strong classifier as a weighted combination of the existing classifiers — classifiers with smaller training errors have higher weights.</li></ol><p>Adaboost and XgBoost is famous example of boosting framwork.</p><p>GBDT与XGBoost的区别和联系？其中一个重要的回答就是：GBDT在模型训练时只使用了代价函数的一阶导数信息，XGBoost对代价函数进行二阶泰勒展开，可以同时使用一阶和二阶导数。</p><p>為什麼我們給錯誤分類的samples比較高的weight?</p><p>1.根據Adaboost的定義Error是<strong>那些錯誤分類的samples的總和</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLB5Jlo2-xNlEk7l0Mqq5g.png" /></figure><p>這樣定義的原因是在下一輪的classifier會嘗試去把error降低.</p><p>2. 實際implement, 我們藉由改變loss function來做re-weighting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8iy6xt93xuSvHELZBMjfQ.png" /><figcaption>怎麼讓ML算法對不同weight的training data感受不一樣, 就是改變loss function: 權重高的data, 錯誤會有比較高的loss. 用這樣的方式, 那ML alg就會去學習讓這些錯誤的data正確使整體的loss下降</figcaption></figure><p><strong>Q5: Why ensembling method could improve the stability and accuracy of ML ML algorithm ? [6]</strong></p><p>如果我們把ensembling裡面每個基模型產生的誤差/error想成一個隨機變數 X:</p><p>有關隨機變數複習, 參考CS229講義[7][8]</p><p>對於隨機變數 X, 我們通常關注期望值和標準差</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCriaoaZZGnja8VNEZgYSw.png" /><figcaption>一個隨機變數會有n個可能發生的值x, 每個值會有相對應發生的機率p</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkA4T_cMGVquEosQ0HZPLw.png" /><figcaption>變異數是x-m平方的期望值</figcaption></figure><p>如果兩個隨機變數是獨立的, 兩個隨機變數的join probability distribution(聯合機率分配)等於兩個個別隨機變數的marginal probability distribution(邊際機率分配)相乘. 反之相關, 我們就計算兩者之間的covariance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cB10XM24gzlwPiSJMYZcA.png" /><figcaption>兩個隨機變數要馬獨立要馬相關</figcaption></figure><p>Independently and Identically distribution(I.I.D)</p><p>從bias and variance角度來思考:</p><p>现在如果我们设想每个<strong>随机变量(x)</strong>都是一个给定模型的<strong>误差</strong>，就可以看到用到的模型的数目在增长(导致第二项消失)，另外模型间的相关性在降低(使得第一项消失并且得到一个独立同分布的定义)，最终导致了集成方法误差的方差的总体降低。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fV09D_ZapvF1niHOlgNvuQ.png" /><figcaption>誤差的variance/方差(假設彼此誤差之間是相依的, 符合真實情況), 設tho =0則等於下面式子</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*SyBKzT9O1nDrWeWRkFovAA.png" /><figcaption>誤差的variance/方差(假設彼此誤差之間是獨立的)</figcaption></figure><p>使用模型的偏差(bias)和方差(variance)来描述其在训练集上的准确度和防止过拟合的能力</p><p>抽样的随机性带来了模型的随机性。</p><p>在bagging和boosting框架中，通过计算基模型誤差X的期望和方差，我们可以得到模型整体的期望和方差。</p><p>For boosting,</p><ol><li>decreasing bias of your base model</li><li>more additive</li></ol><p>每一次迭代都根据上一次迭代的预测结果对样本进行加权，所以随着迭代不断进行，误差会越来越小，所以模型的 bias 会不断降低。但因為這次模型和上一次模型相依性較高, 會略微增加variance.</p><p><strong>Q5: What are some of the fundamental differences between bagging and boosting algorithms?</strong></p><p>從三個角度看差別:</p><ol><li>Training data怎麼取得(how to generate training data)</li></ol><p>Ensemble 用某一種方式產生不同的training data來訓練base learner, 使彼此之間很不一樣.</p><p>bagging 是 <strong>re-sampling</strong>, 而boosting是 <strong>re-weighting</strong>.</p><ol><li>ensemble中的分類器匹此之間的關西</li><li>ensemble中的分類器怎麼取得(how to train)</li><li>ensemble中的base learner/weak learner 特性</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1FToKFSqLKqe4OY3Ve--w.png" /><figcaption>difference between bagging and boosting[4]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ON0eHNmzOScX-aBRjGHLkg.png" /></figure><p>Bagging用的base learner是low bias, high variance(偏差高方差小).</p><p>Boosting用的base learner是high bias, low variance(偏差低方差高).</p><p>舉例來說:</p><p>Randmom Forest用的base learner 是decision tree是很複雜model, 所以base learning在bagging是overfitting, 是low bias, high variance(unstable).</p><p>Adaboost 用的base learner 是decision dump是很簡單model, 只是一條線的分類器, 所以base learning在boosting是underfitting, 是high bias, low variance(stable).</p><p><strong>Q6: What is Adaboost ?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZI4Y80_ylnHW9DdV_AIzg.png" /></figure><p>weight:每一筆training example都有一個weight. 初始值大家都一樣1/N, where N = total number of training data</p><p>weighted error: 就是把error rate根據不同weight 做normalization. error rate分子是所有training data中有多少是分錯的.</p><p>alpha: performance of each classifier, calculated by 加权误差(weighted error)的负对数概率(negative log-odds)。</p><p>re-weight rule( it’s associated with how to re-weight training data based on previous weak learner)</p><p>參考下圖了解為什麼re-weight rule 是長weight * exponential of negative y_hat * h*alpha</p><p>基本上,</p><p>錯誤分類的example 我們乘上一個值dt, 使其原本權重增加</p><p>正確分類的example 我們除上一個值dt, 使其原本權重減少</p><p>這個dt經過推到就是和alpha有關.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nJxu4sytjHKQJxYRuFc1Q.png" /><figcaption><a href="https://www.youtube.com/watch?v=tH9FH1DH5n0&amp;t=2558s&amp;ab_channel=Hung-yiLee">https://www.youtube.com/watch?v=tH9FH1DH5n0&amp;t=2558s&amp;ab_channel=Hung-yiLee</a></figcaption></figure><p>model output: additive modeling, weighted by alpha. and take sign function (因為這是binary classification為例所以take sign function, 把它轉成{-1,1})</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzsYvUQngXrl2PIHNtfYaA.png" /><figcaption>alpha</figcaption></figure><p>sign function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*GJ75K20oNR9X4_n5fqCTcQ.png" /><figcaption>取正負號的函數</figcaption></figure><p>其實AdaBoost就是在等效於在訓練時, 最小化指數損失函數(exponential loss)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BP9CjXTlgnUB49K43Bsjow.png" /><figcaption>為什麼AdaBoost可以理論保證當T夠大時可以得到近似於0的training error.( 因為他一直連乘一個介於0~1的值)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*ck1ibWOOIv5lVDz-FBrruA.png" /><figcaption><a href="https://zhuanlan.zhihu.com/p/58883095">https://zhuanlan.zhihu.com/p/58883095</a></figcaption></figure><p><strong>Q7:</strong> <strong>What is gradient boosting?</strong></p><p>Gradient Boosting produces a prediction model typically from weak decision trees. It builds the model in a <strong>stage-wise fashion</strong> as other boosting methods do, and it generalizes them by allowing optimization of an arbitrary differentiable loss function.</p><p>The way he optimized is use <strong>gradient descent</strong>!</p><p>So, gradient boosting is also called forward stage-wise additive modeling.</p><p>最後的模型, 就是經過T次迭代後的函數.</p><p>Gradient Boosting的核心思想借鉴于梯度下降法，其基本原理是根据<strong>当前模型损失函数的负梯度信息来训练新加入的弱分类器(weak learner)</strong>，然后将训练好的弱分类器以累加的形式结合到现有模型中。采用决策树作为弱分类器的Gradient Boosting算法被称为GBDT。[9]</p><p>In gradient boosting, each weak learner is fit to the negative gradient of a loss function with respect to y_hat/previous model output.</p><p>而為什麼這樣是一種boosting的框架呢?<br>负梯度也被称为“响应 (response)”或“伪残差 (pseudo residual)”，从名字可以看出是一个与残差接近的概念。<strong>直觉上来看/Intuitively</strong>，残差r=y−f(x)越大，表明前一轮学习器f(x)的结果与真实值y相差较大，那么下<strong>一轮学习器通过拟合残差或负梯度</strong>，就能纠正之前的学习器犯错较大的地方。</p><p>在實務上, 我們把找learning rate給固定以簡化, 而不是去找一個最好的learning rate使得loss越小越好.</p><p>與Taylor’s series相比較, 我們可以觀察發現<br><strong> 我們透過建立一個weak classifier to fit negative gradients!!(模擬Taylor’s expansion), 下方的式子就是exactly same as gradient descent. </strong>For XgBoost, they use second order information to get more precise approximation result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mq35PyHa0bWhlV9hObYQmw.png" /><figcaption>pseudo code of gradient boosting framework</figcaption></figure><p><strong>為什麼gradient在gradient boosting frameworks中又被稱作pseudo residuals?</strong></p><p><strong>Hence for a general loss function, gradient boosting requires that we fit the gradients at each step, and for mean squared loss, the gradient just happens to be the residuals</strong> so whilst is seems somewhat intuitive it is also slightly misleading to think of gradient boosting as fitting residuals (or even pseudo residuals as the gradients are often named), it is actually gradient descent in function space [11].</p><p>Gradient Descent vs Gradient boosting</p><p>Gradient Descent是透過對</p><p><strong>Q4:Could you explain GBDT?</strong></p><p>We take decision stump, decision tree with one layer, as weak learner of gradient boosting.</p><p>3steps:</p><ol><li>Have a base model to output prediction y_hat</li><li>Compute residual error</li><li>Sequentially construct DT but with same features but different label( we take previous residual error as label)</li></ol><p>Why take residual error as label or each weak learner?</p><p>Gradient Boosting中则将负梯度作为上一轮基学习器犯错的衡量指标，在下一轮学习中通过拟合负梯度来纠正上一轮犯的错误。这里的关键问题是：<strong>为什么通过拟合负梯度就能纠正上一轮的错误了？</strong></p><p>簡言之，梯度提升算法(gradient boosting) 是一种梯度下降(gradient descent)算法，只需要更改损失函数(loss function)和計算梯度就能将其推广。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycYSP5pOFtlZc1qRQoKPVg.png" /><figcaption>pseudo algorithm of gradient boosting decision tree[1]</figcaption></figure><p>Step1: 我們要找到model的初始值, 這個初始值如何決定, 就是透過我們要最小化我們所定義的loss function, 這個loss function是一個 label和y_hat的函數. 要找到一個函數的最小值, 就是找到一階導數的微分(first order derivative with respect to model output為零的點.<br>Note:</p><ol><li>gamma is nothing but predicted value(y_hat)(<strong>model的輸出就是y_hat就是predicted value</strong>)</li><li>在GBDT的frame work中, 優點是loss function彈性, 讓我們可以解決各種ML task 像是classification, regression and ranking. 也就是說loss function 可以是許多不同的（可微分）Loss Function such as MSE[3]. 在機器學習中, loss function也可以指objective function.</li><li>first order derivative with respect to y_hat= gradient</li><li>residuals basically is gradient/ first order derivative with respect to function(x), where function(x) = y_hat = predicted_value. So, residuals經過數學推導我們發現就是gradient. 所以我們可以用減法就可以很簡單計算gradient.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ifn_eMeOUWFyS5I290KGSg.png" /><figcaption>step1: initialize model with constant value(y_hat=60)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32XW9Zg_Z17wcEWZZL3Mzg.png" /><figcaption>step2: compute pseudo residuals</figcaption></figure><p>Note:<br>r11: residual that example1 caused by model 1 (we’ll created M models)<br>r21: residual that example2 caused by model 1<br>r31: residual that example3 caused by model 1</p><p>step3中的f下標m-1(xi)就是output of previous model(which is fixed value already, 60 in the below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*BH4Zu1mR6kcDD6eIPzALqQ.png" /><figcaption>what step3 looks like when take square loss as our loss function</figcaption></figure><p>3rd part:</p><p>4.3[M] What problems is gradient boosting good for?</p><p><strong>Q8.Why do gradient descent work in theory</strong>?</p><p>從Taylor’s series推導過來:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUYLIPvZ2WJiRbi_Q1_yUA.png" /></figure><p>我們把loss對附近一小步做Taylor’s expansion去尋找怎樣的一小步, 我們可以使得下一步loss會最小, 其中近似這一小步要無限小(Theoretically) 我們才可以忽略<strong>高次項</strong>, 而只考慮<strong>first order derivative</strong>. 而這一步的方向, 從下面推導發現他就是當前梯度的反方向</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zH12hJ6PidFzY2L-9F8V0g.png" /></figure><p>Q9:Could you explain linear regression</p><p>For regression problem, Mean Square loss/ Mean Square Error (均方誤差)是我們常用的objective function. 而基于均方誤差最小化来进行模型求解的方法称 为&quot;最小二乘法&quot; (least square method).</p><p>簡單的線性回歸, 是可以透過一次微分的0的方程式, 求出最優解(close-formed) function</p><p>What are the basic assumptions to be made for linear regression?</p><p>Question Reference:</p><p><a href="https://huyenchip.com/ml-interviews-book/contents/8.1.2-questions.html">https://huyenchip.com/ml-interviews-book/contents/8.1.2-questions.html</a><br>Question list:</p><p><a href="https://huyenchip.com/ml-interviews-book/contents/8.1.2-questions.html">8.1.2 Questions</a></p><p>Reference:</p><p>[1].Reference:<a href="https://www.youtube.com/watch?v=Nol1hVtLOSg&amp;t=391s&amp;ab_channel=KrishNaik">https://www.youtube.com/watch?v=Nol1hVtLOSg&amp;t=391s&amp;ab_channel=KrishNaik</a><br>[2].<a href="https://www.cnblogs.com/shiyublog/p/10992609.html">https://www.cnblogs.com/shiyublog/p/10992609.html</a><br>[3].<a href="https://www.cnblogs.com/shiyublog/p/10992609.html">https://www.cnblogs.com/shiyublog/p/10992609.html</a></p><p>[4].<a href="https://chih-sheng-huang821.medium.com/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-ensemble-learning%E4%B9%8Bbagging-boosting%E5%92%8Cadaboost-af031229ebc3">https://chih-sheng-huang821.medium.com/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-ensemble-learning%E4%B9%8Bbagging-boosting%E5%92%8Cadaboost-af031229ebc3</a></p><p>[5].<a href="https://huyenchip.com/ml-interviews-book/contents/8.1.1-overview:-basic-algorithm.html">https://huyenchip.com/ml-interviews-book/contents/8.1.1-overview:-basic-algorithm.html</a></p><p>[6].<a href="https://www.zhihu.com/question/29036379">https://www.zhihu.com/question/29036379</a></p><p>[7].<a href="https://stanford.edu/~shervine/l/zh-tw/teaching/cs-229/refresher-probabilities-statistics">https://stanford.edu/~shervine/l/zh-tw/teaching/cs-229/refresher-probabilities-statistics</a></p><p>[8].<a href="http://math1.ck.tp.edu.tw/%E6%9E%97%E4%BF%A1%E5%AE%89/%E5%AD%B8%E8%A1%93%E7%A0%94%E7%A9%B6/%E4%B8%8A%E8%AA%B2%E8%AC%9B%E7%BE%A9/99%E8%AA%B2%E7%B6%B1/%E6%95%B8%E7%94%B2%E4%B8%8A/1-1%E9%9A%A8%E6%A9%9F%E7%9A%84%E6%84%8F%E7%BE%A9.pdf">http://math1.ck.tp.edu.tw/%E6%9E%97%E4%BF%A1%E5%AE%89/%E5%AD%B8%E8%A1%93%E7%A0%94%E7%A9%B6/%E4%B8%8A%E8%AA%B2%E8%AC%9B%E7%BE%A9/99%E8%AA%B2%E7%B6%B1/%E6%95%B8%E7%94%B2%E4%B8%8A/1-1%E9%9A%A8%E6%A9%9F%E7%9A%84%E6%84%8F%E7%BE%A9.pdf</a></p><p>[9].<a href="https://mp.weixin.qq.com/s?__biz=MzI5NDMzMjY1MA==&amp;mid=2247485110&amp;idx=1&amp;sn=86bcdb38f51fc5f82236b35c349ada4b&amp;scene=21#wecha%E2%80%A6">https://mp.weixin.qq.com/s?__biz=MzI5NDMzMjY1MA==&amp;mid=2247485110&amp;idx=1&amp;sn=86bcdb38f51fc5f82236b35c349ada4b&amp;scene=21#wecha%E2%80%A6</a></p><p>[10]. Hung-yi Lee上課整理筆記, <a href="https://sakura-gh.github.io/ML-notes/">https://sakura-gh.github.io/ML-notes/</a></p><p>[11]. <a href="https://datascience.stackexchange.com/questions/31609/why-do-we-use-gradients-instead-of-residuals-in-gradient-boosting">https://datascience.stackexchange.com/questions/31609/why-do-we-use-gradients-instead-of-residuals-in-gradient-boosting</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a4a2eed19d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode-Data Stream]]></title>
            <link>https://yunrui-li.medium.com/leetcode-data-stream-a5b43c7cebc5?source=rss-5a78e6b0d45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5b43c7cebc5</guid>
            <dc:creator><![CDATA[Yunrui Li]]></dc:creator>
            <pubDate>Thu, 15 Jul 2021 18:34:09 GMT</pubDate>
            <atom:updated>2021-08-08T11:32:53.421Z</atom:updated>
            <content:encoded><![CDATA[<p>What is data stream?</p><p>It’s constant stream of data. For example, twitter messages and online news article.</p><p>Usually, for data stream related problem, there’s <strong>add function</strong> which will keep adding data <strong>from data stream into data structure you choose</strong> once it’s called. So, initially, we need a good data structure as a container to store past data stream.</p><p><a href="https://en.wikipedia.org/wiki/Data_stream">Data stream - Wikipedia</a></p><p>Basically, for problem that we need to <strong>maintain a sorted unique array</strong>, we come up below workarounds:</p><ol><li><strong>Sorting</strong> as brute force solution: Take <strong>O(nlogn)</strong> once you called add function, which is very efficient.</li><li><strong>Binary Search + insertion</strong>: Take <strong>O(logn)+O(n)=O(n), linear time </strong>once you called add function, which is better.</li><li>Think about <strong>heap</strong> as optimal solution: Take <strong>O(log n)</strong> once you called add function, which is optimal solution.</li><li>For <strong>monotone stack </strong>solution: Take amortized <strong>O(1)</strong> (see LC 901 online stock span)</li><li>For <strong>unique sorted array</strong>, we just need one more data structure called <strong>hashmap/hashset</strong> to help, for seen num, we ignore.</li></ol><p>Note:</p><ol><li>follow-up(進階) or 我們已知input data會在一定range分佈, 舉例來說input data will be in range of [0,100], 可以想到maintain <strong>count array</strong>數據結構, 通常可以得到<strong>O(100) running time and space complexity, constant time.</strong></li><li>Prefix sum + Binary Search, 建立prefix sum array 從count array takes O(n) time.</li><li>count array data structure: array count where count[k] is the <strong>number of times</strong> that k appears in the data stream.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUFPOG9UL54Sztz5RDrO1Q.png" /><figcaption>[1]</figcaption></figure><p>Related problems in LC:</p><ul><li><strong>703. Kth Largest Element in a Stream</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eb326c8748a1a11e9b7cbe9252e32e6/href">https://medium.com/media/5eb326c8748a1a11e9b7cbe9252e32e6/href</a></iframe><ul><li><strong>295. Find Median from Data Stream</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9a866fc7175d823307df11e5a9fef64/href">https://medium.com/media/c9a866fc7175d823307df11e5a9fef64/href</a></iframe><ul><li><strong>346. Moving Average from Data Stream</strong></li><li><strong>901. Online Stock Span</strong></li><li><strong>352. Data Stream as Disjoint Intervals</strong></li></ul><p>Problem Reference:</p><p><a href="https://leetcode.com/tag/data-stream/">https://leetcode.com/tag/data-stream/</a><br>[1].<a href="https://leetcode-cn.com/problems/find-median-from-data-stream/solution/java-cong-tou-shi-xian-dui-heap-by-docke-fxi9/">https://leetcode-cn.com/problems/find-median-from-data-stream/solution/java-cong-tou-shi-xian-dui-heap-by-docke-fxi9/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5b43c7cebc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>