<?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 Chung-Yi on Medium]]></title>
        <description><![CDATA[Stories by Chung-Yi on Medium]]></description>
        <link>https://medium.com/@ncku70230213?source=rss-cd31e136a9d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7pmBgle2UFrE5mAQTc8uzA.jpeg</url>
            <title>Stories by Chung-Yi on Medium</title>
            <link>https://medium.com/@ncku70230213?source=rss-cd31e136a9d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:37:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ncku70230213/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[Build OpenCV GPU Version On Windows 10]]></title>
            <link>https://medium.com/chung-yi/build-opencv-gpu-version-on-windows-10-c37a33437525?source=rss-cd31e136a9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c37a33437525</guid>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Chung-Yi]]></dc:creator>
            <pubDate>Fri, 07 May 2021 08:09:56 GMT</pubDate>
            <atom:updated>2021-05-28T03:00:28.413Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>由於嘗試使用OpenCV dnn modules實作Object Detection時，發現使用pip install opencv-python的opencv只有cpu版本，如果想要使用gpu功能必須自己編譯。</blockquote><h3><strong>Step1</strong></h3><p>安裝Visual Studio Code <a href="https://visualstudio.microsoft.com/zh-hant/downloads/">https://visualstudio.microsoft.com/zh-hant/downloads/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*JWQinazqAlLoC8gz.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ybp6hS5_VJfSQL0G.png" /></figure><h3>Step2</h3><p>安裝CMake，之後做編譯時，可以選擇使用有GUI或是直接在terminal下指令，兩個都有嘗試過，個人比較偏好使用GUI。</p><h3>Step3</h3><p>下載CUDA及cuDNN</p><ul><li>CUDA <a href="https://developer.nvidia.com/cuda-downloads">https://developer.nvidia.com/cuda-downloads</a></li><li>cuDNN <a href="https://developer.nvidia.com/cudnn-download-survey">https://developer.nvidia.com/cudnn-download-survey</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f3Bq1fpnMNo-mQnG.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RY6CHoo27TJwXJyX.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PnV7k6zQvIdE4EyU.png" /></figure><h3>Step4</h3><p>將opencv及opencv_contrib下載到你的資料夾。</p><ul><li>opencv <a href="https://github.com/opencv/opencv">https://github.com/opencv/opencv</a></li><li>opencv_contrib <a href="https://github.com/opencv/opencv_contrib">https://github.com/opencv/opencv_contrib.git</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*VhQTPoTdtqMTfhqA.png" /></figure><h3>Step5</h3><p>打開Cmake進行編譯(如果要使用terminal，記得要把Cmake(C:\Program Files\CMake\bin)，這是我自己電腦的路徑)加到環境變數。</p><p>進行編譯之前，先在opencv底下建立一個build資料夾，這是最後的output資料夾(你也可以選擇放在別的地方)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*Q7J_hAb6TRZahLNW.png" /></figure><p>打開Cmake後，首先先選擇你剛剛下載的opencv，然後再選剛剛新增的build資料夾，然後點擊左下角的configure，並選擇x64，點finish，然後進行Configure。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wK4WlpyHA_500wpa.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xKZ90v8BtYbnB89U.png" /></figure><p>結束後會產生如下的圖片，</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aORaT9-EHps2LeG6.png" /></figure><p>然後WITH_CUDA，OPENCV_DNN_CUDA，ENABLE_FAST_MATH這幾項要打勾。PYTHON_EXECUTABLE及PYTHON3_LIBRARY必須選擇你所建的anaconda environment(因為除了base，你可能有其他的environment)，OPENCV_EXTRA_MODULES_PATH必須指定剛剛下載的opencv_contrib/modules(因為pip install opencv-python裡面的modules都是使用CPU，如果要使用OpenCV dnn modules並且使用到GPU，必須要自己build，因為有CUDA功能的在opencv_contrib/modules)，然後再重新Configure一次，</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ngMjcw7PylpG4wjv.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u7TgqCWEezSJqz6q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PXqzALqqhTPaSQdW.png" /></figure><p>完成後你會看到如下圖的結果，然後把CUDA_ARCH_BIN其他版本號的都刪掉，留下與你cuDNN相符的，然後Configure，Generate，如下圖所示。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f0elRt64AybR_erV.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oorPeZfTpF7xXqpS.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y2TC9wg4mIRcSsQR.png" /></figure><p>接下來點旁邊的Open Project，進入到Visual Studio Code，將Debug模式改成Release，然後再ALL_BUILD點右鍵，再點建置，接下來就慢慢等吧(時間有點久)。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bx1lOeYO-6GbEBvi.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JaFNG6e6NEmksZoq.png" /></figure><p>接下來在INSTALL按右鍵-&gt;僅限專案-&gt;建置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZQ40nyj6ivWPLbY4.png" /></figure><p>完成後應該會在你一開始所見的build資料夾看到裡面一堆東西，重點就是在build裡面的install資料夾，必須將build\install\x64\vc16\bin加入環境變數(E:\opencv\build\install\x64\vc16\bin)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/0*O97ileDXuYs-AO7t.png" /></figure><h3>Step6</h3><p>測試你的environment OpenCV是不是有GPU版本，可以使用下面程式碼測試，如果count=1代表有GPU，0就是沒有。如果你編譯都沒有錯誤，但是測試的時候卻沒有GPU，可能原因有下列幾個，這也是我自己遇到的問題。</p><ol><li>你可能編譯時設定的python envirenment與測試程式碼的environment不一樣</li><li>你可能沒把E:\opencv\build\install\x64\vc16\bin加入環境變數</li></ol><pre>import cv2<br>count = cv2.cuda.getCudaEnabledDeviceCount()<br>print(count)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/0*g47GwxlWoEth8Thl.png" /></figure><h3>結論</h3><p>我自己在測試的時候，如果建置完成後，把包含build的opencv放在C槽底下(C:opencv…)，即使不用設定環境變數也還是吃的到GPU，我覺得應該是當import cv2時，會主動到C槽找opencv底下的\opencv\build\install\x64\vc16\bin裡的modules，所以如果不想在額外加入環境變數，這個路徑名稱就不要亂改啦。</p><p>在windows環境底下編譯真的會遇到很多問題，或是遇到即使編譯完，opencv還是吃不到GPU，繞了非常遠最後才成功，所以做個紀錄以免之後忘記。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c37a33437525" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chung-yi/build-opencv-gpu-version-on-windows-10-c37a33437525">Build OpenCV GPU Version On Windows 10</a> was originally published in <a href="https://medium.com/chung-yi">程式設計之旅</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Python Data Model]]></title>
            <link>https://medium.com/chung-yi/the-python-data-model-74e0ccb1e033?source=rss-cd31e136a9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/74e0ccb1e033</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chung-Yi]]></dc:creator>
            <pubDate>Sat, 30 Nov 2019 15:45:15 GMT</pubDate>
            <atom:updated>2020-04-04T15:46:12.088Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>介紹</blockquote><p>這個章節主要介紹python中的一些magic methods，顧名思義就是擁有魔法一樣，不需要去重新定義或架構一個方法，直接使用即可。例如，假如有一個a = [1, 2, 3]，想知道它的長度，可以直接使用len(a)=3，這是因為type(a)是list，list這個物件的class裡面已經有定義 __len__這個function，所以只要使用len()就直接呼叫__len__這個function。這些magic method的命名方式都是用__x__。</p><p>若想知道某個class有哪些magic methods，可以這個程式碼查看，例如想知道int class的magic methods</p><pre>dir(int)</pre><p>可以得到下面的magic methods</p><pre>[&#39;__abs__&#39;, &#39;__add__&#39;, &#39;__and__&#39;, &#39;__bool__&#39;, &#39;__ceil__&#39;, &#39;__class__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__divmod__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__float__&#39;, &#39;__floor__&#39;, &#39;__floordiv__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__index__&#39;, &#39;__init__&#39;, &#39;__init_subclass__&#39;, &#39;__int__&#39;, &#39;__invert__&#39;, &#39;__le__&#39;, &#39;__lshift__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__neg__&#39;, &#39;__new__&#39;, &#39;__or__&#39;, &#39;__pos__&#39;, &#39;__pow__&#39;, &#39;__radd__&#39;, &#39;__rand__&#39;, &#39;__rdivmod__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rfloordiv__&#39;, &#39;__rlshift__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__ror__&#39;, &#39;__round__&#39;, &#39;__rpow__&#39;, &#39;__rrshift__&#39;, &#39;__rshift__&#39;, &#39;__rsub__&#39;, &#39;__rtruediv__&#39;, &#39;__rxor__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__sub__&#39;, &#39;__subclasshook__&#39;, &#39;__truediv__&#39;, &#39;__trunc__&#39;, &#39;__xor__&#39;, &#39;bit_length&#39;, &#39;conjugate&#39;, &#39;denominator&#39;, &#39;from_bytes&#39;, &#39;imag&#39;, &#39;numerator&#39;, &#39;real&#39;, &#39;to_bytes&#39;]</pre><p>關於magic methods介紹可以參考：<a href="https://www.tutorialsteacher.com/python/magic-methods-in-python">https://www.tutorialsteacher.com/python/magic-methods-in-python</a></p><blockquote>建立一個 class A Pythonic Card Deck</blockquote><p>以下是以撲克牌為例子：</p><pre>class FrenchDeck:</pre><pre>    ranks = [str(n) for n in range(2, 11)] + list(</pre><pre>    &#39;JQKA&#39;)]  # [&#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;, &#39;10&#39;, &#39;J&#39;,     <br>             &#39;Q&#39;, &#39;K&#39;, &#39;A&#39;]</pre><pre>    suits = &#39;spades diamonds clubs hearts&#39;.split()  # [&#39;spades&#39;,    <br>                                    &#39;diamonds&#39;, &#39;clubs&#39;, &#39;hearts&#39;]</pre><pre>    def __init__(self):<br>        self._cards = [Card(rank, suit) for suit in self.suits for   <br>                      rank in self.ranks]</pre><pre>    <br>    def __len__(self):<br>        return len(self._cards)</pre><pre>    def __getitem__(self, position):<br>        return self._cards[position]</pre><p>接下來使用collections.namedtuple來定義一個class，collections.namedtuple的好處是可以為class命名，增加可讀性</p><pre>import collections</pre><pre>Card = collections.namedtuple(&#39;Card&#39;, [&#39;rank&#39;, &#39;suit&#39;])</pre><pre>print(Card)</pre><p>可以得到：</p><p>Card(rank=’7&#39;, suit=’diamonds’)</p><p>接下來實體化FrenchDeck()，透過len(deck)可以得到撲克牌的所有花色及大小</p><pre>deck = FrenchDeck()</pre><pre>print(len(deck))</pre><p>長度為52</p><p>這邊可以使用len()是因為在class FrenchDeck有定義__len__，若是將__len__拿掉會得到：</p><pre>TypeError: object of type &#39;FrenchDeck&#39; has no len()</pre><p>若是使用 index查看deck裡的element:</p><pre>print(deck[0])</pre><p>可以得到Card(rank=’2&#39;, suit=’spades’)，這也是因為class FrenchDeck有定義__getitem__</p><p>Card(rank=’2&#39;, suit=’spades’)</p><pre>deck[:3]</pre><p>[Card(rank=’2&#39;, suit=’spades’), Card(rank=’3&#39;, suit=’spades’), Card(rank=’4&#39;, suit=’spades’)]</p><pre>for card in deck:<br>    print(card)</pre><p>Card(rank=’A’, suit=’hearts’) Card(rank=’K’, suit=’hearts’) Card(rank=’Q’, suit=’hearts’)</p><p><strong>所以說當有一個字串’123’或是一個[1, 2, 3]可以使用len()或是index就是因為class string, class list有__len__及__getitem_，可以用dir(str), dir(list)查看。</strong></p><blockquote>How Special Methods Are Used</blockquote><p>這些magic methods都有一個共通點，就是它是透過Python interpreter主動呼叫，而不是透過使用者自己呼叫，所以上面的例子我們只需要使用len()，而不需要deck.__len__()。但是其實我們在寫程式時，不太需要去直接去呼叫這些特殊的方法，有一個例外的方法就是__init__()，相信對於class有一點概念的大概都會知道，使用__init__()目的是為了做初始化的動作，可以看上面的class FrenchDeck，當實體化一個物件時，它會呼叫__init__()。</p><p>盡量避免隨意定義特殊方法，其實命名特殊發法也是一門學問，在這邊就不做介紹，詳細內容可以參考：<a href="https://aji.tw/python%E4%BD%A0%E5%88%B0%E5%BA%95%E6%98%AF%E5%9C%A8__%E5%BA%95%E7%B7%9A__%E4%BB%80%E9%BA%BC%E5%95%A6/">https://aji.tw/python%E4%BD%A0%E5%88%B0%E5%BA%95%E6%98%AF%E5%9C%A8__%E5%BA%95%E7%B7%9A__%E4%BB%80%E9%BA%BC%E5%95%A6/</a></p><blockquote>Emulating Numeric Types</blockquote><p>首先定義一個class Vector</p><pre>class Vector:</pre><pre>    def __init__(self, x=0, y=0):</pre><pre>        self.x = x</pre><pre>        self.y = y<br></pre><pre>    def __repr__(self):<br>        return &#39;Vector(%r, %r)&#39; % (self.x, self.y)</pre><pre>    def __abs__(self):<br>        return hypot(self.x, self.y)<br></pre><pre>    def __bool__(self):<br>        return bool(abs(self))</pre><pre>    def __add__(self, other):</pre><pre>        x = self.x + other.x</pre><pre>        y = self.y + other.y</pre><pre>        return Vector(x, y)</pre><pre>    def __mul__(self, scalar):</pre><pre>        return Vector(self.x * scalar, self.y * scalar)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lw80R7j8rC91TdeocHx8iw.png" /><figcaption>Figure 1–1. Example of two-dimensional vector addition; Vector(2, 4) + Vector(2, 1) re‐ sults in Vector(4, 5)</figcaption></figure><pre>v = Vector(3, 4)</pre><p>Vector(3, 4)</p><pre>abs(v)</pre><p>5.0，這邊可以跟前面相呼應，直接使用abs() Python interpreter就會去呼叫__abs__()這個special method</p><pre>v1 = Vector(2, 4)</pre><p>Vector(2, 4)</p><pre>v2 = Vector(2, 1)</pre><p>Vector(2, 1)</p><pre>v3 = v1 + v2</pre><p>Vector(4, 5)</p><blockquote>Overview of Special Methods</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9itY7WulYALw38HEURjwmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQ4YIuvGLmMqTiuQHzpmpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhO8HHQXzOJ7CDEKthEgPQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74e0ccb1e033" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chung-yi/the-python-data-model-74e0ccb1e033">The Python Data Model</a> was originally published in <a href="https://medium.com/chung-yi">程式設計之旅</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML入門（二十二）Ridge Regression]]></title>
            <link>https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E4%BA%8C%E5%8D%81%E4%BA%8C-ridge-regression-f638e1887a7e?source=rss-cd31e136a9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f638e1887a7e</guid>
            <category><![CDATA[ridge-regression]]></category>
            <category><![CDATA[maching-learning]]></category>
            <dc:creator><![CDATA[Chung-Yi]]></dc:creator>
            <pubDate>Sat, 05 Oct 2019 07:31:01 GMT</pubDate>
            <atom:updated>2019-10-05T07:34:10.883Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>簡單回顧</blockquote><p>之前在介紹 Gradient Descent 及 <a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E4%BA%94-regularization-solving-overfitting-9d000e3dd561">ML入門（十五）Regularization(Solving overfitting)</a>都有提到，在做最佳化的時候， 會對目標函數加入一些限制條件。舉個例子好了，最近朋友推薦看一部動漫，相信大家也都很熟才對，<strong>鬼滅之刃，主角炭治郎在接受訓練時，一直拼命練習為了能夠變得更強，但是幫他訓練的柱，還是會要求他休息養傷，終究是人類還是得休息。這就是限制條件，在最佳化的問題時，必須要有所限制。</strong></p><p>由下面這張圖可以看到，紅色典是training data，綠色點是testing data。很明顯地紅色的線完整的 f 擬合training data，但是testing data所造成的誤差很大，有high variance及overfitting的情況。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*Y-aAfMHGqtU9qK_9Vszm3w.png" /></figure><p>Ridge Regression就是產生一條新的線(藍色線)，不要那麼完整地擬合taining data。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*Cc1Svv3BcxqJLJNMzoNaUA.png" /></figure><p>之前的章節有提到一個model的好壞必須要有一個目標函數來衡量它，也就是loss function，這邊是MSE(mean square error)為例子，以下圖紅色線來說，它的MSE為0，藍色線MSE &gt; 0。現在加入懲罰項(是不是有點熟悉的感覺)，重新計算兩條線的error，可以發現藍色線是比較小的，所以藍色的線條雖然減少對training data擬合的程度，但是能夠提高對testing data 擬合的程度。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*NVuEoMVJfZlH3Y2pqGkOCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*E_0iIXP0N_9nf1cbi9Dfew.png" /></figure><p>講到這邊應該很熟悉吧!!之前在討論Regularization也有提到，只是那個時候沒有給它特別的名字，所以如果對ridge regression不熟的可以再對照之前所講的，可能才會更加了解。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f638e1887a7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E4%BA%8C%E5%8D%81%E4%BA%8C-ridge-regression-f638e1887a7e">ML入門（二十二）Ridge Regression</a> was originally published in <a href="https://medium.com/chung-yi">程式設計之旅</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML入門（二十一）KNN與K-Means差異]]></title>
            <link>https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E4%BA%8C%E5%8D%81%E4%B8%80-knn%E8%88%87k-means%E5%B7%AE%E7%95%B0-7dc6ad0227fc?source=rss-cd31e136a9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dc6ad0227fc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[knn]]></category>
            <dc:creator><![CDATA[Chung-Yi]]></dc:creator>
            <pubDate>Wed, 02 Oct 2019 10:23:25 GMT</pubDate>
            <atom:updated>2019-10-02T10:23:25.643Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>簡單回顧</strong></blockquote><p>關於兩者更詳細的介紹可以參考<a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E5%85%AB-k-means-f92b9f1e8871">ML入門（十八）K-Means</a>及<a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E4%B9%9D-knn-%E6%87%B6%E6%83%B0%E5%AD%B8%E7%BF%92-a21263fac504">ML入門（十九）KNN（懶惰學習）</a>，這邊做一下整理，歸納出兩者的差異性，不然光看兩個名字都有個K，不知道什麼時候該用哪一個。</p><blockquote><strong>KNN</strong></blockquote><ul><li>分類</li><li>監督式學習</li><li>不需要學習（不去學習一個判別式函數(損失函數)而是要記住整個訓練集）</li><li>在範圍內與旁邊的鄰居進行比較，並以這幾個鄰居（訓練樣本）中出現最多的分類標籤作為最終新樣本數據的預測標籤</li></ul><blockquote><strong>K-Means</strong></blockquote><ul><li>分群</li><li>非監督式學習（沒有label的資料）</li><li>需要訓練</li><li>比較主觀作分類，由人決定k值，目測要分成幾類</li></ul><blockquote><strong>相同及相異的地方</strong></blockquote><ul><li>相同：都是透過一個中心的點，由旁邊的點再去做分析（並不完全相同）</li><li>相異：兩種算法之間的最大區別是，K-means本質上是無監督學習，而KNN是監督學習；K-means是聚類算法，KNN是分類（或回歸）算法。K-means算法把一個數據集分割成cluster，每個cluster裡的點相互靠近，必須一直計算改變 cluster centroid，就好像班上的核心人物一直在改變。KNN算法嘗試基於其k（可以是任何數目）個周圍鄰居來對未標記的觀察進行分類。它也被稱為懶惰學習法，因為它涉及最小的模型訓練。所以k對整個模型非常重要。</li></ul><p>下面兩張圖是K-Means的過程</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hQrERswwutkVOFhHVZqs2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qLMAY-QDl4OSsSpAxZPgiw.png" /></figure><p>下面這張圖是KNN的過程</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*2S4-xzWxjpQbNNPvNrWd1Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dc6ad0227fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E4%BA%8C%E5%8D%81%E4%B8%80-knn%E8%88%87k-means%E5%B7%AE%E7%95%B0-7dc6ad0227fc">ML入門（二十一）KNN與K-Means差異</a> was originally published in <a href="https://medium.com/chung-yi">程式設計之旅</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML入門（二十）PCA降維]]></title>
            <link>https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E4%BA%8C%E5%8D%81-pca%E9%99%8D%E7%B6%AD-9ad3a09782ad?source=rss-cd31e136a9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ad3a09782ad</guid>
            <category><![CDATA[apc]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Chung-Yi]]></dc:creator>
            <pubDate>Tue, 01 Oct 2019 17:15:18 GMT</pubDate>
            <atom:updated>2021-12-03T04:19:08.188Z</atom:updated>
            <content:encoded><![CDATA[<p>降維顧名思義為把高維度降到低維度，也可以把它想成是壓縮數據。降維是機器學習中的一個重要課題，有時候數據太大會造成運算時間過久，佔用內存，所以把數據做降維後有助於我們儲存及分析。那目前最常用的方法就是PCA(principle components analysis)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-7lOVNVCSv8o9R3Dga6bA.png" /></figure><blockquote><strong>降維的平面</strong></blockquote><p>PCA的基本假設是將高維度的資料投影到較低維度的平面（如果原始資料是2D，降維之後會在一條直線上，以下都會以2D平面做介紹）</p><p>如下圖所示，假設我們有一組資料，我們希望找到一個向量可以投影（紅色的線），這條線的選擇依據就是原始資料投影至新的線的距離，又稱為投影誤差（projection error）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmEXVFjETv50vHQ3GUUOmg.png" /></figure><p>以下這張圖我分別用2D及3D來做解釋，以左邊的圖來說，要從二維降到一維，也就是找到一條直線能夠最小化projection error；以右邊的圖來說，要從三維降到二維，也就是找到一個直平面能夠最小化projection error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZRBxHIZl_TwCQvBLJr1AQ.png" /></figure><blockquote><strong>PCA不等於linear regression</strong></blockquote><p>從下面這張圖，你看得出來哪一個是PCA哪一個是linear regression嗎？仔細一看兩個其實是有差異的。左邊是linear regression，我們要找一條線能夠fit所有資料，也就是最小化每個資料與直線平方誤差，就是圖中藍色的線；右邊是PCA，我們要找的是一條投影的向量，讓所有資料的投影誤差最小。而兩者最大的差異在於linear regression要透過input x來預測y，但是PCA料中每一筆資料根本就沒有所需要被預測的y。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-t0TXaFB6NUOtP59uaQSg.png" /></figure><blockquote><strong>PCA步驟</strong></blockquote><p>吳恩達機器學習沒有特別講到找轉換後向量的數學推倒，所以這邊稍微整理一下PCA的整個概念，簡單來說PCA著重在高維度的資料，最大化<strong>變異數</strong>並投影至較低維度的平面。這個轉換後的平面是由正交軸（互相垂直）所組成，也就是說在正交的情況下最大化<strong>變異數。</strong></p><p>假設今天將資料從n維降到k維，必須先計算covariance matrix(共變異數矩陣或 協方差矩陣，這裡有更詳細介紹協方差矩陣 <a href="https://kknews.cc/zh-tw/code/rbrbrko.html">https://kknews.cc/zh-tw/code/rbrbrko.html</a>)。在了解 covariance matrix 之前，我們先了解 單變量的投影後的變異數的計算方式:</p><p>PCA假設資料 μ等於0(每個變數的平均數是0)，這樣可以方便之後做簡化且對投影至新的平面軸的方向不影響，可以看成平移至0的地方。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*xEBBMzeIDgwew_HXPecfRw.png" /></figure><p>通常情況屬於多變量，所以會寫成矩陣的方式:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*LcRtp4TknpyPXqswNf5wDg.png" /></figure><p>C就是covariance matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*f0x7Ypyn_8jj0WaSGIpGQA.png" /></figure><p>所以PCA 就是讓投影向量讓投影後的資料變異量最大，從covariance matrix得到的特徵向量就是變異數最大的方向，就是新的軸(更詳細的數學推導可以參考 <a href="https://medium.com/@chih.sheng.huang821/%E6%A9%9F%E5%99%A8-%E7%B5%B1%E8%A8%88%E5%AD%B8%E7%BF%92-%E4%B8%BB%E6%88%90%E5%88%86%E5%88%86%E6%9E%90-principle-component-analysis-pca-58229cd26e71">機器/統計學習:主成分分析(Principal Component Analysis, PCA)</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*rgegPpdwz9fz5lYCOOS0gw.png" /></figure><ol><li>對數據做標準化，使數據在相同區間較好比較</li><li>建立covariance matrix</li><li>分解covariance matrix為特徵向量及特徵值</li><li>選擇值最大的k個特徵值對應的特徵向量</li><li>利用k特徵向量建立投影矩陣</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ad3a09782ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E4%BA%8C%E5%8D%81-pca%E9%99%8D%E7%B6%AD-9ad3a09782ad">ML入門（二十）PCA降維</a> was originally published in <a href="https://medium.com/chung-yi">程式設計之旅</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML入門（十九）KNN（懶惰學習）]]></title>
            <link>https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E4%B9%9D-knn-%E6%87%B6%E6%83%B0%E5%AD%B8%E7%BF%92-a21263fac504?source=rss-cd31e136a9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21263fac504</guid>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Chung-Yi]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 16:27:10 GMT</pubDate>
            <atom:updated>2020-01-04T17:58:23.602Z</atom:updated>
            <content:encoded><![CDATA[<p>為什麼說KNN是懶惰學習的分類算法？之所以稱“懶惰”並不是由於此類算法看起來很簡單，而是在訓練模型過程中這類算法並不去學習一個判別式函數(損失函數)而是要記住整個訓練集，這樣解釋可能沒有很懂，那就看看下面那張圖吧！</p><p>對於預測新的數據，在範圍內與旁邊的鄰居進行比較，並以這幾個鄰居（訓練樣本）中出現最多的分類標籤作為最終新樣本數據的預測標籤。就好像國小國中常常會搞小團體，某天新來的同學突然被要求選邊站，不想以後在班上被欺負，當然選擇人多的那一邊嘛！！</p><p>或是更簡單一點，用一句話就可以形容KNN的原理，其概念與<strong>「近朱者赤，近墨者黑」</strong>相同，就是周圍的資料決定其分類。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*CE4oExiHRo0hBiFS3WSDqA.png" /></figure><blockquote><strong>步驟</strong></blockquote><ol><li>決定k值及距離度量。</li><li>針對新的資料，找到訓練集中和它最近的k個樣本。</li><li>以多數決的方式進行投票來決定類別。</li></ol><blockquote><strong>如何選定k值</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qYb5x3ij3svaLieWTTWkA.png" /></figure><ol><li>如果選擇較小的k值，k = 1，會造成離新的資料最近的類別是什麼他就是什麼類別，最容易overfitting</li><li>如果k = N(訓練資料)，預測結果都是屬於在訓練資料中最多的類別</li><li>如果k是偶數，則有可能碰到無法直接決定類別，例如k=4，結果在i附近的點有2個type A的資料與 2個type B的資料<br>導致無法判斷結果</li></ol><blockquote><strong>參考文獻</strong></blockquote><p><a href="https://medium.com/@NorthBei/machine-learning-knn%E5%88%86%E9%A1%9E%E6%BC%94%E7%AE%97%E6%B3%95-b3e9b5aea8df">[Machine Learning] kNN分類演算法</a></p><p><a href="https://www.slideshare.net/ssuserf88631/knn-51511604">沒有想像中簡單的簡單分類器 Kn</a>n</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21263fac504" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E4%B9%9D-knn-%E6%87%B6%E6%83%B0%E5%AD%B8%E7%BF%92-a21263fac504">ML入門（十九）KNN（懶惰學習）</a> was originally published in <a href="https://medium.com/chung-yi">程式設計之旅</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML入門（十八）K-Means]]></title>
            <link>https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E5%85%AB-k-means-f92b9f1e8871?source=rss-cd31e136a9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f92b9f1e8871</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[k-means]]></category>
            <dc:creator><![CDATA[Chung-Yi]]></dc:creator>
            <pubDate>Sun, 29 Sep 2019 15:23:33 GMT</pubDate>
            <atom:updated>2019-09-29T15:23:33.819Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>什麼是非監督式學習</strong></blockquote><p>之前我們所介紹的幾種分類方法都監督式學習，而非監督式學習演算法只基於 輸入資料找出模式，無法正確找出結果。K-Means就是透過這個概念將資料做分群，顧名思義就是將資料分成一群一群。常被用在客戶分群、特徵抽象化、非結構化資料分析…。</p><p>下面這張圖可以明顯看出左邊是監督式學習，右邊是非監督式學習。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQiqsZGuXmV17uT-jFor4A.png" /></figure><p>如果還聽不懂沒關係，下面我會舉一個簡單的例子，這個例子是我看到某位大大他在介紹K-Means時所舉的例子（<a href="https://medium.com/@chih.sheng.huang821/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E9%9B%86%E7%BE%A4%E5%88%86%E6%9E%90-k-means-clustering-e608a7fe1b43">機器學習: 集群分析 K-means Clustering</a>）：</p><p>K-means Clustering這個方法概念很簡單，一個概念「物以類聚」。男生就是男生，女生就是女生，男生會自己聚成一群，女生也會自己聚成一群。</p><p>但在這群男生自己不會動成一群，女生也不會動成一群，在機器學習內，我們有的就是一組不會動的身高和體重的資料。那是什麼會動，讓男生女生可以區隔開的是什麼? 回頭看看演算法的名字，k-means，這邊的k是你想分成幾群，means就是每一群群心（ cluster centroid），所以會動的東西就是群心。這邊很懸，什麼是會動的群心??????</p><p>如果用實際的例子說，大家到新學校上學的時候有沒有一種感覺，第一天到的時候基本上大家都不熟，一個兩個人是一群，後來慢慢會有一群人聚在一起，沒幾天就分成兩群、三群，慢慢的到上學後一個月，基本上班上的小團體都分好了，每個團體都有一個key-man，你可以把這個key-man當作是群心，基本上大家都是因為有這個key-man聚在一起的(如果變節又是另一件事情)。那這個key-man在開學到小團體分好之前，基本上有可能會一直換來換去的，甚至多出一個key-man或是少一個key-man(演算法:ISODATA)，或是這個團體的key-man會因為別人的強勢而換掉，這就是<strong>會動=換掉</strong>的群心。</p><blockquote><strong>K-Means運作</strong></blockquote><p>假如手上擁有沒有label的資料，我們想將它分成兩類：</p><ol><li>決定把資料分成k群</li><li>在二維平面上隨機選取 2 個點，稱爲 cluster centroid</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IV9w_IlhpwGrJxdNWo-cjg.png" /></figure><p>3. 對每個資料都計算與這兩個cluster centroid的距離（歐基李德距離Euclidean distance），取比較近的距離，並把它歸為該群(cluster assignment)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zt7cp1tcyEgMuWUnMTdXMg.png" /></figure><p>4. 接著重新計算cluster centroid的位置（因為每次都會有被分類過來的資料）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDjXKC7VqIx8-Jaf5V9mAw.png" /></figure><p>5. 一直重複3、4，直到所有群cluster centroid沒有太大的變動才結束。</p><blockquote><strong>K-Means Algorithm</strong></blockquote><p>這裡的式子可以搭配上面幾張圖看。首先針對每個資料求與μ(cluster centroid)的距離，來找出每筆資料屬於哪個分群</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOwU3-w59GUukvYBY3vS8Q.png" /></figure><p>之前再介紹其他方法時都有目標函數來判斷最佳值，就是loss function，這邊也可以透過目標函數distortion function來判斷：</p><p>其實這個式子跟上面第一個for loop一模一樣，所以其實在做分群時計算每一個資料屬於哪一個群時，就是在取目標函數的最小值。第二個for loop是更新μ的值，就是把同群的放在一起，其實這樣做就可以把目標函數變小。所以這兩個for loop就是在對目標函數做最佳化。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*cSYjHTyeoFr-brkVSOVy6A.png" /></figure><blockquote><strong>Random Initialization</strong></blockquote><p>初始所選定的μ的不同，會導致得到不同 clustering 的結果， 可能導致 local optima，⽽非 global optima。</p><p>所以比較好的做法是，Random Initialization的次數要多一點，找出目標函數最小時的μ來當作一開始所選定的cluster centroid</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6h7rWiXygIgt86f3IHPeyw.png" /></figure><blockquote><strong>K-Means實作</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f25d35b72083ed6c0e09e5cd7daf422d/href">https://medium.com/media/f25d35b72083ed6c0e09e5cd7daf422d/href</a></iframe><p>下面這張圖，藍色點是隨機產生的資料，橘色點是cluster centroid（經過多次計算找出最合適的）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*x_LzFrv9IKZ1HsJ3zWrcfw.png" /></figure><p>計算出每個點與cluster centroid的距離，並用不同顏色將其歸類。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Qif4UzUui8ZQRu3HSkY2TA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f92b9f1e8871" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E5%85%AB-k-means-f92b9f1e8871">ML入門（十八）K-Means</a> was originally published in <a href="https://medium.com/chung-yi">程式設計之旅</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML入門（十七）隨機森林(Random Forest)]]></title>
            <link>https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E4%B8%83-%E9%9A%A8%E6%A9%9F%E6%A3%AE%E6%9E%97-random-forest-6afc24871857?source=rss-cd31e136a9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6afc24871857</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[boosting]]></category>
            <dc:creator><![CDATA[Chung-Yi]]></dc:creator>
            <pubDate>Sat, 28 Sep 2019 11:22:49 GMT</pubDate>
            <atom:updated>2019-09-29T15:11:55.012Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>介紹</strong></blockquote><p>Random Forest的基本原理是，結合多顆CART樹（CART樹為使用GINI算法的決策樹），並加入隨機分配的訓練資料，以大幅增進最終的運算結果。顧名思義就是由許多不同的決策樹所組成的一個學習器，其想法就是結合多個「弱學習器」來建構一個更強的模型：「強學習器」。這種方法又稱為Ensemble Method，也就是「三個臭皮匠勝過一個諸葛亮」的概念。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*iWHiPjPv0yj3RKaw0pJ7hA.png" /></figure><p>不過我們只有一個數據集，所以要形成多顆具差異性的樹以進行Ensemble Method，就是要產生不同的數據集，才能產生多顆具差異性的CART樹，其作法有兩種方式：</p><ol><li>Bagging(Bootstrap Aggregation):</li></ol><p>Bootstrap指的是「重新取樣原有Data產生新的Data，取樣的過程是均勻且可以重複取樣的」，使用Bootstrap我們就可以從一組Data中生出多組Dataset。</p><p>此種方法會從Training dataset中取出K個樣本，再從這K個樣本訓練出K個分類器（在此為tree）。每次取出的K個樣本皆會再放回母體，因此這個K個樣本之間會有部份資料重複，不過由於每顆樹的樣本還是不同，因此訓練出的分類器（樹）之間是具有差異性的，而每個分類器的權重一致最後用投票方式(Majority vote)得到最終結果。</p><p>2. Boosting:</p><p>與Bagging類似，但更強調對錯誤部份加強學習以提升整體的效率。是透過將舊分類器的錯誤資料權重提高，加重對錯誤部分的練習，訓練出新的分類器，這樣新的分類器就會學習到錯誤分類資料(misclassified data)的特性，進而提升分類結果。就好像在學校考試時，面臨大型考試前都會加強比較弱的部分或是把之前考試時錯誤的題目再多練習幾次。</p><p>所以大概可以猜想得出來：</p><p><strong>Random Forest = Bagging + Decision Tree</strong></p><blockquote><strong>步驟</strong></blockquote><ol><li>定義大小為n的隨機樣本（這裡指的是用bagging方法），就是從資料集中隨機選取n個資料，取完後放回。</li><li>從選取的n個資料中，訓練出決策樹。對每一個節點：<br>a. 隨機選取d個特徵<br>b. 使用特徵分割該節點（信息增益，information gain，不熟的話可以去看<a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E5%85%AD-%E6%B1%BA%E7%AD%96%E6%A8%B9-decision-tree-59e5fb6a0f56">ML入門（十六）決策樹(Decision Tree)</a>，有介紹什麼是信息增益）</li><li>重複k次步驟1~步驟2</li><li>匯總所有決策樹的預測，以<strong>多數決</strong>的方式，來決定分類結果。</li></ol><blockquote>鳶尾花數據實作</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd5f1337e0e476350f98b320577e1671/href">https://medium.com/media/cd5f1337e0e476350f98b320577e1671/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*2e5_86G_2QZuR3yBTkuJ6g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6afc24871857" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E4%B8%83-%E9%9A%A8%E6%A9%9F%E6%A3%AE%E6%9E%97-random-forest-6afc24871857">ML入門（十七）隨機森林(Random Forest)</a> was originally published in <a href="https://medium.com/chung-yi">程式設計之旅</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML入門（十六）決策樹(Decision Tree)]]></title>
            <link>https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E5%85%AD-%E6%B1%BA%E7%AD%96%E6%A8%B9-decision-tree-59e5fb6a0f56?source=rss-cd31e136a9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/59e5fb6a0f56</guid>
            <category><![CDATA[maching-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Chung-Yi]]></dc:creator>
            <pubDate>Fri, 27 Sep 2019 13:03:06 GMT</pubDate>
            <atom:updated>2019-09-27T14:56:54.266Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>介紹</strong></blockquote><p>之前我們在做二元分類的時候有介紹幾種模型，perceptron，linear classification。這邊我們要介紹另一種更好懂得模型，<strong>決策樹(Decision Tree)</strong>，顧名思義就是詢問一些問題來分割數據。這個模型有多好懂呢?看了下面的圖片你大概就懂了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*wRKXWGksx8eIXE1CKtjQ9g.jpeg" /></figure><blockquote><strong>如何做分類</strong></blockquote><p>決策樹是透過training data的fearture(例如上圖的Eat pizza, Exercise)，學出一系列的問題，然後來推斷其分類。</p><p>一開始會先從根節點(父節點)開始，然後依據各個feature將資料作分割到左右兩邊。為了能在節點上，使用最具意義的特徵來做分割，需要透過<strong>信息增益(information gain)</strong>來判斷。簡單來說， 信息增益大的話那麼這個特徵對於分類來說很重要，很關鍵的一切，就能把數據分得很乾淨， 決策樹就是這樣來找特徵的。</p><p>所以在決策樹算法的學習過程中，信息增益是特徵選擇的一個重要指標，它定義為<strong>一個特徵能夠為分類系統帶來多少信息，帶來的信息越多，說明該特徵越重要，相應的信息增益也就越大</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*dRbx86Q5NkzSccD4y_4d1A.png" /></figure><p>上面的式子，f代表節點用來作分割的feature，Dp、Dj分別代表父節點及第j個子節點的資料，Np、Nj分別代表父節點及第j個子節點的資料數量。這裡有一個比較重要的參數，I代表不純度(impurity measure)，可以把它想成是分類完整的程度，從式子可以看得出來，如果子節點的I總和越小，代表分割越乾淨，所以信息增益(IG)也就越大。</p><p>其中最常見的不純度有三種:</p><ul><li>Gini 不純度(Gini impurity): p(i|t)代表在某個節點t，屬於類別c的比例。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*qcpXByaUeYD9iu5oTUoLCw.png" /></figure><ul><li>熵(entropy): 不確定性的多少，假如在做二元分類時，如果p(i=1|t) = 1或p(i=0|t) = 0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*psSRZnpIOTz-XeLxlnCG_Q.png" /></figure><ul><li>分類錯誤率(classification error):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*Ulto35vnsM9BmuTBUAbqvQ.png" /></figure><p>下面是以上面提到的三種不同不純度，對A、B做分析(可以代入上面的公式推導)：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*0n745n-Bxg2aH58DwIXQoA.png" /></figure><ol><li>Gini 不純度(Gini impurity):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*PMy8uqvzRLj4cZLvjAFiKw.png" /></figure><p>2. 熵(entropy):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*XBJr0mpH1BWsgySR4HttaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*jxR2oJ3QfYKf7JdFkv3EOg.png" /></figure><p>3. 分類錯誤率(classification error):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*Bi4bDJvW89HX6Is4r19ZqA.png" /></figure><blockquote><strong>鳶尾花數據實作</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c2d3fc6434c620d7e61d25c034340e6/href">https://medium.com/media/2c2d3fc6434c620d7e61d25c034340e6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*ViV2UGYFOS--MVwumYoOYw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59e5fb6a0f56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E5%85%AD-%E6%B1%BA%E7%AD%96%E6%A8%B9-decision-tree-59e5fb6a0f56">ML入門（十六）決策樹(Decision Tree)</a> was originally published in <a href="https://medium.com/chung-yi">程式設計之旅</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML入門（十五）Regularization(Solving overfitting)]]></title>
            <link>https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E4%BA%94-regularization-solving-overfitting-9d000e3dd561?source=rss-cd31e136a9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d000e3dd561</guid>
            <category><![CDATA[maching-learning]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[regularization]]></category>
            <dc:creator><![CDATA[Chung-Yi]]></dc:creator>
            <pubDate>Thu, 26 Sep 2019 10:49:13 GMT</pubDate>
            <atom:updated>2019-09-26T10:52:48.293Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>簡單回顧</strong></blockquote><p>介紹regularization之前，必須要了解什麼是overfitting。在之前的章節或多或少都有提到overfitting這號人物，那他為什麼那麼常被提到呢？如果你有訓練過模型，相信對它並不陌生。在訓練的時候，經常會出現overfitting的情況，regularization就是用來解決它的方法。</p><blockquote><strong>Overfitting</strong></blockquote><p>最右邊那張圖就是overfitting的狀況，顧名思義就是過度學習，對於訓練資料可以完美的做分類，但是如果有一筆新的資料可能會被分錯。</p><p>舉一個簡單的例子，平時上課不認真學生在拼指考時，不懂得舉一反三，就算只是一直寫考古題，也只能把寫過的考題答對，但如果有新的題型出現，可能就會考得很差。</p><p>如果訓練資料的features太多，就會造成訓練的hypothesis過於複雜，就會造成overfitting的情況。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*01UkbtKEjO2gmWKf-uaGWA.png" /></figure><blockquote><strong>Regularization</strong></blockquote><p>左右兩張圖做比較可以發現，其實用到二次方就可以完美fit這些資料，所以我們現在就是要把其他高次方的參數拿掉，讓模型不會過於複雜，減少overfitting。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hTEdbMaDtP0vZruM0OQrA.png" /></figure><p>以linear regression來說，我們就是在原本的loss function後面再加上 λΣθ²</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-skzm9uwouIuvT2oK51Gw.png" /></figure><p>下面這張圖可以得知，參數做更新的狀況，跟之前所介紹的gradient descent類似，只是後面多了regularization那一項，將式子整理後可以得到，θ後面乘上(1-α*λ/m)，因為(1-α*λ/m)&lt; 1，所以可以減少原本的weight（指的是θ，大部分書籍都是用w）的影響，小的θ影響不大，如果本來就很大的θ，就可以有效受到抑制。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCadmO08SZ2H1XLah0gKRw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d000e3dd561" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chung-yi/ml%E5%85%A5%E9%96%80-%E5%8D%81%E4%BA%94-regularization-solving-overfitting-9d000e3dd561">ML入門（十五）Regularization(Solving overfitting)</a> was originally published in <a href="https://medium.com/chung-yi">程式設計之旅</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>