<?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 Yuki Liu on Medium]]></title>
        <description><![CDATA[Stories by Yuki Liu on Medium]]></description>
        <link>https://medium.com/@yuki810289?source=rss-9c0bd00b9012------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TltIjktTVorIphZM4YkKwA.jpeg</url>
            <title>Stories by Yuki Liu on Medium</title>
            <link>https://medium.com/@yuki810289?source=rss-9c0bd00b9012------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:20:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yuki810289/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[影像辨識偵測異常行為]]></title>
            <link>https://medium.com/ai-academy-taiwan/%E5%BD%B1%E5%83%8F%E8%BE%A8%E8%AD%98%E5%81%B5%E6%B8%AC%E7%95%B0%E5%B8%B8%E8%A1%8C%E7%82%BA-196b41648bc1?source=rss-9c0bd00b9012------2</link>
            <guid isPermaLink="false">https://medium.com/p/196b41648bc1</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Yuki Liu]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 04:00:51 GMT</pubDate>
            <atom:updated>2022-02-15T04:00:51.331Z</atom:updated>
            <content:encoded><![CDATA[<h4>善用 AI 技術保護人員安全兼顧品質</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaIDvEn-FYatZDmGYEPYeA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@speedoshots?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Miłosz Klinowski</a> on <a href="https://unsplash.com/s/photos/cctv?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>工作場域安全一直是製造業最需關注之處，也是企業的痛點之一，即便根據不同的場域安全提出規範以及建立防護措施，但大多屬於被動式的防護，或需要大量的人力監控才能持續維護，然而此作法除了會降低工作效率，也會因執行上的落差而造成安全防護的漏洞。另外，道路攝影機林立往往也是有事故後才來調用，而不能即時制止災難或事故的發生。</p><p>現今結合 AI 技術，在物件偵測任務上清楚定義目標物，與攝影機整合，便能達到即時反應產業中，作業人員是否遵守安全守則以及是否依循產品作業流程，成為主動式的防護。以下將會分享所使用到的技術以及應用情境。</p><p>在物件偵測演算法中不外乎最熱門的 YOLO （You Only Look Once）系列，其中 ScaledYOLOv4 能實現即時預測以及具備相當的精準度。以下將會先概要 YOLOv4 的作法以及理解。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYUU6F6TQYLfOdxzFP1epQ.png" /><figcaption>圖1，ScaledYOLOv4 超越發表時的 EfficientDet-B7，達到最高的精準度以及最快的預測時間</figcaption></figure><h3>ScaledYOLOv4 作法及理解</h3><p>如圖 2 所示，在 YOLO 的核心想法上會將任何大小的輸入照片透過卷積層（convolutional layers）、堆疊以及殘差網路（residual net）擷取特徵，概念上如同切割成 SxS 的網格，並讓每一個網格預測三種資訊，分別是<strong>標記框的位移量</strong>（中心點 x, y 座標、標記框的寬高 w, h）、<strong>標記框的信心程度</strong>（是否存在標記框）以及屬於<strong>各個類別的機率</strong>，接著透過 IoU 或其變形的指標（GIoU、DIoU、CIouU）與正確答案比較調整訓練過程中應如何產生更精準的標記框。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQjY6FXvRMQjj53m1J7S7g.png" /><figcaption>圖 2，Yolo 算法獲得的輸出資料藉由預測的標記框位移量、信心程度以及屬於各類別的機率結合而成</figcaption></figure><p>依照 Yolov4 原始的架構而言，輸入的大小分別會藉由三種比例來切割網格，1/8、1/16、1/32，如圖 3 所表示的 ScaledYOlOv4 架構，若以 608x608 大小的輸入照片，則會切割成 76x76 （輸入照片邊長 1/8 大小）、38x38（1/16 大小）、以及 19x19（1/32 大小）的網格，這也因此造成使用原始架構時，需要將輸入照片設為 <strong>32 的倍數</strong>之原因。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIM_6J4pzDC3B0J0N-BfoA.jpeg" /><figcaption>圖 3，ScaledYOLOv4 簡易架構圖。圖片來源：<a href="https://zhuanlan.zhihu.com/p/150127712">https://zhuanlan.zhihu.com/p/150127712</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*4D6oFUFl9CImarB0.png" /><figcaption>圖4，卷積神經網路感受視野（receptive field），圖片來源：<a href="https://www.cnblogs.com/shine-lee/p/12069176.html">https://www.cnblogs.com/shine-lee/p/12069176.html</a></figcaption></figure><p>然而以卷積的想法來說，越後面的層（layer）得到的特徵圖（feature map）中的每一個像素（pixel）所反推到輸入照片的範圍越廣，也就是感受視野（receptive field）的概念（圖 4）。因此在 76x76、38x38、19x19 網格中得到的輸出對應到的標記框大小就會從小排到大。而在 YOLOv4 裡有 9 種 anchor，分別會在三種大小網格各 3 種 anchor 作為標記框的基底，再結合模型所預測出的標記框位移量得到最後標記框的位置及大小。</p><blockquote>計算以 608x608 大小的輸入照片，在 YOLO 的算法中最多可以得到多少個候選標記框呢？</blockquote><blockquote><em>19 x 19 x 3 ( 3 種大小的 anchor)+38 x 38 x 3+76 x 76 x 3 = 22743 個標記框</em></blockquote><p>從候選框中，再透過信心分數以及標記框的重疊率（利用 IoU 或其變形指標）篩選出最終的結果。</p><p>了解 YOLOv4 的細節以及與 YOLOv3 的差異，請參考</p><p><a href="https://medium.com/@d246810g2000/yolo-72d072007e2">https://medium.com/@d246810g2000/yolo-72d072007e2</a></p><h3>異常行為偵測場域</h3><p>以下依照曾處理過的異常行為任務分為兩種：</p><h4>靜態行為</h4><p>是否有佩戴防護器具、產品的處置，經常是作業人員會忽略的部分，包含安全帽、口罩、貨車承載物是否蓋上帆布等等。</p><h4>動態行為</h4><p>是否符合安全作業流程，人為的操作錯誤往往會帶來暗藏的危險，以及對產品的品質也會存在一些影響。例如：操作機台過程中是否依照現場警示正確操作、存放高危險物質的桶子是否有將封口緊密、中間產物的清潔是否確實等。</p><p>首先，會先來討論有關第一個屬靜態異常行為偵測，使用物件偵測時需要注意的項目。</p><ol><li>確認訓練照片的品質以及拍攝角度（若以工作場域所架設的攝影機為例，大多未考慮光線，或者拍攝角度與目標任務所要識別的物件並未達到好的角度）</li><li>確認標記時的標準一致（例如：是否框到背景資訊，目標物定義是否清楚）</li><li>確認模型所能負荷的輸入大小（例如：硬體設備以及每次訓練所能看到的照片數目）</li><li>確認符合模型輸入大小的照片品質（例如：不同比例的輸入照片，形變是否影響判別、縮放後的照片是否還明顯存在目標特徵）</li><li>確認從候選框中挑選最終標記結果所訂的閾值（標記框信心程度以及標記框重疊率）</li><li>確認各類別的辨識率（考慮是否要增加該類別的訓練資料）</li></ol><p>以下將會論述有關這六個步驟的細節：</p><blockquote><strong><em>步驟 1 </em></strong>確認訓練照片的品質以及拍攝角度</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ayfkGCrU72ZpSZhTpxIrUw.png" /><figcaption>圖 5，各個監視器架設角度以其光源對照片品質的差異。圖片來源：<a href="https://tw.live/national-highway/1/">https://tw.live/national-highway/1/N/N/</a></figcaption></figure><p>（如圖 5）大部分監視器角度以俯視並希望能觸及到最廣的範圍，這很有可能導致目標物件的形變，而無法以同一個模型廣泛應用到各個監視器影像上。光源也可能在工作場域中無法很好的控制，而造成照片品質不一。以上都會影響模型的訓練成效，因為在利用卷積網路擷取影像特徵時，都是基於每個像素不同強度（顏色）的排列組合。不同的形狀、不同的光源，套用在同一個物件上，會有很大的差別，也會導致訓練上的不易。因此在選用資料來源時，確認品質以及拍攝角度是在機器學習專案中最重要的第一步。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*LsJIugQZbHNB9V_SV4DBJg.jpeg" /><figcaption>圖 6，背光導致無法看清目標物件的細節。圖片來源：<a href="http://photo.popart.hk/newweb/archives/58138">http://photo.popart.hk/newweb/archives/58138</a></figcaption></figure><blockquote><strong><em>步驟 2 </em></strong>確認標記時的標準一致</blockquote><p>以標記＂是否佩戴安全帽＂這個行為為例，並非僅框安全帽就佩戴＂的行為在裡面，因此在這個目標上會選擇將人的頭部特徵一併框入標記框裡，如圖 7 所示。以上的概念是，有助於判斷目標物件的特徵都能思考是否要包含在標記框內。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*CyeEDd1sHQ6ThdIi31fiwg.jpeg" /><figcaption>圖 7，是否佩戴安全帽的標記框，圖片來源：<a href="https://www.itread01.com/content/1567425784.html">https://www.itread01.com/content/1567425784.html</a></figcaption></figure><p>以標記＂人＂的情況時，人透過以往的經驗以及對物件的認知，是可以知道在被遮擋的情況下一些物件還存在。例如圖 8 中間女生的小腿被前方蹲著的男生遮擋住，雖然人可以意會到後方存在著女生的腳，但若將標想像存在的小腿範圍一併標記進去，模型在這個標記框所學習到<strong>＂人＂的特徵</strong>包含大腿以下存在一些遮擋物。相同的，標記物品時，要如何界定框的範圍，會造成模型學習上一定的影響。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x1pBSQmhOI439NiI.png" /><figcaption>圖 8，人的標記框，圖片來源：<a href="https://appsilon.com/pp-yolo-object-detection/">https://appsilon.com/pp-yolo-object-detection/</a></figcaption></figure><blockquote><strong><em>步驟 3 </em></strong>確認模型所能負荷的輸入大小</blockquote><p>越大的模型輸入大小，所需要的記憶體就越大，因為在經過卷積後得到的特徵圖是較大的。若要以較大的模型輸入就需要犧牲掉每次訓練時批次的照片張數，也就是 Batch size 越小。在訓練時，以單張輸入做為模型更新的依據，可能會更受雜訊的干擾而導致模型收斂不易，此情況可以想像做決策時聽從多人的意見與一人意見的差別。多人意見需要達成共識或蒐集意見時相較耗時，而一人意見就容易偏頗，引入到 Batch size 的選用，最終導致的結果各會犧牲掉不同的東西。</p><blockquote><strong><em>步驟 4 </em></strong>確認符合模型輸入大小的照片品質</blockquote><p>從步驟一的圖 5 中看到監視器架設於高速公路上，為了看到大範圍的車流，因此也會讓車輛這個目標物更小，而工作場域的監視器大多也面臨一樣的問題。所以，為了符合模型的輸入大小，經常採用的處理方式為縮放照片，但這會讓目標物所佔的像素更少，甚至讓特徵不見；同時，在訓練過程以及推論過程中，縮放照片也會佔去大量的處理時間，可能導致無法即時預測。針對前者的問題，可採取的方法是以切割照片的方式保持相同的解析度，但這也會面臨切割線處如何偵測目標物，以及還原切割照片時的標記框如何整合。後者在一開始架設監視器時，先解決其解析度的問題能杜絕後續更多的問題。以目前的技術，大多的照片品質都相當的高，建議以人的肉眼能夠從照片中判斷目標物的特徵為底線，做為調整的依據。</p><blockquote><strong><em>步驟 5 </em></strong>確認從候選框中挑選最終標記結果所訂的閾值</blockquote><p>閾值包含候選框的信心程度以及候選框的覆蓋率（IoU 數值或其他變形的指標），調整數值可以處理最後標記框的乾淨程度。信心程度與是否容易出現易混淆，或相似特徵的物件有關，調整的準則通常以觀察誤判與正確判斷分數的分割點作為信心程度的閾值；如圖 9，覆蓋率能過濾掉過於接近的多個候選框，進而保留信心分數較高的，在 IoU 的數值意義上，越大的數值表示可容許的重疊率越大。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*-6e4a90YjCPfX_WeDdSllw.png" /><figcaption>圖 9，將 IoU 的閾值設為 0.4 時，能將 IoU 值大於 0.4 的候選框過濾掉。圖片來源：<a href="https://blog.csdn.net/u012052268/article/details/105989026">https://blog.csdn.net/u012052268/article/details/105989026</a></figcaption></figure><blockquote><strong><em>步驟 6 </em></strong>確認各類別的辨識率</blockquote><p>各個類別的標記張數應該有多少張，這個問題依舊只能從照片特徵的明顯程度、一致程度等來決定，然而 YOLOv4 的作者之一（Alexey）所提供的程式碼中（<a href="https://github.com/AlexeyAB/darknet">https://github.com/AlexeyAB/darknet</a>），寫下了有關資料準備的建議</p><blockquote>For each object which you want to detect — there must be at least 1 similar object in the Training dataset with about the same: shape, side of object, relative size, angle of rotation, tilt, illumination. So desirable that your training dataset include images with objects at different: scales, rotations, lightings, from different sides, on different backgrounds — you should preferably have 2000 different images for each class or more, and you should train 2000*classes iterations or more</blockquote><p>欲偵測的目標物，至少需要在訓練集中出現過至少一張相似的形狀、面向、大小、旋轉角度、傾斜程度、亮度，因此為了適應各式的情況，也就需要準備不同的形狀、面向、大小、旋轉角度、傾斜程度、亮度的影像。然而，每個類別以 2000 張來訓練可以達到近乎最好的結果，但實際上很難達成標記這麼多張的照片。以往的經驗，會以百計算的訓練集來實驗結果，再來增加較難以預測的類別照片張數。</p><p>而第二種動態行為需要考慮時間的推移，但若要以物件偵測的方式來解決，就可以利用輸出標記框間的相對位置，或者其中的資訊得到判斷。</p><ol><li>定義目標物件</li><li>標記框的後續處理</li></ol><blockquote><strong><em>步驟 1 </em></strong>定義目標物件</blockquote><p>利用物件偵測的方時判斷動態的行為，首先就須要找到要標記的目標物件，而目標物件的選取會藉由思考什麼是判斷此行為的構成物。</p><p>例如：</p><ul><li>擦拭玻璃，可以輔助行為判斷的是抹布、手等等。</li><li>鎖緊螺帽，可藉由板手（工具）、手等等來行為判斷。</li><li>爬高，人與支撐物等等作為判對依據。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vE4iRX4EqVPjEqMgqCsdEg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2d6FDmTeA1wxKCv3kYFoBg.png" /><figcaption>圖 10，左圖，擦拭玻璃可以標記的物件。圖片來源：jemaintenancell.com；右圖，鎖緊螺帽可以標記的物件。圖片來源：<a href="https://www.twmotor.com.tw/buy/main_products.php?pid=1831">https://www.twmotor.com.tw/buy/main_products.php?pid=1831</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*feAahdE_vn1uFOc0kRD33g.png" /><figcaption>圖 12，判斷是否爬高可以標記的物件。圖片來源：<a href="https://opinion.cw.com.tw/blog/profile/430/article/8883">https://opinion.cw.com.tw/blog/profile/430/article/8883</a></figcaption></figure><blockquote><strong><em>步驟 2</em></strong><em> </em>標記框的後續處理</blockquote><p>要判斷動態的行為，就需要連續觀察在不同的時間下，目標物件的標記框如何變化。</p><p>例如：</p><ul><li>擦拭玻璃，確認區域內是否都有確實擦拭，就可以使用標記框的<strong>中心點</strong>來做為軌跡紀錄。</li><li>鎖緊螺帽，在觀察時連續動作時，可以發現板手的標記框，<strong>長寬比</strong>在手轉動時，會有所改變，因此藉由這種想法來判斷是否有＂鎖＂的這個動作。</li><li>爬高，使用的是人與支撐物兩類別的標記框有<strong>重疊</strong>時，來判斷相對位置，也就是說，以認知上人這個類別應會相對於支撐物這個類別，使用中心點位置的比較，或者上下邊是否較高等等的做法。</li></ul><p>以上的作法，都是需經過資料的觀察以及探討，來確認規則是否存在例外。例如拍攝的角度，造成目標物件間的相對關係不如以往認知、或者目標物在判讀行為時被遮住等等的問題。</p><p>最後，在動態的行為上有更多其他的方法可以採用，例如：預測人的骨架去簡化特徵（PoseNet等等）、利用光流的方式找到物件移動方向。</p><h3>參考資料</h3><ul><li><a href="https://arxiv.org/pdf/2004.10934.pdf">Bochkovskiy, Alexey, Chien-Yao Wang, and Hong-Yuan Mark Liao. “Yolov4: Optimal speed and accuracy of object detection.” <em>arXiv preprint arXiv:2004.10934</em> (2020).</a></li><li><a href="https://arxiv.org/pdf/2011.08036.pdf">Wang, Chien-Yao, Alexey Bochkovskiy, and Hong-Yuan Mark Liao. “Scaled-YOLOv4: Scaling Cross Stage Partial Network.” <em>arXiv preprint arXiv:2011.08036</em> (2020).</a></li><li><a href="https://aics.asus.com/ai-safety-keeper/">利用人工智慧，打造一個安全無死角的工作場域</a></li><li><a href="https://zhuanlan.zhihu.com/p/150127712">YOLOv4 －網路結構和損失函數解析</a></li><li><a href="https://www.itread01.com/content/1546372272.html">行為識別 人體骨架檢測+LSTM</a></li><li><a href="https://www.gushiciku.cn/pl/pLB3/zh-tw">影片光流估計綜述：從演算法原理到具體應用</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=196b41648bc1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-academy-taiwan/%E5%BD%B1%E5%83%8F%E8%BE%A8%E8%AD%98%E5%81%B5%E6%B8%AC%E7%95%B0%E5%B8%B8%E8%A1%8C%E7%82%BA-196b41648bc1">影像辨識偵測異常行為</a> was originally published in <a href="https://medium.com/ai-academy-taiwan">Taiwan AI Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Semi-Supervised Learning]]></title>
            <link>https://medium.com/ai-academy-taiwan/introduction-to-semi-supervised-learning-20b5d2794da6?source=rss-9c0bd00b9012------2</link>
            <guid isPermaLink="false">https://medium.com/p/20b5d2794da6</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[semi-supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yuki Liu]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 04:00:23 GMT</pubDate>
            <atom:updated>2022-02-15T04:00:23.369Z</atom:updated>
            <content:encoded><![CDATA[<h4>探索半監督式學習</h4><p>半監督式學習（Semi-supervised learning，SSL）字面意義就如同採用一半的監督式學習（Supervised learning），以及一半的非監督式學習（Unsupervised learning）來設計的方法。然而實際上會遇到的問題往往是有大量的無標籤資料，為了使用較高準確率的監督式學習方法，而開始標記少量的資料。但標記資料牽涉到許多的問題，包括需要耗費各式成本，如何訂定統一的標準等等，都造成不易產生大量標記資料的原因。因此如何在有限的標記資料下，以及善用大量未標記資料來做目標任務成為了半監督式學習著重的目標。</p><p>Google 首席科學家 Vincent Vanhoucke 闡述了對半監督式學習發展的想像，提及一個典型的機器學習工程師遇到半監督式學習的處境時，處理的過程如下圖一所示：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*wSh6ogBZewMu69b-" /><figcaption>圖一，以往的半監督式與監督式學習的發展</figcaption></figure><ol><li>當一開始完全使用監督式學習時，只能得到糟糕的結果，不如嘗試使用半監督式學習。</li><li>雖然數字上升了，但還是不盡理想，還是只能嘗試多點標籤資料。</li><li>標籤資料越多越好了，如果拋棄半監督式學習是否能更好。</li><li>似乎一開始盡力標記資料就好了。</li></ol><p>（如圖二）要達到半監督式學習高於監督式學習的程度還需要一些新的突破，例如要如何讓數據加標籤的方法更加精準，將標籤誤差或雜訊都考慮進模型訓練的依據。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*4e5uodRLVMKEfIKc" /><figcaption>圖二，希望半監督式學習達到的成效</figcaption></figure><p>以下是近年來發展半監督式學習的大致方向</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHdKCwZm1Ls0oFvtevGMCw.png" /><figcaption>圖三，半監督式學習的方法分類</figcaption></figure><p>如何在未標籤的資料上獲得相對應合理的標籤，以及找到標籤資料與未標籤資料的共同特性，是發展各種方法的重點之一。</p><h3>Proxy-label methods</h3><p>此類的做法是利用現有標記資料訓練之模型，擷取未標籤資料的特徵並得到代理標籤（Proxy label），目標是讓所有的資料都能取得對應的標籤，進而訓練完整的模型於所有資料上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*8xXjHQywiu7JUzHPyNPgkQ.png" /><figcaption>圖四，Proxy-label 方法用於 SSL 之概念圖</figcaption></figure><p>如圖五，若現有的資料集為具有標籤影像，例如貓、狗、狐狸等等，另外有未標籤的動物影像，按照 Proxy-label 方法，則步驟是：</p><ol><li>利用貓、狗、狐狸等等的影像利用監督式的方法訓練出一個模型。</li><li>利用步驟 1. 訓練好的模型，去預測未標籤的動物影像，則會得到一組類別的機率分布（若此動物影像具有貓的特徵，預期會得到屬於貓的機率較高）。</li><li>界定一個閾值（Threshold），若最高機率值超過此閾值，則將此影像的標籤定為最高機率的類別，藉此得到未標籤影像的標籤，也表示對此標籤足夠具有信心；若未超過閾值，則不賦予標籤。</li><li>從步驟 2. 得來的未標籤影像的類別機率分布或者從步驟 3. 得來的未標籤影像的標籤，與原始未標籤影像則可視為一組已標籤的資料，再與原始標籤資料合併重新訓練模型。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3EEJ3WLMRMmkydsmf_Og5w.png" /><figcaption>圖五，Proxy-label 方法之例子</figcaption></figure><h3>Consistency regularization</h3><p>假設存在一真實擾動於資料上，則轉換至低維度空間中的結果也與原始資料不會有明顯的差異，如圖六。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*0jgYRfZA_M3KN7l8BONgYQ.png" /><figcaption>圖六，Consistency regularization 目標</figcaption></figure><p>Consistency regularization 這類的算法基於以上假設來做進一步的訓練的目標 — 最小化轉換資料與其經擾動後轉換資料間的距離，即是</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yg32CbFKsMuNaLkDu3G-A.png" /></figure><p>如圖七，若現有的資料集是影像資料，按照 Consistency regularization 方法，則步驟是：</p><ol><li>針對影像資料添加擾動，例如增加噪點、旋轉、翻轉等。</li><li>對所有資料藉由模型轉換至較低維度的空間。</li><li>最小化具擾動的影像與原始影像轉換至低維空間中的距離，以更新模型。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBx-7Zw89-1Qn9WmaByqog.png" /><figcaption>圖七，Consistency regularization 方法之例子</figcaption></figure><h3>Generative methods</h3><p>生成模型中 Autoencoder-based（自動編碼器，AE） 方法的目標是經過重建得到與本身一樣的資料，也就是要最小化重建與輸入資料間的距離，而此過程是不需要任何標記資料，為非監督式的學習（Unsupervised learning），得到重要的資訊是透過降維後所擷取出的特徵。經由訓練的過程讓降維後的特徵有足夠的訊息量來表示原始資料，進而加入標記資料做目標任務，即是監督式的學習（Supervised learning）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbtM34c70e2uAINx3UchsA.png" /><figcaption>圖八，Autoencoder-based 方法用於 SSL 之概念圖</figcaption></figure><p>另一種 GAN-based（對抗式生成網路，Generative adversarial network） 方法的目標是透過生成器（Generator）和判別器（Discriminator） 去做到生成以及判斷是否為生成，也無須資料標籤參與訓練。然而在目標任務上需要的標籤資料則大多會與判別器結合輸出，以達到半監督式學習（Semi-supervised learning）的訓練方法。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgxUD8VyNgja_-mXCW-rhA.png" /><figcaption>圖九，GAN-based 方法用於 SSL 之概念圖</figcaption></figure><h3>Self-supervision</h3><p>自監督式學習（Self-supervision、Self-supervised learning）基於輔助任務（Pretext task）來提供訊息作為監督式學習的目標，通常是基於特定領域、對資料的共識、特性來設計的訓練過程。然而此過程中無須存在額外的標籤，而是以資料本身通過特定轉換作為目標，預先得到好的特徵表達式以至於能遷移到其他的目標任務上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*DqaCfu0qLsRWZjxcxWJ5FQ.png" /><figcaption>圖十，Self-supervision 概念圖。圖片來源：<a href="https://sthalles.github.io/self-supervised-learning/">https://sthalles.github.io/self-supervised-learning/</a></figcaption></figure><p>要得到好的特徵表達式就需要設計好的輔助任務（Pretext task），在圖像上常見的方法有旋轉（Rotation）、色彩化（Colorization）、修復（Inpainting）等，另外在文本中最有名的就是利用 CBOW 以及 Skip-gram，從中學習文字間的關聯性進而得到好的特徵表達式。</p><h3>Graph-based SSL</h3><p>圖（Graph）的方法中需要考慮的兩個步驟是，如何建構圖（Graph construction），以及如何做標籤的推論（Label inference）。然而在推論的方法中又分為 Regularization，以及 Embedding 的方式。</p><ul><li>Graph regularization</li></ul><p>目標分為兩個部分，一個是經過轉換函式後得到的值要越靠近給定的標籤，另一個是轉換的函式要足夠平滑，也就是限制模型的複雜程度。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*JqAkdwMemqXpNJsYEODHuQ.png" /><figcaption>圖十一，Graph regularization 目標函數</figcaption></figure><ul><li>Graph embedding</li></ul><p>將圖中的各個節點編碼至一個較低的維度空間中，而原始節點間的位置以及結構能夠反應在這個空間中。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYGqwVdoFM4-x33K6lgAVg.png" /><figcaption>圖十二，Graph embedding 示意圖。圖片來源：<a href="https://towardsdatascience.com/overview-of-deep-learning-on-graph-embeddings-4305c10ad4a4">https://towardsdatascience.com/overview-of-deep-learning-on-graph-embeddings-4305c10ad4a4</a></figcaption></figure><p>在半監督式學習當中有各式解決不同資料型態，不同問題的方法，以上所列出來的方法會在後續的文章中一一介紹其中較著名的技術。</p><h3>參考資料</h3><ul><li><a href="https://arxiv.org/pdf/2006.05278.pdf">Ouali, Yassine, Céline Hudelot, and Myriam Tami. “An Overview of Deep Semi-Supervised Learning.” arXiv preprint arXiv:2006.05278 (2020).</a></li><li><a href="https://arxiv.org/abs/2102.13303">Song, Z., Yang, X., Xu, Z., &amp; King, I. (2021). Graph-based Semi-supervised Learning: A Comprehensive Review. arXiv preprint arXiv:2102.13303.</a></li><li><a href="https://arxiv.org/pdf/1902.06162.pdf">Jing, Longlong, and Yingli Tian. “Self-supervised visual feature learning with deep neural networks: A survey.” <em>IEEE transactions on pattern analysis and machine intelligence</em> (2020).</a></li><li><a href="https://towardsdatascience.com/the-quiet-semi-supervised-revolution-edec1e9ad8c">The Quiet Semi-Supervised Revolution</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20b5d2794da6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-academy-taiwan/introduction-to-semi-supervised-learning-20b5d2794da6">Introduction to Semi-Supervised Learning</a> was originally published in <a href="https://medium.com/ai-academy-taiwan">Taiwan AI Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes on CS231n: Convolutional Neural Networks for Visual Recognition Part II]]></title>
            <link>https://medium.com/ai-academy-taiwan/notes-on-cs231n-convolutional-neural-networks-for-visual-recognition-part-ii-817f74004c15?source=rss-9c0bd00b9012------2</link>
            <guid isPermaLink="false">https://medium.com/p/817f74004c15</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Yuki Liu]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 10:04:13 GMT</pubDate>
            <atom:updated>2020-03-28T10:04:13.476Z</atom:updated>
            <content:encoded><![CDATA[<p>Loss Function and Optimization, Backpropagation and Neural Networks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Q_S-E1HD8ipXzP3swuQBQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@matreding?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mat Reding</a> on <a href="https://unsplash.com/s/photos/valley?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>CS231n 第 2 課介紹了最簡單的線性分類器的想法，接下來第 3 課將會介紹如何去評估模型表現的好壞以及他更新模型的機制，而第 4 課會接著說明在複雜的類神經網路內，如何快速地去計算要更新的數據。</p><h3><strong>Lecture 3: Loss Function and Optimization</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*X-C9QWE1HE9TYZMAGxFL8w.png" /><figcaption>從線性系統 f(x, W) = Wx 找到影像對應各個類別的分數</figcaption></figure><p>我們從上次最簡單的線性分類器 Wx 可以得到此影像屬於各個類別的分數。但如何才能評估此分數的好壞呢？只要所屬類別分數最高就好嗎？其中有兩種常見的想法，分別是 Multi-class SVM 以及 Softmax classifier。</p><h4><strong>Multi-class SVM</strong></h4><p>此方法將線性分類器計算出來的分數看做每個類別的得分，而這個數值大小並不重要，它的意義僅在於跟其他類別比較。因此能想像到的是，只要所屬類別相對其他不屬於的類別分數夠有鑑別度（比其他類別的分數來得高），就能有自信說他確實屬於這個類別。</p><p>如果要達成這個目標，且此影像所屬的類別為 y_i，則能滿足以下這個式子</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*YE2e0W2Q06Xc-KM0oFAhdA.png" /><figcaption>正確類別的分數比其他不正確類別的分數來得還要高 margin 的量</figcaption></figure><p>相對來說，分數不夠好，則還有以下的距離需要增進，才足夠有信心被識別為正確類別</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*7r_a0pujFKJsUamgOYtK_g.png" /></figure><p>因此，我們統整以上欲滿足的條件，則可以定義與目標的距離（Objection function）或者稱為損失函數（Loss function）為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*regtBxj2a4HSNhLQBZvMsg.png" /><figcaption>Loss = 0，則表示分數足夠好了；Loss &gt; 0，則表示分數還有可以改善的空間</figcaption></figure><p>而此定義方式即是 SVM（Support Vector Machine）計算多類別的損失函數。</p><p>假設 margin= 1，則可以透過損失函數，又稱 <strong>Hinge loss</strong>，計算出此分類器對各個影像的分數（最好的損失值為 0）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSEqDZ84hSNdOliFwoaIoA.png" /><figcaption>以這三張訓練樣本來說，對於此分類器計算後得到的平均損失為 5.27</figcaption></figure><h4><strong>Softmax classifier</strong></h4><p>它將線性系統得出來的分數視作一種未歸一化的對數機率分布（unnormalized log probabilities）。因此若想得到常見的機率形式，則可利用指數再歸一化得到，也就是以下式子，又稱為 <strong>Softmax function</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*EOcUrLm0RRlbfvPRKX4lIw.png" /><figcaption>將每個類別得到的分數都視為是一個條件機率，而這個數值會介於 [0, 1] 之間</figcaption></figure><p>依照此想法，若想要得到 W，則要最大化似然，即是</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*lc6Kkin6QaH5jYBp6sb2PA.png" /></figure><p>因此，我們可以將損失函數定義為以下式子，又稱為 <strong>Cross-entropy loss</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*p0gsWee3FSUXAVl-_Lv-ug.png" /><figcaption>預期的是最小化 Loss，因此加上負號便能達到一樣的目標</figcaption></figure><p>由以下例子就可以分別看到計算 Hinge loss 以及 Cross-entropy loss 的結果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zYRqmEiBoLYmq4D97Lkeg.png" /><figcaption>Hinge loss 是跟其他類別的分數比較出來的，而 cross-entropy loss 的想法是從機率分布來的（normalize 過的結果會像是個機率形式）</figcaption></figure><p>然而，損失函數的意義是評估模型表現的好壞。每當我們使用訓練的樣本去訓練模型時，會希望損失函數是低的，但更重要的是這個模型可以應用在測試的資料上（未經訓練的資料）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*79fVavPN0rG28AhcrAhrZA.png" /><figcaption>藍色圓圈為訓練資料，綠色方塊則為測試資料。在訓練時，模型為了達到低的損失值，就會越擬合訓練資料的分布，但很有可能無法很好地推論到測試的資料上（如右圖）</figcaption></figure><p>若一味的追求損失函數在訓練集上的表現，很有可能會出現過擬合的傾向，也就是過度擬合訓練資料。然而，不可避免的是訓練資料可能帶有雜訊干擾模型，因此在擬合這些資料時，就會對往後測試資料的判斷造成影響。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oT3xGNy6itp6n3xp6jbK2A.png" /><figcaption>不用很複雜的模型去擬合，反而用簡單模型會有更好的抗雜訊能力，使得泛化性（generalization）更好</figcaption></figure><p>為了降低模型的複雜度，可以利用<strong>正規化</strong>（ Regularization）的方法限制了決定模型複雜度的參數 W。R(W) 加入損失函數 L，即可視為懲罰項，若 R(W) 很大（複雜度高）則會讓損失值上升。因此整個損失函數則可同時判別<strong>精準度</strong>以及<strong>複雜度</strong>，其中的比例以 lambda 去做平衡。</p><p>最常見的正規化方法有 L1, L2 以及 Elastic net（L1+L2）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1aCUiFp-yZ6LOQa8pZ9TWg.png" /></figure><p>透過正規化的限制，W_i 的值會被限縮，因此無法透過大範圍的調整達到好的分數（精準度），但複雜度會因而降低。</p><p>除了正規化的方式可以降低模型複雜度，還有一個常見的方法是 Dropout，會在後面的章節詳細介紹。</p><h4>Optimization</h4><p>在了解如何評估模型結果的好壞之後，模型就可以依據這個評估標準來做模型的更新，也就是優化器（Optimizer）的部分。我們可以想像損失函數在高維空間中表示的是一個超曲面，若簡單以三維空間來說的話，他會如以下圖所示</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*FIcIIn8e7LNQ9hAi.png" /><figcaption>優化器的目標就是會了找到曲面的最低點位置，表示損失函數最低的地方</figcaption></figure><p>為了走到最低點的地方，有一些策略可以思考：</p><ol><li>隨機搜尋（Random search）何處最低，但此方法的可信度會相當依賴取樣的個數。</li><li>根據斜率去尋找走的方向，尋找當下位置切線向下的方向，一點一點地前進。</li></ol><p>因此要計算斜率，會依據以下公式去求得</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*5A2ZKIHxnZ2D8NK9UFHwyw.png" /><figcaption>從損失函數的平面去找 gradient，而損失函數的變數即是 W</figcaption></figure><p>最常見的 Optimization 方法是梯度下降（Gradient Descent），他的想法便是最直覺地利用梯度（gradient）去更新 W 的值，所以，新的 W 位置就會依照下面的方法去做更新</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*zpa0Q4bl4ikO7Ntz0AW23Q.png" /><figcaption>step_size 的意義是為了調整 gradient 方向上的更新距離</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2_2_D7T3m-ezKXtRIdSsw.png" /><figcaption>為了往低處走，不論是 gradient 是正是負，新的 W 位置都會是 W — step_size * W_gradient</figcaption></figure><p>Gradient Descent 的方法會依照所有訓練資料計算出來的損失值去做一次模型的更新，但是當訓練資料的總數很大時，這通常會讓模型更新速度上變得緩慢。然而，有另一個方法提出的解決辦法是取一個較小的訓練樣本數去逼近原本的平均損失，進而快速的更新模型，而此方法稱為 Stochastic Gradient Descent（SGD）。</p><p><a href="https://docs.google.com/file/d/0Byvt-AfX75o1NndHNjVoVU1RRzQ/preview">sgd+adam.mov</a></p><p>除了直接利用影像上每個像素的值作為特徵去辨識外，我們可以看到很多過去為了影像的演算法利用一些影像的特性作為特徵，去解決一些問題，例如：Color Histogram、Histogram of Oriented Gradients 等等，但哪一些影像的特徵是有助於做影像分類的問題呢？在往後的章節就會介紹 ConvNet 如何去擷取出影像的特徵。</p><p>影片位址： <a href="https://www.youtube.com/watch?v=h7iBpEHGVNc">https://www.youtube.com/watch?v=h7iBpEHGVNc</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fh7iBpEHGVNc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dh7iBpEHGVNc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fh7iBpEHGVNc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1094f0f4e5eb8ea0363ea60b8ceb7bd2/href">https://medium.com/media/1094f0f4e5eb8ea0363ea60b8ceb7bd2/href</a></iframe><h3>Lecture 4: Backpropagation and Neural Networks</h3><p>在上一課內容談及除了要評估模型好壞以外，也要依據此評估指標來做模型上的更新，也就是透過 Gradient 的方向去尋找損失相較低的方向前進。而這個 Gradient 是針對模型內的每個參數去做計算的。然而對於一個深層的網路或複雜的網路，應該如何得到呢？因此以下會由一個簡單的例子示意，觀察計算各參數的 Gradient 有何規律。</p><h4>A simple example: f( X, Y, Z ) = ( X+ Y) Z</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*b44Ai5kOe4gpeAks4O0wNw.png" /><figcaption>分別將 X=-2, Y=5, Z=-4 代入f(X, Y, Z) = ( X + Y ) Z</figcaption></figure><p>對於簡單的四則預算，如何從最終的結果，也就是函數的輸出來往回推導各個參數的 Gradient 呢？也就是要分別計算出 f 對 X, Y, Z 的 Gradient 值</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*8_7e44MEE19_3hhTuNNHUw.png" /><figcaption>目標得到各個參數的 Gradient 值</figcaption></figure><p>若令 X + Y = q，則 f = q Z。因此利用計算偏導數的規則分別可得到</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*woFN4TmDKWNKNDcNjs8thg.png" /><figcaption>分別計算每個參數的偏導數</figcaption></figure><p>依照鏈法則（Chain Rule）的規則，因此</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*gPjGl9CMD6JGiPudWwxU0w.png" /></figure><p>從計算圖上觀察</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*3aaopNzHELpsPHcjSEwd6A.png" /><figcaption>對於每個計算元皆有兩輸入一輸出，則從後向前傳遞，前者的 Gradeint 皆會與後者有關</figcaption></figure><p>我們再來細看每一個運算元前後的關係何？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjVb8RfxzcS7Hbctq21fYA.png" /><figcaption>每個節點對於最終 Loss 的偏導數為 Local gradient 與 Upstream gradient 的乘積</figcaption></figure><p>因此每個節點都可以運用 Local gradient 與 Upstream gradient 的乘積來計算 Gradient，值到傳播到最一開始輸入的節點，由後向前傳遞 Gradient 的概念也稱為反向傳播（Backpropagatation）</p><p>除了基本的四則運算外，若經過更複雜的計算是否也還能依據此法得到相對應的 Gradient 值，以下將由另一個例子示意。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*8KL7BR35S2tteYbax0UqLQ.png" /></figure><p>此函數運算包含倒數以及指數等，是否能用相同的規則去計算各節點的 Gradient？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eL4Ayue_CnHkM2tFCREg3A.png" /><figcaption>利用 Local gradient x Upstream gradient 得到各個節點的 gradient 值</figcaption></figure><p>經由函數直接做各個參數的偏導數計算，可以得到最終的結果與上述法則得到的結果相同。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*5hCXJosntuA9as-iMahwfQ.png" /><figcaption>實際計算對於 w_0, x_0, w_1, x_1, w_2 的偏導數</figcaption></figure><p>其中令 X= w_0 x_0+w_1 x_1+w_2，則</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZjtLCTElM76XXYHAVMb2w.png" /><figcaption>sigmoid function 及其導函數</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OZuzH8A9uBaCF9fT4vrrw.png" /><figcaption>也能將多個節點合併一起計算其 Gradient 值</figcaption></figure><p>由一個神經元輸出到計算損失函數，可以看到反向傳播 Gradient 是如何進行的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQBhG-PwLUa1szk6q1XnNQ.png" /></figure><p>然而，對於一個深層複雜的類神經網路將每個節點的 Gradient 一一透過方程式解偏導數是不現實的作法。所以需要透過反向傳播，循環使用鏈法則的方法，藉由向前傳播（forward）計算而得的 Local gradient，以及由後向前傳遞（backward）的 Upstream gradient，來得到每個節點（神經元）所需參數的 Gradient，進而更新整個網路，往可以得到相較小的損失函數方向前進。</p><p>接下來需要探討的問題是一層簡單的線性分類器無法解決現實複雜的情況，如何思考非線性且合理的類神經網路。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xRTd07pIM37RwmxB5lQeKg.png" /><figcaption>透過 max(‧) 在神經網路內製造非線性因子</figcaption></figure><p>我們可以實際考慮神經的作用來跟類神經網路的神經元去做對照。由樹狀突起（dendrite）處接收訊息，接著匯集至細胞體（cell body）去做訊息處理，最後再經由軸索（axon）將訊息傳遞出去，而此訊息需要有一定的能量差才能傳遞，因此而有設立激活函數（activation function）來仿造此生物反應。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CNrvIOUPKEzX0r7ONSL6w.png" /></figure><p>除了使用 Sigmoid function 作為激活函數以外，還有其他函樹研究在類神經網路內可以使用的激活函數。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7km34zCa2yH-ZtlnpSWCQQ.png" /><figcaption>目前在類神經網路適合使用的激活函數。</figcaption></figure><p>我們需要用非線性的函數來解決現實中較複雜的任務以外，還需要考慮的問題是，在影像中，需要將每個像素值都視為一個節點，對於目前的神經網路架構設計上會有很大的負擔，因為在解析度越大的影像上，所需具備的參數量也就越大，會由以下圖示來解釋。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUKNTfTRP9pl9OaeVWQi_g.png" /><figcaption>每一個節點都會跟後面的神經元作連結，也稱為全連接層（Fully-connected layers）</figcaption></figure><p>若想像 input layer 輸入的每個節點分別是圖像上的一個像素點（pixel），則排序（影像的形狀會從二維轉換成一維的向量，元素數量不變）上以及參數量（每一層的神經元個數與前一層節點總數相乘）上都需要有更多的考量，才能更好地解決視覺影像的任務。而下一個章節則會談談視覺影像的特性，以及如何更好的來擷取影像上的特徵以利做影像上的任務。</p><p>影片位址： <a href="https://www.youtube.com/watch?v=d14TUNcbn1k">https://www.youtube.com/watch?v=h7iBpEHGVNc</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fd14TUNcbn1k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dd14TUNcbn1k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fd14TUNcbn1k%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d006076fdb3b3442715f2b8c194f093d/href">https://medium.com/media/d006076fdb3b3442715f2b8c194f093d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=817f74004c15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-academy-taiwan/notes-on-cs231n-convolutional-neural-networks-for-visual-recognition-part-ii-817f74004c15">Notes on CS231n: Convolutional Neural Networks for Visual Recognition Part II</a> was originally published in <a href="https://medium.com/ai-academy-taiwan">Taiwan AI Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes on CS231n: Convolutional Neural Networks for Visual Recognition Part I]]></title>
            <link>https://medium.com/ai-academy-taiwan/notes-on-cs231n-convolutional-neural-networks-for-visual-recognition-part-i-7c11944a3891?source=rss-9c0bd00b9012------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c11944a3891</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Yuki Liu]]></dc:creator>
            <pubDate>Tue, 03 Dec 2019 09:01:01 GMT</pubDate>
            <atom:updated>2020-08-08T04:08:37.395Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction, Image Classification pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Io9X6JB0eKBt94kK96CbUQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pawelskor?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Paul Skorupskas</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>CS231n 是一堂相當熱門的電腦視覺課程，由 Stanford Computer Science 的李飛飛教授主講，以下簡介節錄自此課程的官方網站<a href="http://cs231n.stanford.edu/">http://cs231n.stanford.edu/</a>：</p><blockquote>Computer Vision has become ubiquitous in our society, with applications in search, image understanding, apps, mapping, medicine, drones, and self-driving cars. Core to many of these applications are visual recognition tasks such as image classification, localization and detection. Recent developments in neural network (aka “deep learning”) approaches have greatly advanced the performance of these state-of-the-art visual recognition systems. This course is a deep dive into details of the deep learning architectures with a focus on learning end-to-end models for these tasks, particularly image classification.</blockquote><p>2017 春季的課程已在 YouTube 上公開上課影片。從此篇文章開始，將會一一分享影片裡面所學到的內容。</p><p>CS231n Spring 2017 主要有 14 堂課程以及 2 次的演講，從電腦視覺的基礎概念開始介紹，奠定基礎分類模型、神經網路和最佳化算法後介紹 CNN、RNN、Generative Model、RL 主要幾個深度學習模型在電腦視覺上的應用。此文將會先介紹基礎的內容（Lecture 1、2）：</p><ol><li>Introduction</li><li>Image Classification pipeline</li></ol><h3><em>Lecture 1: Introduction</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hKHljzhaZia6xBEW3ft1KQ.png" /><figcaption>電腦視覺是一門跨學科的學問，包含物理學、生物學、心理學、電腦科學、數學、及工程。</figcaption></figure><p>以下將會簡介一些在電腦視覺領域上較有名的研究歷史發展，以及近期更多電腦視覺所要解決的任務。</p><h4>A brief history of computer vision</h4><p><em>生物視覺機制</em></p><ul><li>Hubel &amp; Wiesel, 1959</li></ul><p>觀察貓的視覺皮質細胞對哪種刺激會有反應，視覺皮質細胞含有各種神經元，特別有簡單細胞及複雜細胞對 “ 簡單圖樣及其移動的方向 ” 發生強烈的反應。此實驗發現<strong>視覺處理始於簡單的結構，進而處理複雜的物件能辨識所看到的物體</strong>。</p><p><em>機器視覺機制</em></p><ul><li>Gemma Frisius, 1545</li></ul><p><strong>針孔成像相機</strong>如早期生物眼睛構造，從小孔接收光線，透過後面的平面板收集信息且投影成像，也是<strong>最早仿造生物視覺的機器。</strong></p><ul><li>Larry Roberts, 1963</li></ul><p><strong>Block world</strong> 為最早有關電腦視覺的一篇論文，提出<strong>視覺世界從簡單的幾何圖形開始，進而能識別及重建。</strong></p><ul><li>David Marr, 1970s</li></ul><p><strong>Vision</strong> 這本書描述作者如何理解視覺，以及如何開發識別視覺世界的演算法 — 從一張拍攝的影像要獲得真實世界的 3D 模型，必須經歷的一些過程。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXPfw-NncJRtmkJCPcI5zg.png" /></figure><ol><li>Primary Sketch：以大部分的邊緣、端點、線條、曲線簡單的結構來表示一張影像。</li><li>2.5-D Sketch：從不連續的深度曲面分割影像。</li><li>3-D Model Representation：各個分層的曲面則可組織出 3D 模型</li></ol><p>此種理想的思維影響了電腦視覺領域幾十年，也是<strong>一種非常直觀的方式來解構視覺信息並重建視覺世界的物體。</strong></p><ul><li>Fischler and Elshlager, 1973; Brooks &amp; Binford, 1979</li></ul><p>思考如何<strong>以簡單的結構辨識及表示真實世界中的物體</strong>，分別提出以圓形（<strong>Pictorial Structure</strong>）及圓柱體（<strong>Generalized Cylinder</strong>）簡單的物件來組合成複雜的結構。</p><ul><li>David Lowe, 1987</li></ul><p><strong>通過偵測線和邊緣建構影像中的資訊，嘗試解決物體識別的任務。</strong></p><p><em>1960~1989 年間，科學家從有限且簡單的樣本，嘗試物體識別的任務，但很難做出實際有價值的應用。因此，轉而思考另一個機器視覺的任務 — 如何對目標進行分割。</em></p><ul><li>Shi &amp; Malik, 1997</li></ul><p>提出基於圖學的 Normalized Cut 演算法，<strong>將影像中的像素間的關係並分群至有意義的區域，達成影像分割的任務。</strong></p><p><em>另一個在電腦視覺中有所進展的任務是人臉辨識。</em></p><ul><li>Viola &amp; Jones, 2001</li></ul><p>基於 1999 – 2000 年間發展的各式機器學習方法，其中以 AdaBoost 來偵測主要人臉的特徵 — 眼睛及其他器官，進而找到人臉。值得一提的是當時的硬體設備有所限制，但此研究實現的卻是<strong>即時的人臉檢測，也是實際能在數位相機上應用的技術。</strong></p><p><em>「如何繼續更好地做物體識別任務」依舊是電腦視覺領域的一大問題。</em></p><ul><li>David Lowe, 1999</li></ul><p>通常物體識別會因為光線、遮罩、拍攝角度等因素而難以辨識。而 <strong>SIFT</strong> 算法透過特徵的解析，具有物體的表現性及不變性以解決辨識的問題。因此<strong>物體識別的任務從偵測 “ 整個目標 ” 轉移到偵測 “ 特徵 ” 上</strong>，這讓辨識的任務變得更加容易。</p><ul><li>Schmid &amp; Ponce, 2006</li></ul><p><strong>Spatial Pyramid Matching</strong> 進一步識別的是整張圖的場景，其想法是<strong>透過影像各個位置的特徵描述，進而由 SVM 的方法對特徵做識別。</strong></p><ul><li>Dalal &amp; Triggs, 2005; Felzenswalb, McAllester, Ramanan, 2009</li></ul><p>思考如何更好的表示一張影像中的特徵，<strong>Histogram of gradients </strong>及 <strong>Deformable Part Model</strong> 一樣<strong>透過各自提出的特徵提取方式，並用機器學習方法來識別所要解決的任務。</strong>前者以統計梯度方向作為特徵，後者則多加入更細部的位置資訊作為特徵。</p><p>電腦視覺主要的任務在於物體辨識，為了解決這項任務，從了解生物視覺系統開始，一直到如何做特徵擷取。而同時也有其他電腦視覺的任務在發展。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Y_4zS-um0e184qL2DjxKw.png" /></figure><p>直到 21世紀的早期，才開始真正擁有具有標註的資料集提供衡量物體識別任務的成果，其中包含 20 種標記物體的資料集 PASCAL 及更加龐大的資料集 IMAGENET 有 2 萬 2000 種標記的物體影像。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ap_8laBvsaNN1qj8ksdDJw.png" /><figcaption>IMAGENET 的競賽從2010年開始，錯誤率一直持續在下降，甚至到了 2015 年更是比人類的識別錯誤率還要更低。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_g81W1lAJBUNMwvb4lM9sw.png" /><figcaption>從 2012 年開始有效的降低識別的錯誤率，而當年獲獎的算法即是使用了一種卷積神經網路的方法，持續到 2015 年的優勝算法依舊是卷積神經網路。</figcaption></figure><h4><strong>CS231n overview</strong></h4><p>此課程會先專注在電腦視覺最主要的任務上 — 影像辨識，而更進一步發展出來的問題是如何達到物件偵測 Object detection（有邊界框描述位置）、動作識別 Action classification（多張影像的識別）、圖像摘要（形容多個物件間的關係）等。</p><p>另外也有更多電腦視覺的任務正在進行中…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udA1R-ARKdCdbas7zbgULA.png" /><figcaption>左上：語意分割 (Semantic segmentation) 左下：動作識別 (activity recognition) 右上：三維重建 (3D reconstruction) 右下：虛擬實境 (virtual reality)</figcaption></figure><p>影片位址： <a href="https://www.youtube.com/watch?v=vT1JzLTH4G4&amp;list=PL3FW7Lu3i5JvHM8ljYj-zLfQRF3EO8sYv&amp;index=2">Lecture 1: Introduction</a></p><h3>Lecture 2: Image Classification pipeline</h3><p>對於影像辨識的任務會面臨種種挑戰：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLKtcuRRIJSy17kYpD1XIw.png" /><figcaption>種內差異 (Intraclass variation)、背景干擾 (Background clutter)、亮度(Illumination)、形變 (Deformation)、遮蓋 (Occlusion)</figcaption></figure><ul><li>高解析度的影像需要處理的維度很高，例如一張256*256 大小的彩色影像，則需 256*256*3(RGB channel) = 196608 維來表示。</li><li>拍攝角度不同，如同平移過的影像，幾乎所有像素值都會改變，但所要識別的目標並未改變。</li><li>同種物體間的差異性，例如材質、形狀、大小、顏色等。</li><li>相似材質的背景或與背景融合。</li><li>不同的光源及場景影響影像的亮度。</li><li>形變、姿勢及位置。</li><li>場景的覆蓋或遮罩。</li></ul><p>面對這些挑戰應該如何做分類器？先想到輸入照片，經過一連串的判斷，最終輸出為對應的類別。</p><pre>def classify_image(image):<br>    # Some magic here?<br>    return class_label</pre><p>最直覺的想法是中間的過程需要做一些特徵的提取，但對於不同的目標會有不同的特徵，也會因為上述的各種干擾而無法找到好的特徵，因此這並非容易的事。</p><p>而另一種想法是 Data-Driven Approach，指的是</p><ol><li>先大量蒐集各種影像，並同時賦予標籤</li><li>使用機器學習的方式訓練分類器</li><li>最後驗證在新的影像上</li></ol><pre>&#39;&#39;&#39; Memorize all data and labels &#39;&#39;&#39;<br>def train(images, labels):            <br>    # Machine learning!<br>    return classifier</pre><pre>&#39;&#39;&#39; Predict the label of the most similar training image &#39;&#39;&#39;<br>def predict(classifier, test_image):  <br>    # Use classifier to predict labels<br>    return test_labels</pre><p>所以 Data-Driven 的想法變成兩部分，先記憶所有資料及其對應的標籤，在測試時找到訓練集中最像的照片，則預測為同一類。此概念即是 1-Nearest Neighbors 的作法。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPWhDQbVkQcWiVARg93OeQ.png" /><figcaption>K-Nearest Neighbors, K=1 的結果。</figcaption></figure><p>想像每張圖片在高維空間上成為一點，而顏色代表他的類別，則可以看到每個位置將會被預測為哪一類。但 K=1 時，表示參考的圖片僅有一張，因此很容易會因為雜訊而誤判，如同上圖中綠色區域裡的黃色點，或崎嶇的紅藍邊界。所以增加參考的點數會讓模型更可以抗雜訊。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HM1AAkef30EHUQa6QM0xWg.png" /><figcaption>結果則由最近幾個參考點來表決。K=5 時，結果相對其他兩者，邊界更平滑。</figcaption></figure><p>但也並非 K 越大就越好，因為 K 越大，則可能選定的參考點是有一定距離，就沒有參考價值了。</p><p>另外的問題是，應該如何判斷兩張照片的相似程度？最簡單的想法是計算每個像素點間的 L1 或 L2 norm。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ai0Uvh8UZvlc1yK73N8rZA.png" /><figcaption>（K=1 時）L1 distance 較容易會有垂直以及水平的邊界線，對於 L2 distance邊界則為兩兩中垂線構成。</figcaption></figure><p>對於如何選擇 K 以及 distance metric，是相當依賴所要解決的問題，也就是資料集以及識別的種類。</p><p>通常調整要決定的超參數會有以下的做法：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NC6CvV2c-6-aBvVZr9owQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_EUUdiBehPQoK-N04Fo9A.png" /><figcaption>調整超參數的想法，應如何切分資料集</figcaption></figure><ol><li>將所有資料去做訓練，則以 K-nearest neighbor方法，選用 K=1 必定會有最小的誤差；而以其他方法也無法驗證模型的好壞，可能已產生過擬合的情況卻無法發覺。</li><li>將資料集切分成訓練集(train set)及測試集(test set)，並以測試集的結果調整超參數，則無法判定模型的好壞（因為是以有答案的測試集去調整模型）。</li><li>將資料集切分成訓練集(train set)、驗證集(validation set)及測試集(test set)，並以驗證集的結果調整超參數，再以測試集來評估模型的好壞，對於整個流程是最完整的想法。</li><li>將資料切成好幾等份以及測試集，以前面輪流一份作為驗證集，其餘為訓練集，最後平均結果。此方法避免太依賴其中一份驗證集的資料去作調參，但對於龐大資料集的訓練並非是一件有效率的事。</li></ol><p>實際上，在做影像辨識時並不會用使用 K-Nearest Neighbor 的算法，因為衡量相似程度時，通常是以 L1 或 L2 norm 去計算之間的差距。但有相同的誤差值，卻可能對於影像有很大的不同。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFA_8XI4hGggSpJEk4GRmw.png" /><figcaption>遮罩、平移或改變色調，可能得到相同的的 L2 distance</figcaption></figure><p>另一個原因是，在高維度空間中，若要有好的結果，就必須要有密布整個空間的資料點，這樣最近的點才具有參考性。但往往很難拿到如此大量的影像資料。</p><p>還有什麼方法可以做影像辨識呢？下面會從最簡單的 Linear model 講起。</p><h4>Linear Classification</h4><p>線性的分類器是類神經網路的基礎，其想法很簡單，透過一個線性函數得到分別屬於各個類別的分數。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjmEsty7mwVXUy69NApq7g.png" /><figcaption>影像作為 x 輸入，透過權重 W 以及偏差 b 得到各個類別的分數</figcaption></figure><p>實際作法是將影像拉成一條向量，再與權重 W 做矩陣乘法，得到的便是對應各個類別的分數。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKCd9YOsDagmu8vonQFhuA.png" /></figure><p>從矩陣乘法的操作可以看到，權重 W 第 n 列 (row) 的數值會決定第 n 個類別的分數，每個值對應的也是影像中每個像素的權重。為了解釋 W 所看重的區域，可以將列向量重新排列至與影像相同的形狀。下圖則為在資料集 CIFAR-10 上所看到的權重圖。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOynC0zwl64xneKCodZnXQ.png" /><figcaption>W 所顯示的有些能隱約看出各類別的特徵</figcaption></figure><p>找到的線性函數則可在高維空間成一個高維平面，透過這個平面去切割空間，判定各個點所屬的類別為何。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuapVdDOVkSdPoP5dRZbqw.png" /></figure><p>但是通常資料的分布成非線性，以線性分類器來說就無法很好地逼近每個類別的界線。還有另一個問題是，如何判斷權重是好是壞？下一課則會說明如何評估模型的好壞以及如何找到好的權重值。</p><p>影片位址： <a href="https://www.youtube.com/watch?v=OoUX-nOEjG0&amp;list=PL3FW7Lu3i5JvHM8ljYj-zLfQRF3EO8sYv&amp;index=2">Lecture 2: Image Classification pipeline</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c11944a3891" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-academy-taiwan/notes-on-cs231n-convolutional-neural-networks-for-visual-recognition-part-i-7c11944a3891">Notes on CS231n: Convolutional Neural Networks for Visual Recognition Part I</a> was originally published in <a href="https://medium.com/ai-academy-taiwan">Taiwan AI Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering method 7]]></title>
            <link>https://medium.com/ai-academy-taiwan/clustering-method-7-fc4c9dd9575b?source=rss-9c0bd00b9012------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc4c9dd9575b</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[clustering-algorithm]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yuki Liu]]></dc:creator>
            <pubDate>Tue, 29 Oct 2019 09:01:02 GMT</pubDate>
            <atom:updated>2019-10-29T09:01:02.238Z</atom:updated>
            <content:encoded><![CDATA[<h4>BIRCH（Balanced Iterative Reducing and Clustering using Hierarchies）</h4><p>之前提及過階層式分群法依據定義的兩資料點間的距離來做切割或聚合，但每階層都須重新計算所有資料點間的距離關係，才能進行近一步的處理。然而，BIRCH 的算法記錄每群的群聚特徵，以便進行分群並達到減少計算量的效果。此算法也是一種增量的分群方法，意即每一次的決策是基於當前已處理過的資料點來做決定。</p><p>以下將會介紹此算法如何轉換成便於分群的特徵以及其分群的依據，也提供相同的範例以便進行比較。</p><h3>－ 基本概念 －</h3><p>BIRCH 算法的主要概念是，依據每群資料點集合的群聚特徵（Clustering Feature, CF）建構聚類特徵樹（Clustering Feature-Tree, CF Tree），直接對此特徵進行分群，因此只須看過一次資料集即可進行分群。然而群聚特徵以及聚類特徵樹會在下面一一說明。</p><h4><strong>群聚特徵（Clustering Feature, CF）</strong></h4><p><em>CF =（N, LS, SS）</em>，每群的特徵以三個維度表示，分別為資料點集合的個數<em>N</em>，所有資料點的和 <em>LS</em>，以及所有資料點的平方和 <em>SS</em>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*ysBQoLHov0smxOsIj64b9g.png" /><figcaption>LS 為資料點的和， SS 則為資料點的平方和。</figcaption></figure><p>此種表示每群的特徵有計算上的好處，對於不相交的兩群合併，<em>CF</em> 有可加性。因此針對一個群僅需保留一個 <em>CF</em> 的信息，以減少儲存空間，而分群的決策也是依據此特徵去做運算。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*bUbSbfOt8WhkyxaJDp2DmA.png" /><figcaption>CF 可加性定理</figcaption></figure><h4><strong>度量方法（metric）</strong></h4><p>若 <em>N</em> 個資料點 <em>X_i , i=1, …, N</em>，表達每個群的基本量有</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GV243bKZtokYT_uAJNfb_g.png" /><figcaption>半徑 (R) 及直徑 (D) 為測量靠近中心點的密集程度</figcaption></figure><p>若兩群資料點分別為 <em>x_i , i=1, …, N_1</em>，<em>x_j , j=1, …, N_2</em>，則兩群間的距離有下列幾種測量方式</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*RtpEuuJnh2FEtK_EfVoODQ.png" /><figcaption>兩群 (clusters) 間的距離測量方式</figcaption></figure><h4><strong>聚類特徵樹（Clustering Feature Tree, CF Tree）</strong></h4><p>每群的特性由 Clustering Feature 去表示，而樹的節點由好幾群去長成，然而樹的深度以及寬度由三個參數決定，分別是</p><ol><li>非葉子節點（Non-leaf Nodes）可容納最大的子群數 <em>B</em>（最大 CF 數）。</li><li>葉子節點（Leaf Nodes）可容納最大的子群數<em> L</em>（最大 CF 數）。</li><li>葉子節點每群最大半徑 <em>T</em>，意即群中的所有資料點將落在半徑為 <em>T</em> 的超球體內。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zldNVGEiJ03qH08q0eBQAg.png" /><figcaption>此 Clustering Feature-Tree 參數設定為 B = 6, L = 5, T</figcaption></figure><p>聚類特徵樹（Clustering Feature Tree）的生成，可由以下步驟去建構：</p><ol><li>選擇跟節點（Root），初始由資料集中處理的第一點擔任。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*6NPMED-HtSy0RzKVlkbUDQ.png" /><figcaption>p1 為初始的根結點，此時 CF1 = (1, LS1, SS1)</figcaption></figure><p>2. 從根節點向下搜尋，根據選擇的度量方法判斷距離最近的群。若距離此群在 <em>T </em>以內，則合併群。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*bfD_96u_wYnEZghJlrkA6Q.png" /><figcaption>若距離小於T則合併成同一群，因此 p2 合併至 p1 內，而更新後的 CF1=(2, LS1&#39;, SS1&#39;)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*u9seudPHOR8i2HRR_eD_LA.png" /><figcaption>若距離大於 T，則另成新的一群，因此在根節點下有兩個 CF，分別為 CF1=(2, LS1&#39;, SS1&#39;), CF2=(1, LS2, SS2)</figcaption></figure><p>3. 若群數大於葉子節點的所能容納的數目（<em>L</em>），則分裂節點。由距離最遠的兩個群做為種子，剩下的群則重新分配，與最近的群分在同一個葉子節點下。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*S_NFALikLH8pvILur2csyQ.png" /><figcaption>若 L=2，且新資料點 p4 距離 CF1 及 CF2 皆大於 T，則需分裂節點。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0spe2VvMHVEL2xUHVBN0uA.png" /><figcaption>假設 CF1_1 與 CF2_1 為最遠的群，且CF1_2 與 CF1_1 距離最近，則重新分配的結果為上。</figcaption></figure><p>4. 持續處理下一個新資料點，若葉子節點數目大於所能容納的非葉子節點數（<em>B</em>），則進行分裂，與上述方法相同。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdsjsCmJm_iGnJ6y79CrOQ.png" /><figcaption>新資料點 p5 與 Leaf Node 1 的 距離較近，但因設定的參數 L = 2，所以需進行分裂</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDHJVAWOfjZHhT77S9avNw.png" /><figcaption>Leaf Node 1分裂為兩個 Leaf Nodes。若 B = 2，則節點需再進行分裂。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rycwS8c63rTygQx0fktdg.png" /><figcaption>若 Leaf Node 的數目超過可容納的最大值（B=2），則需要重新分配節點，結果如左圖。右圖為上下連結關係圖。</figcaption></figure><p>（命名方式為容易看出節點上下關係，因此有所變動，但實際上在重新分配時，僅更改指標方向而已。）</p><p>總結以上過程，插入CF Tree 新節點即是以下的迭代步驟：</p><ol><li>從根節點向下尋找與新資料點距離最近的群（葉子節點內的 CF 節點）。</li><li>若新資料點加入後，此群後半徑不超過所定的閾值 <em>T</em>，則加入資料點並更新所有影響的 <em>CF</em> 值。</li><li>若當前節點內包含的 CF 節點數小於 <em>L</em>，則創建 CF；若大於 <em>L</em>，則以最遠兩個節點作為種子分裂成兩節點，其餘分配至最近的節點中，並更新所有的 <em>CF</em> 值。</li><li>若非葉子節點數目大於 <em>B</em>，則以最遠兩個子節點做為種子分裂成兩節點，其餘分配至最近的節點中，並更新所有的 <em>CF</em> 值。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAB3I41WhBVOdH6h-eorlw.png" /><figcaption>建構聚類特徵樹（Clustering Feature Tree）流程圖</figcaption></figure><p>藉由設定的參數以及定義的距離關係即可建構聚類特徵樹（Clustering Feature Tree），而後續的應用則與階層式分類法相同。</p><h3>－ 演算法 －</h3><ul><li>輸入：資料集 <em>D</em>，建構聚類特徵樹參數 <em>B</em>（非葉子節點可容納最大的子群數）、<em>L</em>（葉子節點可容納最大的子群數）、<em>T</em>（葉子節點每群最大半徑），分群數目 <em>k</em>（非必要）以及定義距離 <em>metrics</em></li><li>輸出目標分群集合 <em>Clusters</em></li></ul><ol><li>將所有資料點依次讀入，建構聚類特徵樹（Clustering Feature Tree, CF Tree）（設定 <em>B</em>、<em>L</em>、<em>T</em> 等參數，依照上述步驟建構）。</li><li>去除異常的節點（節點內的資料點很少，可視為異常），與最近的群合併。</li><li>為了消除資料點處理順序所造成的不合理結構，可以利用其他分群演算法進一步的分類，得到較好的 CF Tree。</li><li>利用新的 CF Tree 中所有子群的質心作為起始點，按距離再重新分群。</li></ol><p>對於 BIRCH 算法中最重要的步驟即是建構 CF Tree，其他接續的步驟皆為了對樹的結構做最佳化處理。</p><h3>－ 算法實例 －</h3><p>使用 Sklearn.cluster.Birch 套件：</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.cluster import Birch<br>from sklearn import datasets</pre><pre>#create datasets<br>X,y = datasets.make_blobs(n_samples=50, centers=3, n_features=2, random_state= 20, cluster_std = 1.5)</pre><pre>#parameter setting<br>T = 2 # maximum radius of CF<br>n = 3 # number of clusters (not essential)</pre><pre><strong>#BIRCH method<br>model = Birch(threshold=T, n_clusters = n)<br># If type(n_clusters)=int, then the model is AgglomerativeClustering # with n_clusters</strong></pre><pre><strong>model.fit(X)<br>labels = model.fit_predict(X)<br>c = model.subcluster_labels_</strong></pre><pre>#results visualization<br>plt.figure()<br>plt.scatter(X[:,0], X[:,1], c = labels)<br>plt.scatter(c[:,0], c[:,1], marker=&#39;x&#39;, c=model.subcluster_labels_)<br>plt.axis(&#39;equal&#39;)<br>plt.title(&#39;Prediction&#39;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*724dOfdmVJZdUUan37R-iQ.png" /><figcaption>（標示顏色僅是分群結果，沒有順序性）右圖為 T=2 的結果，’x’為葉子節點的質心。</figcaption></figure><p>若 n_cluster 設為 None，則算法不執行最後一個以 Agglomerative 分群算法去重新分群。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*GtzRodrmwfVEWCIIJV5IKw.png" /><figcaption>右圖算法的 n_clusters 設為 None，則依照 CF Tree 的葉子節點作為分群結果</figcaption></figure><p>用於影像分割…</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from skimage.transform import rescale<br>from sklearn.cluster import Birch<br>import cv2</pre><pre>#load image<br>img = cv2.imread(&#39;AIA.png&#39;)<br>img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>img = rescale(img, 0.2)<br>rows, cols, chs= img.shape</pre><pre>#convert image shape [rows, cols, 3] into [rows*cols, 3]<br>feature_img = np.reshape(img, [-1, 3])</pre><pre>#consider the data without density-dependent factor<br>uni_feature_img, idx = np.unique(feature_img, axis=0, return_inverse = True)</pre><pre>#parameters setting<br>T = 0.01 # maximum radius of CF<br>n = 15   # number of clusters (not essential)</pre><pre><strong>#BIRCH Clustering method<br>model = Birch(threshold=T, n_clusters=n) <br>model.fit(uni_feature_img)<br>labels = model.fit_predict(uni_feature_img)</strong></pre><pre>#results visualization<br>fig = plt.figure(figsize = (20, 12))<br>ax = fig.add_subplot(121)<br>ax1 = fig.add_subplot(122)    <br>    <br>ax.imshow(img)<br>ax1.imshow(np.reshape(labels[idx], [rows, cols]))</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSAuIKgkh_rCo5YMKpsOzA.png" /><figcaption>左圖為原圖，右圖為分割的結果。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtQJbwQzjWH0RbGGQDtzYw.png" /><figcaption>左圖僅顯示被歸為背景藍色的像素，右圖則表示被歸為白色的像素。</figcaption></figure><h3>－ BIRCH 算法總結－</h3><p>優點：</p><ol><li>節省儲存空間，Leaf Nodes 以外的節點僅儲存 Cluster Feature（CF）值以及指向 Child 和 parent 的指標。</li><li>計算速度快，合併兩個群僅需將對應的 CF 值相加，而計算兩群的距離只需 CF 值去判別。</li><li>可辨識雜訊點。包含較少資料點的群視為離群值。</li></ol><p>缺點：</p><ol><li>分群結果依賴資料點的處理順序。</li><li>對於非球狀的分布效果不佳，取決於距離的計算方式（大多與歐式距離去做計算）。</li><li>每個子節點數有經由參數限制，因此得出的分群結果可能與實際的分布情況相差很大。</li></ol><h3>－ 參考資料 －</h3><ul><li>BIRCH 原始論文： Zhang, Tian, Raghu Ramakrishnan, and Miron Livny. “BIRCH: an efficient data clustering method for very large databases.” <em>ACM Sigmod Record</em>. Vol. 25. №2. ACM, 1996.</li><li>相關論文： Zhang, Tian, Raghu Ramakrishnan, and Miron Livny. “BIRCH: A new data clustering algorithm and its applications.” <em>Data Mining and Knowledge Discovery</em> 1.2 (1997): 141–182.</li><li>BIRCH 維基百科： <a href="https://en.wikipedia.org/wiki/BIRCH">https://en.wikipedia.org/wiki/BIRCH</a></li><li>sklearn.cluster.Birch 套件： <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.Birch.html">https://scikit-learn.org/stable/modules/generated/sklearn.cluster.Birch.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc4c9dd9575b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-academy-taiwan/clustering-method-7-fc4c9dd9575b">Clustering method 7</a> was originally published in <a href="https://medium.com/ai-academy-taiwan">Taiwan AI Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering method 6]]></title>
            <link>https://medium.com/ai-academy-taiwan/clustering-method-6-d0c207daced6?source=rss-9c0bd00b9012------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0c207daced6</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[cluster-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Yuki Liu]]></dc:creator>
            <pubDate>Tue, 24 Sep 2019 09:01:01 GMT</pubDate>
            <atom:updated>2019-09-24T09:01:01.652Z</atom:updated>
            <content:encoded><![CDATA[<h4>OPTICS（Ordering points to identify the clustering structure）</h4><p>OPTICS（Ordering points to identify the clustering structure），是一種基於密度的分群方法。與 DBSCAN 非常相似，但此方法解決了 DBSCAN 依賴給定初始參數的特性，OPTICS 改進對初始參數的敏感度。事實上，OPTICS 算法輸出的是一個有序的數列，涵括各樣密度的分群結果，也就是以排序的方式來決定分群的結構。</p><p>以下將會介紹 OPTICS 的基本概念，演算法以及提供相同的範例結果以便與前幾次的分群方法做比較。</p><h3>－ 基本概念 －</h3><p>OPTICS 與 DBSCAN 的輸入參數，以及想法是一樣的。如同先前 DBSCAN 介紹過的名詞 — 核心點、<em>epsilon</em> 鄰域、密度可達、直接密度可達等等。而在 DBSCAN 的基礎之上，OPTICS 引入新的兩個名詞定義，分別是核心距離（core-distance）以及可達距離（reachability-distance）。</p><ul><li>核心距離（core-distance）</li></ul><p>核心距離僅對核心點有定義。核心距離即為最小能包含 <em>MinPts</em> 個資料點的距離，因此可表示為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*RwYvPnRPn1E0HWZqIp-T5w.png" /><figcaption>核心距離（Core Distance）的定義</figcaption></figure><ul><li>可達距離（reachability-distance）</li></ul><p>可達距離的對象僅在核心點上，所以 <em>x</em> 不是核心點就無法定義。可達距離在核心距離內的點都設為核心距離，若在核心距離外則為該點與核心點的距離，因此可達距離表示為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*uz4lIl0ONA8WEY8fELSYRg.png" /><figcaption>可達距離（Reachability Distance）的定義</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*jR4X6ZhDyg1Nxp3VVAxWbg.png" /><figcaption>設MinPts = 5，則核心距離（Core Distance）為 x 到正上方點 y_4 的距離。另外，在核心距離內的點，可達距離皆為核心距離，若超出核心距離則可達距離為該點與核心點的距離。</figcaption></figure><h3>－ 演算法 －</h3><ul><li>輸入：資料集 <em>D</em>，半徑 <em>epsilon</em>，給定點在 <em>epsilon</em> 鄰域內成為核心點的最少點數 <em>MinPts</em>（與 DBSCAN 分群法相同）</li><li>輸出：具有可達距離資訊的資料點序列</li></ul><ol><li>分別建立一有序陣列（存放核心點以及該核心點的直接密度可達點）及一結果序列（排序並作為輸出的結果）</li><li>從資料集選取一未放入結果序列中的核心點（未處理過的核心點）並找到其所有直接密度可達點，若此點未在結果序列則放入有序陣列中並依照可達距離（Reachability-distance）排序</li><li>從有序陣列中取出第一個資料點。判斷是否為核心點，是則依照步驟2. 找齊所有密度可達點並排序；不是則將該點放入結果序列</li><li>直到有序陣列為空</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_MnU14CNUuU_WUdwcM73tw.png" /><figcaption>OPTICS 演算法流程圖</figcaption></figure><p>依照算法得到的結果陣列集為輸出具有可達距離訊息的有序陣列，依照可達距離以及核心距離與選取的半徑關係，即可達到不同的分群結果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmSBcfZh-adDIV5Cr8ISbw.png" /><figcaption>依照給定的半徑輸出分群結果</figcaption></figure><h3>－ 算法實例 －</h3><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.cluster import OPTICS<br>from sklearn import datasets</pre><pre>#create datasets<br>X,y = datasets.make_blobs(n_samples=50, centers=3, n_features=2, random_state= 20, cluster_std = 1.5)</pre><pre>#parameter setting<br>eps = 2<br>MinPts = 5</pre><pre><strong>#OPTICS method<br>model = OPTICS(MinPts, eps=eps, cluster_method=&#39;dbscan&#39;)<br>#Use cluster_method=&#39;dbscan&#39; to compare with DBSCAN method <br>model.fit(X)<br>labels = model.fit_predict(X</strong>)</pre><pre>#results visualization<br>plt.figure()<br>plt.scatter(X[:,0], X[:,1], c = labels)<br>plt.axis(&#39;equal&#39;)<br>plt.title(&#39;Prediction&#39;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*mIRyet_aZTVdUhACNni4qA.png" /><figcaption>（標示顏色僅是分群結果，沒有順序性）右圖為 epsilon=2 的結果</figcaption></figure><pre>plt.figure(figsize = (15, 10))<br>plt.axis(&#39;equal&#39;)</pre><pre># plot all data<br>plt.scatter(X[:,0], X[:,1], c = labels)</pre><pre># rearrange the order of data<br>X_all = X[order,:]<br>seq_labels = labels[model.ordering_]</pre><pre>for classes in range(3):<br>    class_idx = seq_labels == classes<br>    class_X = X_all[class_idx,:]<br>    plt.plot(class_X[:,0], class_X[:,1])</pre><pre>    for i in range(class_idx.sum()):<br>        point = class_X[i,:]<br>        plt.text(point[0], point[1], str(i))</pre><pre>plt.title(&#39;Ordering&#39;)<br>plt.xlabel(&#39;x&#39;)<br>plt.ylabel(&#39;y&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*z8PuT7iUGxkhvzPVSFsPUg.png" /><figcaption>此圖為同一群中資料點的排序，紫色點則為雜訊點</figcaption></figure><pre>from matplotlib import cm<br>plt.figure(figsize = (15, 10))</pre><pre>for klass, color in zip(range(0, class_num-1), colors):<br>    Xk = space[seq_labels == klass]<br>    Rk = reachability[seq_labels == klass]<br>    print(klass, cm.get_cmap(&#39;viridis&#39;)((klass+1)/4)[:3])<br>    plt.scatter(Xk, Rk, c = cm.get_cmap(&#39;viridis&#39;)((klass+1)/3)[:3], alpha=1)</pre><pre>plt.scatter(space[seq_labels == -1], reachability[seq_labels == -1], c = cm.get_cmap(&#39;viridis&#39;)(0)[:3])<br>plt.plot(space, np.full_like(space, 2., dtype=float), &#39;k-&#39;, alpha=0.5)<br>plt.plot(space, np.full_like(space, 0., dtype=float), &#39;k-.&#39;, alpha=0.5)</pre><pre>plt.axis(&#39;equal&#39;)<br>plt.ylabel(&#39;Reachability (epsilon distance)&#39;)<br>plt.title(&#39;Reachability Plot&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kte-Ho-VIy1OmwaR2qIk2A.png" /><figcaption>輸出的有序陣列（具有可達距離資訊的資料點序列）。X 軸為 OPTICS 算法處理資料點的順序，Y 軸表示其可達距離。實線為 epsilon = 2 的閾值。</figcaption></figure><p>設定 epsilon=2.5，其結果為 ...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Pydot_E9OSSp8mbZOQSBg.png" /><figcaption>輸出的有序陣列（具有可達距離資訊的資料點序列）。X 軸為 OPTICS 算法處理資料點的順序，Y 軸表示其可達距離。實線為 epsilon = 2.5 的閾值。</figcaption></figure><p>用於影像分割</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from skimage.transform import rescale<br>from sklearn.cluster import OPTICS<br>import cv2</pre><pre>#load image<br>img = cv2.imread(&#39;AIA.png&#39;)<br>img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>img = rescale(img, 0.2)<br>rows, cols, chs= img.shape</pre><pre>#convert image shape [rows, cols, 3] into [rows*cols, 3]<br>feature_img = np.reshape(img, [-1, 3])</pre><pre>#parameter setting<br>eps = 0.02<br>MinPts = 50</pre><pre><strong>#OPTICS method<br>optics = OPTICS(MinPts, max_eps=eps, cluster_method=&#39;dbscan&#39;)<br>#Use cluster_method=&#39;dbscan&#39; to compare with DBSCAN method<br>optics.fit(feature_img)<br>labels = optics.labels_</strong></pre><pre>#results visualization<br>fig = plt.figure(figsize = (20, 12))<br>ax = fig.add_subplot(121)<br>ax1 = fig.add_subplot(122)    <br>    <br>ax.imshow(img)<br>ax1.imshow(np.reshape(labels, [rows, cols]))</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JjswEyRnLvrUJAzmNMl2g.png" /><figcaption>左圖為原圖，右圖為分割的結果。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0v3aYxmAGOBIn2a9k-wSyA.png" /><figcaption>左圖僅顯示被歸為背景藍色的像素，右圖則表示被歸為白色的像素。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOLhmLzCI4xiTnEDhR56gg.png" /><figcaption>輸出的有序陣列（具有可達距離資訊的資料點序列）。X 軸為 OPTICS 算法處理資料點的順序，Y 軸表示其可達距離。實線為 epsilon = 0.02 的閾值。</figcaption></figure><p>雖說 OPTICS 不需要 <em>epsilon</em>，但算法中依舊需輸入參數 <em>epsilon</em> 及 <em>MinPts</em>，因為參數對分群結果有輔助作用，並不會影響到資料點的相對輸出順序。</p><p>基於密度的分群算法必須確定那些點是核心點以及雜訊點，就需要有 <em>epsilon</em>的輔助。雖給定 <em>epsilon</em>，但算法輸出的資料點順序並不會因不同的 <em>epsilon</em>而有所改變。然而算法會依據 <em>epsilon</em> 去決定核心點，因此核心距離以及可達距離就會有倍數上的差別，造成選用相同的 <em>epsilon</em>，在 OPTICS 算法與 DBSCAN 算法上有些微的落差。</p><h3>－ OPTICS 算法總結－</h3><p>OPTICS 為 DBSCAN 的擴展算法，以下列出相對於 DBSCAN 改進的部分。</p><p>優點：</p><ol><li>此算法相對 DBSCAN 而言，對參數的選定較不敏感。</li><li>輸出為一有序陣列，容易依照給定的 <em>epsilon</em> 而改變分群的結果，不須重新以不同的 <em>epsilon</em> 作為輸入執行分群演算法。</li></ol><h3>－ 參考資料 －</h3><ul><li>OPTICS 原始論文： <em>Ankerst, Mihael, et al. “OPTICS: ordering points to identify the clustering structure.” ACM Sigmod record. Vol. 28. №2. ACM, 1999.</em></li><li>OPTICS 維基百科： <a href="https://en.wikipedia.org/wiki/OPTICS_algorithm">https://en.wikipedia.org/wiki/OPTICS_algorithm</a></li><li>sklearn.cluster.OPTICS套件：<a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.OPTICS.html">https://scikit-learn.org/stable/modules/generated/sklearn.cluster.OPTICS.html</a></li><li>DBSCAN 原始論文： <a href="http://www.aaai.org/Papers/KDD/1996/KDD96-037.pdf"><em>Ester, Martin, et al. “A density-based algorithm for discovering clusters in large spatial databases with noise.” Kdd. Vol. 96. №34. 1996.</em></a></li><li>DBSCAN維基百科：<a href="https://en.wikipedia.org/wiki/DBSCAN">https://en.wikipedia.org/wiki/DBSCAN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0c207daced6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-academy-taiwan/clustering-method-6-d0c207daced6">Clustering method 6</a> was originally published in <a href="https://medium.com/ai-academy-taiwan">Taiwan AI Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering method 5]]></title>
            <link>https://medium.com/ai-academy-taiwan/clustering-method-5-88c109369fa8?source=rss-9c0bd00b9012------2</link>
            <guid isPermaLink="false">https://medium.com/p/88c109369fa8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[affinity-propagation]]></category>
            <category><![CDATA[cluster-analysis]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Yuki Liu]]></dc:creator>
            <pubDate>Fri, 19 Jul 2019 04:16:15 GMT</pubDate>
            <atom:updated>2021-03-30T10:56:57.054Z</atom:updated>
            <content:encoded><![CDATA[<h4>Affinity Propagation</h4><p>這次要介紹的鄰近傳播分群法（Affinity Propagation）分群方法與最常使用的K-means是基於一樣的 Similarity matrix，也就是以定義的距離來作分群，但此種方法加入了數據間傳遞信息的想法，因此計算複雜度也較高，但能得到較好的平方誤差。常使用在生物基因的分群、文句的提取等等。</p><p>以下將會介紹鄰近傳播分群法的基本概念以及會使用到的名詞解釋，依舊以相同例子的結果來比較各種分群法的差異。</p><h3>－ 基本概念 －</h3><p>鄰近傳播分群法（Affinity Propagation）是一種基於資料點間信息傳遞的分群算法。依據點間的相似度（Similarity）傳遞所需的消息，進而計算出各點的分群中心。過程中所傳遞的信息分別是吸引度（Responsibility）和歸屬度（Availability）。透過不斷更新此兩種訊息，產生較好的分群中心（Exemplar）得以將資料及分群。</p><ul><li>相似度（Similarity）</li></ul><p>資料點間的相似度一般以點間的距離來計算，距離越近則表示相似度越高，意即</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*OrsdlmlOaTxfq46pMlikHQ.png" /><figcaption>S(i, j) 即為資料點 x_i<strong> </strong>及 x_j 之間的相似程度</figcaption></figure><p>同時相似度也表明 <em>x_j</em> 作為 <em>x_i</em> 的分群中心的適合程度（因為相似度越高，越容易分為同一群）。</p><ul><li>參考度（Preference）</li></ul><p>指的是資料點作為分群中心的參考度，也就是可作為分群中心的適合程度。一般取相似度的中間值作為參考度並取代相似度矩陣的對角值。</p><p>因此可以解釋相似度矩陣的元素 <em>S(i, j)</em><strong><em> </em></strong>指的是 <em>x_i</em><strong><em> </em></strong>選定 <em>x_j</em><strong> </strong>為分群中心的偏好程度。</p><ul><li>吸引度（Responsibility）</li></ul><p>若以 <em>R(i, k)</em> 來表示吸引度，稱資料點 <em>x_k</em> 吸引資料點 <em>x_i</em> 作為分群中心的程度。</p><ul><li>歸屬度（Availability）</li></ul><p>若以 <em>A(i, k)</em> 來表示歸屬度，稱資料點 <em>x_i</em> 選擇資料點 <em>x_k</em> 作為分群中心的適合程度。</p><p>因此吸引度及歸屬度對於給定資料點與某欲作為分群中心的資料點間的關係為：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*x8O-YgGuke17ZSCiHjgwog.png" /><figcaption>X_i（該資料點） 與 X_k（欲作為分群中心的資料點）之間的關係</figcaption></figure><p>此算法即是不斷更新吸引度以及歸屬度來找到對每個資料點最適合的分群中心。迭代更新的過程如下：</p><p>1. <em>x_k</em> 若要吸引 <em>x_i</em> 做為它的分群中心，必須要跟 <em>x_i </em>有足夠高的相似程度（<em>S(i, k)</em>），並且證明比其他點更適合作為分群的中心，也就是 <em>x_i</em> 認可其他點 <em>x_k&#39;</em> 的程度（<em>A(i, k)</em>）以及 <em>x_k&#39;</em> 作為 <em>x_i</em> 的分群中心的合適度（<em>S(i, k’)</em>）要比對 <em>x_k</em> 的來得低。因此更新吸引度 <em>R(i, k) </em>的方式為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*F-eP_3sZPq6NfgrE3V5MbQ.png" /><figcaption>更新吸引度（Responsibility）的方法</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*IB2ZhuzzPGJyc_k2DECscA.png" /><figcaption>R(i, k)為 x_k 比其他資料點更吸引 x_i 的程度</figcaption></figure><p>2. 若 <em>x_k</em> 吸引<em>x_i</em>以外的資料點，<em>x_i</em> 也容易選擇 <em>x_k</em> 作為其分群中心。因此 <em>x_k</em> 對其他點 <em>x_i&#39;</em> 的吸引度（<em>R(i’, k)</em>）表示它成為其他點 <em>x_i&#39;</em> 的分群中心有多適合。<em>R(k, k) </em>則表示 <em>x_k </em>自己不適合其他點的程度。最後綜合兩種考慮的想法則能表示歸屬度 <em>A(i, k) </em>為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*EMPfhFd_sgp5RcmBciwQwA.png" /><figcaption>更新歸屬度（Availability）的方法</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*SVcWafjy5WsUETi4_UtFzg.png" /><figcaption>A(i, k) 表示 X_i 選擇 X_k 作為分群中心的適合程度（所以 X_i 會根據其他點的看法來決定是否選擇 X_k，也就是 X_k 有沒有能力作為分群中心）</figcaption></figure><p>可以想像吸引度（Responsibility）是比較分群中心的適合程度，則歸屬度（Availability）是找出較適合成為分群中心的資料點。</p><h3>－ 演算法 －</h3><p>輸入：資料集 <em>D</em>，參考度 <em>preference</em>。</p><p>輸出：目標分群集合 <em>Clusters</em></p><ol><li>根據資料集 <em>D </em>計算相似度矩陣 <em>S</em>，將 <em>S</em> 對角線上的元素設為給定的參考度 <em>preference</em>，即是 <em>S(i, i) = preference </em>。</li><li>初始化吸引度 <em>R</em> 以及歸屬度 <em>A</em> 為 0 矩陣。</li><li>更新個資料點間的吸引度。</li><li>更新個資料點間的歸屬度。</li><li>對資料點 <em>d_i </em>來說<em>，</em>分群中心 <em>Exemplar </em>即為 <em>argmax{A(i, k)+R(i, k)} </em>。</li><li>重複步驟 3. 4. 5. 直到所有資料點所屬的分群中心不再改變為止。</li></ol><h3>－ 算法實作 －</h3><p>使用Sklearn.cluster.AffinityPropagation套件：</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.cluster import AffinityPropagation<br>from sklearn import datasets<br>from sklearn.metrics import pairwise_distances</pre><pre>#create datasets<br>X,y = datasets.make_blobs(n_samples=50, centers=3, n_features=2, random_state= 20, cluster_std = 1.5)</pre><pre>#parameter setting<br>S = -np.square(pairwise_distances(X)) #Affinity matrix<br>prefer = np.mean(S) #set preference value</pre><pre><strong>#Affinity Propagation method<br>model = AffinityPropagation(preference = </strong>prefer<strong>)<br>model.fit(X)<br>labels = model.fit_predict(X)<br>cluster_center = model.cluster_centers_</strong></pre><pre>#results visualization<br>plt.figure()<br>plt.scatter(X[:,0], X[:,1], c = labels)<br>plt.scatter(cluster_center[:,0], cluster_center[:,1], c = &#39;r&#39;)<br>plt.axis(&#39;equal&#39;)<br>plt.title(&#39;Prediction&#39;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4r41pgNlwrLLlp6uT-UEQ.png" /><figcaption>左圖為原始資料集，右圖則為Affinity Propagation分群的結果（紅色點為分群中心）</figcaption></figure><p>用於影像分割 …</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from skimage.transform import rescale<br>from sklearn.cluster import AffinityPropagation<br>import cv2<br>from sklearn.metrics import pairwise_distances</pre><pre>#load image<br>img = cv2.imread(&#39;AIA.png&#39;)<br>img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>img = rescale(img, 0.2)<br>rows, cols, chs= img.shape</pre><pre>#convert image shape [rows, cols, 3] into [rows*cols, 3]<br>feature_img = np.reshape(img, [-1, 3])</pre><pre>#consider the data without density-dependent factor<br>uni_feature_img, idx = np.unique(feature_img, axis=0, return_inverse = True)</pre><pre>#parameters setting<br>S = -np.square(pairwise_distances(uni_feature_img)) #Affinity matrix<br>prefer = np.mean(S) #set preference value</pre><pre><strong>#</strong>Affinity Propagation<strong> method<br>model = </strong>AffinityPropagation<strong>(preference = prefer) <br>model.fit(uni_feature_img)<br>labels = model.labels_</strong></pre><pre>#results visualization<br>fig = plt.figure(figsize = (20, 12))<br>ax = fig.add_subplot(121)<br>ax1 = fig.add_subplot(122)    <br>    <br>ax.imshow(img)<br>ax1.imshow(np.reshape(labels[idx], [rows, cols]))</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYO0JM-BmEyyA_WAGIswpw.png" /><figcaption>此例僅考慮顏色的因素，並不考慮密度，因此同顏色的像素都將視為同一點。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_yklAKzpuwiIUDf1351vA.png" /><figcaption>左圖僅顯示被歸為背景藍色的像素；右圖則表示被歸為白色系的像素</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*1_WZekUXTMomefEjtl6Nqw.png" /><figcaption>紅色 x 點為 Affinity Propagation 分群法最後的分群中心</figcaption></figure><h3>－ Affinity Propagation 算法總結－</h3><h4>優點：</h4><ol><li>不需要給定分群的個數，且最終的分群中心為原有的資料點。</li><li>此方法較不依賴初始值的選定</li></ol><h4>缺點：</h4><ol><li>此算法雖不須給定分群中心的個數，但所需的參考度（preference）即與分群中心個數有正相關的關係。</li><li>每次迭代都需要更新資料點吸引度（ Responsibility）和歸屬度（ Availability），因此計算複雜度較高。</li></ol><h3>－ 參考資料 －</h3><ul><li>原始論文： Dueck, Delbert, and Brendan J. Frey. “Non-metric affinity propagation for unsupervised image categorization.” <em>2007 IEEE 11th International Conference on Computer Vision</em>. IEEE, 2007.</li><li>Affinity Propagation 維基百科：<a href="https://en.wikipedia.org/wiki/Affinity_propagation">https://en.wikipedia.org/wiki/Affinity_propagation</a></li><li>sklearn.cluster.AffinityPropagation套件：<a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AffinityPropagation.html">https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AffinityPropagation.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88c109369fa8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-academy-taiwan/clustering-method-5-88c109369fa8">Clustering method 5</a> was originally published in <a href="https://medium.com/ai-academy-taiwan">Taiwan AI Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering method 4]]></title>
            <link>https://medium.com/ai-academy-taiwan/clustering-method-4-ed927a5b4377?source=rss-9c0bd00b9012------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed927a5b4377</guid>
            <category><![CDATA[hierarchical-clustering]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[datasci]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Yuki Liu]]></dc:creator>
            <pubDate>Tue, 02 Jul 2019 06:01:01 GMT</pubDate>
            <atom:updated>2019-07-02T06:01:01.346Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hierarchical Clustering — Agglomerative Clustering</h4><p>之前介紹的分群方法都有較複雜的演算過程，此次的階層式分群法（hierarchical clustering）僅需資料點兩兩間的距離，即可達到分群效果，相對容易，但也較依賴定義的距離關係，而有不同的群聚結果。</p><p>以下將會介紹階層式分群法的基本概念以及常見於階層式分群法定義距離的算法，最後亦會用此算法處理相同的例子來比較差異。</p><h3>－ 基本概念 －</h3><p>階層式分群法（hierarchical clustering）即是一種階層架構的方式，將資料反覆分裂或聚合，最後產生目標的分群集合。常見的階層式分群法有兩種：</p><ul><li>聚合（agglomerative）：是一種 “ bottom-up” 的方法，也就是先準備好解決問題可能所需的基本元件或方案，再將這些基本元件組合起來，由小而大最後得到整體。因此在階層式分群法中，就是將每個資料點都視為一個個體，在一一聚合。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cf5uMi2NO5FD6Ki2vVGj4w.png" /><figcaption>由下到上的聚合方式（Agglomerative）</figcaption></figure><ul><li>分裂（divisive）：是一種 “ top-down” 的方法，先對問題有整體的概念，然後再逐步加上細節，最後讓整體的輪廓越來越清楚。而此法在階層式分群法中，先將整個資料集視為一體，再一一的分裂。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1szbtTycnHE_s-BYFwjs5g.png" /><figcaption>由上到下的分裂方式（Divisive）</figcaption></figure><p>此次將會介紹以聚合的方式呈現階層式分群法，而群間的距離演算法會是階層式分群法中最重要的一環，因距離的算法衡量兩群的相似程度，分群也會依據此量測方式來做決策。以下將會有幾種最常見的群間的距離算法：</p><ul><li>單一連結聚合演算法（single-linkage agglomerative algorithm）：群間的距離定義為兩群中最近點的距離。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*mM06A_VwDsmMXwfZFWNPFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*cqCE93Mfjd3mvMAiK1k49A.png" /><figcaption>紅色線的長度即為單一鏈結聚合算法的距離</figcaption></figure><ul><li>完整連結聚合演算法（complete-linkage agglomerative algorithm）：群間的距離定義為兩群中最遠點間的距離。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*XyeMQp5Y14a3RnSgdqUgXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*sBlvPVYyTeWrfr11fIMuYQ.png" /><figcaption>紅色線的長度即為完整鏈結聚合算法的距離</figcaption></figure><ul><li>平均連結聚合演算法（average-linkage agglomerative algorithm）： 群間的距離定義為兩群間各點間的距離總和平均</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*h4XddAGowCtqAhZPYZMfvQ.png" /></figure><ul><li>中心聚合演算法（centroid method）：群間的距離定義為兩群中心點間的距離</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*N6qRCp5Zx21iAA9sKRVXhg.png" /><figcaption>mu_C指的是C集合中的平均值</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*ImaXoMurW2sZ_9eBJhq2uQ.png" /><figcaption>紅色線的長度即為中心聚合算法的距離（藍色點為紫色資料點的中心點，橘色則為綠色資料點的中心點）</figcaption></figure><ul><li>沃德法（Ward’s method）： 群間的距離定義為兩群合併後，各點到合併群中心的距離平方和</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*M8sfIcyIqGoSrXVnbcqKrA.png" /></figure><p>根據上述算法來定義群間的距離，也可視為測量群間的相似性，來合併同質性較高的群，以達到聚合的目的。</p><h3>－ 演算法 －</h3><p>輸入：資料集 <em>D </em>，分群數目 <em>k</em>（非必要）以及定義距離 <em>metrics</em></p><p>輸出：目標分群集合 <em>Clusters</em></p><ol><li>每個資料點都視為一個分群集合 <em>C_i</em>，<em>i = 1, …, n。</em></li><li>利用距離函數 <em>metrics</em> 計算兩兩集合間的距離，並將最近的兩個集合合併為一個新的集合。</li><li>重複步驟 2. 直到分群集合 <em>Clusters</em> 以達到目標分群數目 <em>k</em>（或合併為同一類為止）</li></ol><h3>－ 算法實作 －</h3><p>使用Sklearn.cluster.AgglomerativeClustering套件：</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.cluster import AgglomerativeClustering<br>from sklearn import datasets</pre><pre>#create datasets<br>X,y = datasets.make_blobs(n_samples=50, centers=3, n_features=2, random_state= 20, cluster_std = 1.5)</pre><pre>#parameter setting<br>n = 3 #number of clusters (not essential)</pre><pre><strong>#Agglomerative Clustering method<br>model = AgglomerativeClustering(n_clusters = n, linkage = &#39;ward&#39;)<br>#linkage: [&#39;ward&#39;, &#39;complete&#39;, &#39;average&#39;]<br>model.fit(X)<br>labels = model.fit_predict(X)</strong></pre><pre>#results visualization<br>plt.figure()<br>plt.scatter(X[:,0], X[:,1], c = labels)<br>plt.axis(&#39;equal&#39;)<br>plt.title(&#39;Prediction&#39;)</pre><pre>plt.show()</pre><ul><li>Ward’s method</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PXdq0ml3dNS72NQRynZ8bg.png" /><figcaption>左圖為原始資料集，右圖為階層式分群法利用 “ Ward’s method “ 計算距離的分群結果。</figcaption></figure><ul><li>Complete-linkage agglomerative algorithm</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1XKIewEuBxEJDu95qcR4aQ.png" /><figcaption>左圖為原始資料集，右圖為階層式分群法利用 “ complete-linkage “ 計算距離的分群結果。</figcaption></figure><ul><li>Average-linkage agglomerative algorithm</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adEK-etjSgbpK8ny0GvzMQ.png" /><figcaption>左圖為原始資料集，右圖為階層式分群法利用 “ average-linkage “ 計算距離的分群結果。</figcaption></figure><p>因為有較明顯群聚分布的資料集，選用測量距離的方式對於結果較無差別。也可利用樹狀圖來看分群的策略為何：</p><pre>from scipy.cluster.hierarchy import dendrogram, linkage</pre><pre># Performs hierarchical/agglomerative clustering on X by using &quot;Ward&#39;s method&quot;<br>linkage_matrix = linkage(X, &#39;ward&#39;)</pre><pre>figure = plt.figure(figsize=(7.5, 5))</pre><pre># Plots the dendrogram<br>dendrogram(linkage_matrix, labels = labels)<br>plt.title(&#39;Hierarchical Clustering Dendrogram (Ward)&#39;)<br>plt.xlabel(&#39;sample index&#39;)<br>plt.ylabel(&#39;distance&#39;)<br>plt.tight_layout()<br>plt.show()</pre><ul><li>Ward’s method</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*-PIVb2Qop2Q8rQtV1TaOng.png" /><figcaption>以樹狀圖呈現階層式分群法的分群策略（利用 Ward&#39;s method 聚類）</figcaption></figure><ul><li>Complete-linkage agglomerative algorithm</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*idvzRLFGFaKPQw12q-wtxQ.png" /><figcaption>以樹狀圖呈現階層式分群法的分群策略（利用 Complete-linkage 聚類算法）</figcaption></figure><ul><li>Average-linkage agglomerative algorithm</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*L6cKcW5lUWb4uWBFe0cXlw.png" /><figcaption>以樹狀圖呈現階層式分群法的分群策略（利用 Average-linkage 聚類算法）</figcaption></figure><p>以上三種聚類方法，因為資料集較有群聚的分布，因此大致分類的決策非常相近，僅有些微的不同（對於 “ Ward&#39;s method ＂距離的差距較大， “Average-linkage ＂聚類方式所計算的距離範圍較小，意即三種方法間距離比例的差異）。</p><p>用於影像分割 …</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from skimage.transform import rescale<br>from sklearn.cluster import SpectralClustering<br>import cv2</pre><pre>#load image<br>img = cv2.imread(&#39;AIA.png&#39;)<br>img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>img = rescale(img, 0.2)<br>rows, cols, chs= img.shape</pre><pre>#convert image shape [rows, cols, 3] into [rows*cols, 3]<br>feature_img = np.reshape(img, [-1, 3])</pre><pre>#consider the data without density-dependent factor<br>uni_feature_img, idx = np.unique(feature_img, axis=0, return_inverse = True)</pre><pre>#parameters setting<br>n = 10 #number of clusters (not essential)</pre><pre><strong>#Agglomerative Clustering method<br>model = SpectralClustering(n_clusters = n, linkage = &#39;ward&#39;) <br>#linkage: [&#39;ward&#39;, &#39;complete&#39;, &#39;average&#39;]<br>model.fit(uni_feature_img)<br>labels = model.fit_predict(uni_feature_img)</strong></pre><pre>#results visualization<br>fig = plt.figure(figsize = (20, 12))<br>ax = fig.add_subplot(121)<br>ax1 = fig.add_subplot(122)    <br>    <br>ax.imshow(img)<br>ax1.imshow(np.reshape(labels[idx], [rows, cols]))</pre><pre>plt.show()</pre><ul><li>Ward&#39;s method</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pn_8CH4S7B1YAVrDX-xF-w.png" /><figcaption>利用 “ Ward’s method “ 定義距離，從而得出的分群結果。此例僅考慮顏色的因素，並不考慮密度，因此同顏色的像素都將視為同一點。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LU7HhZxNYciwSXhxYuxBzw.png" /><figcaption>左圖僅顯示被歸為背景藍色的像素；右圖則表示被歸為白色系的像素</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaNM2tSVwwmOaIIkMTQ-Uw.png" /><figcaption>以樹狀圖呈現階層式分群法的分群策略（利用 Ward’s method 聚類）</figcaption></figure><ul><li>Complete-linkage agglomerative algorithm</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMolngk330xT_L9-u1R7fg.png" /><figcaption>利用 “ complete-linkage “ 定義距離，從而得出的分群結果。此例僅考慮顏色的因素，並不考慮密度，因此同顏色的像素都將視為同一點。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RvO02TRfPGo-3sji3F_Ueg.png" /><figcaption>左圖僅顯示被歸為背景藍色的像素；右圖則表示被歸為白色系的像素。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBvP53g-ozz_umDtxNJVYA.png" /><figcaption>以樹狀圖呈現階層式分群法的分群策略（利用 Complete-linkage 聚類算法）</figcaption></figure><ul><li>Average-linkage agglomerative algorithm</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HEa5UtewujKYvpC_t8TnIw.png" /><figcaption>利用 “ average-linkage “ 定義距離，從而得出的分群結果。此例僅考慮顏色的因素，並不考慮密度，因此同顏色的像素都將視為同一點。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXwXNpJVl_lrKbO_OgGPbA.png" /><figcaption>左圖僅顯示被歸為背景藍色的像素；右圖則表示被歸為白色系的像素。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjavIFy8PCiwvRaOVPvZLA.png" /><figcaption>以樹狀圖呈現階層式分群法的分群策略（利用 Average-linkage 聚類算法）</figcaption></figure><p>此例中，每一不同顏色都視為一點，而有較複雜的分布，對於不同的量測距離的方式所做出的聚合決策將會有較大的差異。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*bFcPL7U5a2pQfOVQoq8cyg.png" /><figcaption>影像中，顏色的分布圖。（在影像中的每一種顏色都視為一資料點）</figcaption></figure><p>Complete-linkage 可能會導致大小不一的分群集合產生，相對而言，Ward&#39;s method 可以有較均衡的分群集合，但是僅能使用歐幾里得距離公式才符合假設條件。使用其他距離公式進行分群，並均衡集合大小，則能使用 Average-linkage的方式進行，因此一般較常使用此種方式去量測集合間的距離。</p><h3>－ Hierarchical Clustering 算法總結－</h3><h4>優點：</h4><ol><li>可以使用樹狀結構圖（Dendrogram）來呈現分群的過程。</li><li>僅需要資料點間的距離，便可有分群的結果。</li></ol><h4>缺點：</h4><ol><li>僅適合資料點較少的資料集，難以處理大量的資料，意即計算複雜度較大。</li><li>定義群聚的距離很依賴資料集，而有不同的效果。</li></ol><h3>－ 參考資料 －</h3><ul><li>Hierarchical Clustering 維基百科：<a href="https://en.wikipedia.org/wiki/Hierarchical_clustering">https://en.wikipedia.org/wiki/Hierarchical_clustering</a></li><li>Ward&#39;s method 維基百科：<a href="https://en.wikipedia.org/wiki/Ward%27s_method">https://en.wikipedia.org/wiki/Ward%27s_method</a></li><li>Dendrogram 維基百科：<a href="https://en.wikipedia.org/wiki/Dendrogram">https://en.wikipedia.org/wiki/Dendrogram</a></li><li>Johnson, Stephen C. “Hierarchical clustering schemes.” <em>Psychometrika</em> 32.3 (1967): 241–254.</li><li>sklearn.cluster.AgglomerativeClustering套件：<a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html#sklearn.cluster.AgglomerativeClustering">https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html#sklearn.cluster.AgglomerativeClustering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed927a5b4377" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-academy-taiwan/clustering-method-4-ed927a5b4377">Clustering method 4</a> was originally published in <a href="https://medium.com/ai-academy-taiwan">Taiwan AI Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering method 3]]></title>
            <link>https://medium.com/ai-academy-taiwan/clustering-method-3-879ce60ab0d5?source=rss-9c0bd00b9012------2</link>
            <guid isPermaLink="false">https://medium.com/p/879ce60ab0d5</guid>
            <category><![CDATA[spectral-clustering]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering-algorithm]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Yuki Liu]]></dc:creator>
            <pubDate>Mon, 11 Mar 2019 14:12:42 GMT</pubDate>
            <atom:updated>2019-03-16T02:27:05.315Z</atom:updated>
            <content:encoded><![CDATA[<h4>Spectral Clustering</h4><p>非監督式學習（Unsupervised Learning）的目標是透過不同的方法去擬合資料集，並找到其潛在的分布以便分群或分類。之前已經介紹過基於密度及核密度估計（kernel density estimation，KDE）的分群方法，此篇將會說明另一種基於圖論的分群方法 —— 譜分群（Spectral Clustering）。</p><p>結合圖論的分析，可以將資料點間的關係建構權重圖（weighted graph），也就是將頂點（vertex）作為資料點，邊（edge）則表示資料點間的距離。以下將會介紹如何建構關係圖進而去做分群，以及其演算法和實作。</p><h3><strong><em>－ 基本概念 －</em></strong></h3><p>譜分群的想法是將所有的資料視為空間中的點（vertex），而點與點之間可以邊（edge）相接。而點間的距離較近，便賦予較大的權重；反之，則給予較小的權重。最後，對建構好的圖去做裁切，使得圖間的權重和（weighted sum）盡可能的低，同時讓圖內的權重和盡可能的高，達到分群的效果。</p><h4><strong>圖（graph）</strong></h4><p>基本上，〝圖〞由頂點 <em>V</em>（vertex）及邊 <em>E</em>（edge）構成，即為 <em>G</em>（<em>V, E</em>）。其中 <em>V = </em>｛<em>v_1 , v_2 , … , v_n</em>｝及 <em>E=</em>{<em>e_1, e_2, …, e_m</em>}，<em>e_i ＝</em>｛<em>v_j , v_k</em>｝表示頂點 <em>v_j </em>和頂點 <em>v_k </em>相接。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*BogCrd13yLAk8e62EjaEMQ.jpeg" /></figure><h4><strong>鄰接矩陣（Affinity matrix）</strong></h4><p>除了基本圖的元素，也會透過鄰接矩陣去表示任意兩點間的連接關係。在無權圖（unweighted graph）中，鄰接矩陣被定義為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*8VvpZVcg0yvNqdL7NzUchA.png" /><figcaption>頂點 v_i 和頂點 v_j 有相接則給值 1</figcaption></figure><p>但對於兩點間的關係僅有 1 或 0，並無法表示不同的強度。因此在權重圖（weighted graph）中是利用兩點間的距離去給權重表示連接的強度。其中的想法是距離較遠給低權重，而較近的兩點則給較高的權重。常用的方法是 k 鄰近法及全連接法。</p><ul><li>k 鄰近法是先透過 k-nearest neighbor （KNN）方法篩選兩點間是否要連接，則可定義鄰接矩陣為</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*YsJrJdojvcL12ko0T1WEsA.png" /><figcaption>knn(v_i) 表示與頂點 v_i 最近的 k 個頂點。若頂點 v_i 及頂點 v_j 互不在對方的鄰近區域內，則不連接v_i 和 v_j（給值 0）；反之，以高斯核函數表示權重。</figcaption></figure><ul><li>全連接法則是將所有點連接，以核函數表示點間的距離關係。以下以最常使用的高斯核函數表示鄰接矩陣，可寫成</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*KyyF71wtFtgBeLAV084pew.png" /><figcaption>對所有點間的權重依據核函數去賦予。</figcaption></figure><h4><strong>切圖（Cut）</strong></h4><p>透過鄰接矩陣，則可把兩點間連接的強度一一表示。接下來將圖切割成數個子圖以達到分群的效果。然而，裁切的方式應最小化子圖間的連接關係，同時最大化每個子圖內的連接關係。對於切圖的概念，能以數學式表示為以下的式子</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*ym2Vf7TobUnQ6Hg0y_4_tA.png" /><figcaption>G_i 表示為子圖，G_i^C 為 G_i 的補集（G \ G_i）</figcaption></figure><p>其中子圖間的權重可表示為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*DQ2XaMnw5lLlRtW50MRdDA.png" /></figure><p>因此目標則為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*r9bwj35kUPhhrinhMLyySA.png" /></figure><p>但直接最小化切圖間的連接關係，會導致算法直接對權重和最小的點做裁切。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*sakBYvTd7dIGtbB0FbIWnw.jpeg" /><figcaption>紅色線為直接最小化切圖值的切圖方法，但較好的應該是黃色線</figcaption></figure><p>以下有兩種方法藉由規範每個子圖的大小解決此問題。</p><ul><li><strong>Ratio Cut</strong></li></ul><p><em>RatioCut </em>不僅最小化 <em>Cut</em>（<em>G_1 , G_2 , … , G_k</em>），同時最大化子圖的點數。則可表示為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*lDrMxDQCy9MVVYXCQFr9XA.png" /><figcaption>利用子圖的節點數控制規模（權重）</figcaption></figure><p>對於某個子圖 <em>G_i</em>，</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*rGZ64791DqIkJoxI6F0c1g.png" /></figure><p>令 <em>f_i </em>定義為下，</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*uJRU7zsv-JWx70gM_j6bvA.png" /></figure><p>然而，對每個子圖 <em>G_i</em> 的 <em>RatioCut</em> 則可寫成</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*zo-0MMPGgpt_GbxerNc30w.png" /></figure><p>其中 <em>D</em> 為度矩陣（<strong>degree matrix</strong>），定義其對角元素為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*TFNWU5eFkFRll7J7yABlkA.png" /><figcaption>即為相似矩陣的列總和，組成對角矩陣D</figcaption></figure><p>而 <em>L</em> 則為拉普拉斯矩陣（<strong>Laplacian matrix</strong>），定義如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*Ppyt_2i83puTOGkZKJSkDw.png" /><figcaption>拉普拉斯定義為度矩陣與鄰接矩陣之差</figcaption></figure><p>因此最小化 <em>RatioCut</em> 的值，即為最小化 <em>f ’Lf </em>。</p><p>假設存在 <em>lambda </em>使得</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*qwsTt1YskK552UuH4qUf6g.png" /><figcaption>lambda 即為 L 的特徵值</figcaption></figure><p>同時左乘 <em>f &#39;</em>，則會得到</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*WkqHG0ScoXfWVU3pHFoYZw.png" /></figure><p>也就是說，僅需找到最小的特徵值 <em>lambda </em>對應的特徵向量即可最小化 <em>f &#39;Lf</em>。</p><ul><li><strong>Normalized Cut</strong></li></ul><p>然而，<em>NormalizedCut </em>則是另一種切圖的方法，其算法不僅最小化 <em>Cut</em>（<em>G_1 , G_2 , … , G_k</em>），同時最大化子圖的連接權重值。則可表示為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*mCddSCT-etq4MRRJQDhb9w.png" /></figure><p>找到目標函數的最小值如上述推導，僅在權重上有所改變。而此做法多考慮了距離的因素，為譜分群使用的切圖算法。</p><p>找出的特徵向量如同 PCA 等降維方法一般，但此對應著最佳劃分圖的方法。最終需要再將連續的特徵向量離散化，即為特徵的劃分，進而得到欲達成的分群。</p><h3><strong><em>－ 演算法 －</em></strong></h3><p>輸入：資料集 <em>V </em>，以及分群數目 <em>k</em></p><p>輸出：目標分群集合 <em>Clusters</em></p><ol><li>求出資料點的鄰接矩陣 <em>A</em>（Affinity matrix）。</li><li>對鄰接矩陣 <em>A</em> 的第 <em>i</em> 列加總作為對角矩陣 <em>D</em> 第（<em>i, i</em>）的元素值，並算出矩陣拉普拉斯矩陣 <em>L </em>。</li><li>從矩陣 <em>L </em>中找出對應前 <em>l </em>個特徵值的特徵向量 <em>x_1 , x_2 , … , x_l </em>，並建構 <em>n </em>x <em>l </em>維的矩陣 <em>X = </em>[ <em>x_1 | x_2 | … | x_l </em>]。</li><li>對矩陣 <em>X</em> 的每一列做正規化（<em>R → </em>[<em>0 , 1</em>]），得到 <em>Y</em> 矩陣。</li><li>將矩陣 <em>Y</em> 的每一列做為新資料點（即原資料點降維成 <em>l</em> 維的資料點），透過 K-means 或其他分群方法分成 <em>k</em> 類。</li><li>若 <em>Y</em> 的第 <em>i</em> 列被歸為第 <em>j</em> 類，則原資料點 <em>s_i</em> 即為第 <em>j</em> 類。</li></ol><h3><strong><em>－ 算法實作 －</em></strong></h3><p>使用Sklearn.cluster.MeanShift套件：</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.cluster import SpectralClustering<br>from sklearn import datasets</pre><pre>#create datasets<br>X,y = datasets.make_blobs(n_samples=50, centers=3, n_features=2, random_state= 20, cluster_std = 1.5)</pre><pre>#parameter setting<br>n = 3 #number of clusters</pre><pre><strong>#Spectral Clustering method<br>model = SpectralClustering(n_clusters = n, <br>                           assign_labels = &#39;discretize&#39;)<br>model.fit(X)<br>labels = model.fit_predict(X)</strong></pre><pre>#results visualization<br>plt.figure()<br>plt.scatter(X[:,0], X[:,1], c = labels)<br>plt.axis(&#39;equal&#39;)<br>plt.title(&#39;Prediction&#39;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mINo05Kzz25wXmkUhdOrjA.jpeg" /><figcaption>左圖為原始資料集，右圖為譜分群設定 n = 3 時的結果。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbvOXZkyvuneDdMJP2tXJA.jpeg" /><figcaption>n = 2 時，譜分群就會將距離較近的兩群合為一類。</figcaption></figure><p>用於影像分割 …</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from skimage.transform import rescale<br>from sklearn.cluster import SpectralClustering<br>import cv2</pre><pre>#load image<br>img = cv2.imread(&#39;AIA.png&#39;)<br>img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>img = rescale(img, 0.2)<br>rows, cols, chs= img.shape</pre><pre>#convert image shape [rows, cols, 3] into [rows*cols, 3]<br>feature_img = np.reshape(img, [-1, 3])</pre><pre>#consider the data without density-dependent factor<br>uni_feature_img, idx = np.unique(feature_img, axis=0, return_inverse = True)</pre><pre>#parameters setting<br>n = 15 #number of clusters</pre><pre><strong>#Spectral Clustering method<br></strong>model = SpectralClustering(n_clusters = n, random_state = 40)<br>model.fit(uni_feature_img)<br>labels = model.fit_predict(uni_feature_img)</pre><pre>#results visualization<br>fig = plt.figure(figsize = (20, 12))<br>ax = fig.add_subplot(121)<br>ax1 = fig.add_subplot(122)    <br>    <br>ax.imshow(img)<br>ax1.imshow(np.reshape(labels[idx], [rows, cols]))</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSXjaJBDqp_P_SMiw5YNAg.jpeg" /><figcaption>此例僅考慮顏色的因素，並不考慮密度，因此同顏色的像素都將視為同一點。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyWChbigSNMfznKjY-EO-g.jpeg" /><figcaption>左圖僅顯示被歸為背景藍色的像素；右圖則表示被歸為白色系的像素</figcaption></figure><h3><strong><em>－ Spectral Clustering算法總結－</em></strong></h3><h4>優點：</h4><ol><li>只需要資料點間的相似矩陣，因此對於稀疏資料點的分群有顯著的效果。</li><li>此算法利用拉普拉斯矩陣降維，所以對高維度的資料集的分群計算複雜度相對低。</li></ol><h4>缺點：</h4><ol><li>若降維後的維度依舊很高，則會影響分群的速度也會導致分群的效果不好，因此選擇降維的 k 值尤為重要。</li><li>亦會因為相似矩陣的計算方式得到不同的分群效果。</li></ol><h3><strong><em>－ 參考資料 －</em></strong></h3><ul><li>Spectral Clustering 原始論文： Ng, Andrew Y., Michael I. Jordan, and Yair Weiss. “On spectral clustering: Analysis and an algorithm.” <em>Advances in neural information processing systems</em>. 2002.</li><li>Spectral Clustering 維基百科：<a href="https://en.wikipedia.org/wiki/Spectral_clustering">https://en.wikipedia.org/wiki/Spectral_clustering</a></li><li>Graph 維基百科：<a href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)">https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)</a></li><li>Similarity measure 維基百科：<a href="https://en.wikipedia.org/wiki/Similarity_measure">https://en.wikipedia.org/wiki/Similarity_measure</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=879ce60ab0d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-academy-taiwan/clustering-method-3-879ce60ab0d5">Clustering method 3</a> was originally published in <a href="https://medium.com/ai-academy-taiwan">Taiwan AI Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering method 2]]></title>
            <link>https://medium.com/ai-academy-taiwan/clustering-method-2-cd9bb883a0cb?source=rss-9c0bd00b9012------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd9bb883a0cb</guid>
            <category><![CDATA[mean-shift]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[clustering-algorithm]]></category>
            <dc:creator><![CDATA[Yuki Liu]]></dc:creator>
            <pubDate>Sun, 24 Feb 2019 11:01:00 GMT</pubDate>
            <atom:updated>2019-02-24T11:01:00.807Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mean Shift</h4><p>上一篇介紹了基於密度的分群方法——DBSCAN，此篇會介紹另一個分群方法——Mean Shift，與DBSCAN一樣不需要預先知道欲分群的數目， 而對於分群的形狀也沒有限制。</p><p>然而，此法是基於核密度估計（kernel density estimation）的演算法。可以想像資料是從同一種機率分佈的資料集取樣，而 KDE（kernel density estimation）的方法就是就是去估計資料的分佈情況。Mean Shift 算法在許多領域都有成功的應用，例如圖像分割、物體追蹤等。以下將會詳述此法的基本概念、演算法、以及算法實作。</p><p><strong><em>－ 基本概念 －</em></strong></p><p>Mean Shift 主要的想法是假設資料集的密度以多個合成的核函數分佈，也就是隨核密度分佈，而資料集的所有點只要沿著密度較高的方向移動，直到位於最近最大密度的地方，意即核密度估計曲線的最大值，便能將資料分群。</p><ul><li><strong>核密度估計（kernel density estimation）</strong></li></ul><p>利用核函數（kernel）來擬合資料點 <em>x_1, x_2, … , x_n</em> 的分佈來預估密度的分佈曲線（機率分佈），所以對一個資料點 <em>x</em> 來說，機率的估計可以寫成</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*9C0yxvDCcD_Szqcrjtha_A.jpeg" /></figure><p><em>K </em>為核函數（kernel function），<em>d </em>是維度，<em>h </em>為帶寬（bandwidth）。不同的 <em>h </em>會對核密度估計有很大的影響。太小的<em>h</em>會使得 KDE 的最大值為資料集的所有點（自成一類）；太大則會使最大值只剩一個（分成一類）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*OyAbEJaDoBT9FQquJV2avQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*uexfdiaqAMhB5vYsJirR7g.jpeg" /><figcaption>左圖為資料集；右圖為核密度估計曲線 bandwidth 為 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*IB7gfaXnf00vWKVCgkv7Bw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*4dGSZJXWYFQ5qymJaTVIiw.jpeg" /><figcaption>左圖的帶寬 bandwidth 為 0.05，右圖的帶寬 bandwidth 為 5</figcaption></figure><ul><li><strong>核函數（kernel function）</strong></li></ul><p>核函數一般而言是以零為中心點對稱的函數，表示為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*4h3h4-d1_htN_fQW2k26OA.jpeg" /></figure><p><em>c_{k, d}</em> 是正規化參數，使得函數的積分值為 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*Ps5836sw48lK3JXTc0mMwg.png" /></figure><p>最常見的是高斯函數，定義為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*g1ryTjiJ1zEUKA4S8B8ySg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*KtVFokVXzr3wX0zrkBAZ3Q.png" /><figcaption>常用的核函數（kernel function）。來源：<a href="https://en.wikipedia.org/wiki/Kernel_(statistics)">https://en.wikipedia.org/wiki/Kernel_(statistics)</a></figcaption></figure><p>Mean Shift算法會沿著 KDE 的梯度方向尋找機率最大值，因此考慮</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*itBu7ePVGmGPUZcBmCmIbQ.jpeg" /></figure><p>令 <em>g(s) = -k’(s)</em>，則</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*0-Yre0Q2s8IwFpweNlmfKw.png" /></figure><p>前一項為核函數，後一項則為 mean shift vector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*HwVPG57pI8yjHA_DxZAYfQ.png" /></figure><p>利用迭代的方式更新中心點：</p><ol><li>計算當前的 <em>mean shift vector</em>，也就是 <em>m_h(center_old)</em></li><li>中心點沿著平均偏移向量移動做為新的中心點，意即 <em>center_new = center_old + mean shift。</em></li></ol><p>直到收斂便會找到核密度估計最大值的地方。</p><p><strong><em>－ 演算法 －</em></strong></p><p>輸入：資料集 <em>D</em>，以及帶寬 <em>bandwidth</em></p><p>輸出：目標分群集合 <em>Clusters</em></p><ol><li>從未被分群的資料點中選擇一起始點做為中心。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*lQG9ss3MT8fqwumR5EFoiw.png" /></figure><p>2. 將距離中心點小於 <em>bandwidth </em>的資料點分為同一群，記為集合 <em>M</em> 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*SIcOBrk_M5mf_rUMr_sqsg.png" /><figcaption>紅色點為集合 M 裡的 element</figcaption></figure><p>3. 計算從中心點到集合 <em>M</em> 中每個元素的向量，並做向量平均相加得到平均偏移向量 <em>mean</em> <em>shift vector。</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*AqucmnSUM06WroMHhIQJBA.png" /><figcaption>橘色向量即為 mean shift vector</figcaption></figure><p>4. 中心點沿著平均偏移向量移動做為新的中心點，意即 <em>center = center + mean shift。</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*Y2O9zmGekzN8Kvwq1tt4Mg.png" /><figcaption>橘色點為新的中心點（會往 KDE 的最大值方向移動）</figcaption></figure><p>5. 重複步驟 2、3、4，直到中心點不再更動為止（也就是找到局部極大值）。若此群的中心點已被歸於先前所分的群中，便將兩群合併為同一群。</p><p>6. 重複以上步驟直到所有點都被歸類為止。</p><p><strong><em>－ 算法實作 －</em></strong></p><p>使用Sklearn.cluster.MeanShift套件：</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.cluster import MeanShift, estimate_bandwidth<br>from sklearn import datasets</pre><pre>#create datasets<br>X,y = datasets.make_blobs(n_samples=50, centers=3, n_features=2, random_state= 20, cluster_std = 1.5)</pre><pre>#estimate bandwidth<br>bandwidth = estimate_bandwidth(X, quantile=0.2, n_samples=1000)</pre><pre><strong>#Mean Shift method<br>model = MeanShift(bandwidth = bandwidth, bin_seeding = True)<br>model.fit(X)<br>labels = model.fit_predict(X)</strong></pre><pre>#results visualization<br>plt.figure()<br>plt.scatter(X[:,0], X[:,1], c = labels)<br>plt.axis(&#39;equal&#39;)<br>plt.title(&#39;Prediction&#39;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2SQVayvGnSi61yilY-53A.jpeg" /><figcaption>右圖預測的結果依照bandwidth的選取會有所不同，在此估計bandwidth為 2.92</figcaption></figure><p>用於影像分割 …</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from skimage.transform import rescale<br>from sklearn.cluster import MeanShift, estimate_bandwidth<br>import cv2</pre><pre>#load image<br>img = cv2.imread(&#39;AIA.png&#39;)<br>img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>img = rescale(img, 0.2)<br>rows, cols, chs= img.shape</pre><pre>#convert image shape [rows, cols, 3] into [rows*cols, 3]<br>feature_img = np.reshape(img, [-1, 3])</pre><pre>#estimate bandwidth<br>bandwidth = estimate_bandwidth(feature_img, quantile=0.2, n_samples=1000)</pre><pre><strong>#Mean Shift method<br>model = MeanShift(bandwidth = bandwidth, bin_seeding = True)<br>model.fit(feature_img)<br>labels = model.fit_predict(feature_img)</strong></pre><pre>#results visualization<br>fig = plt.figure(figsize = (20, 12))<br>ax = fig.add_subplot(121)<br>ax1 = fig.add_subplot(122)    <br>    <br>ax.imshow(img)<br>ax1.imshow(np.reshape(labels, [rows, cols]))</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cz_RTS8L9tY8gB6wOrjGQ.jpeg" /><figcaption>左圖為原圖；右圖選用 bandwidth = 0.17 的分割結果（在深灰的部分顏色差異不大被歸為同一類，白色也與淺灰歸為同一類，不易將亮度或色調差異不大的顏色分群）</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jc3-oEOrHExMHFDanRkdow.jpeg" /><figcaption>左圖僅顯示被歸為背景藍色的像素；右圖則表示被歸為白色系的像素（因為灰色系的顏色差異不大，所以被歸為同一類）</figcaption></figure><p>完整程式：<a href="https://gitlab.aiacademy.tw/yuchi/2018December_blog.git">https://gitlab.aiacademy.tw/yuchi/2018December_blog.git</a></p><p><strong><em>－ Mean shift算法總結－</em></strong></p><p>優點：</p><ol><li>此算法與基於距離的分群法不同，可以任意形狀分群（基於距離的算法大多以類似圓形或凸形的形狀分群）。</li><li>不須指定分群的數目。</li><li>可以利用 <em>k-nearest neighbor </em>的方法去估計較適合的參數 <em>bandwidth</em></li></ol><p>缺點：</p><ol><li>計算複雜度為 <em>O( kN ²)</em>，<em>N </em>為資料集大小，<em>k</em>為每個資料點平均迭代的次數。</li><li>對於一些離群值無法找到合適的分群，即無法判別離群值（雜訊）。</li></ol><p><strong><em>－ 參考資料 －</em></strong></p><p>[1] <a href="https://ieeexplore.ieee.org/abstract/document/1055330/"><em>Fukunaga, Keinosuke, and Larry Hostetler. “The estimation of the gradient of a density function, with applications in pattern recognition.” IEEE Transactions on information theory 21.1 (1975): 32–40.</em></a></p><p>[2] <a href="https://ieeexplore.ieee.org/abstract/document/400568/"><em>Cheng, Yizong. “Mean shift, mode seeking, and clustering.” IEEE transactions on pattern analysis and machine intelligence17.8 (1995): 790–799.</em></a></p><p>Mean shift 維基百科：<a href="https://en.wikipedia.org/wiki/Mean_shift">https://en.wikipedia.org/wiki/Mean_shift</a></p><p>Kernel density estimation 維基百科：<a href="https://en.wikipedia.org/wiki/Kernel_density_estimation">https://en.wikipedia.org/wiki/Kernel_density_estimation</a></p><p>Kernel（statistics）維基百科：<a href="https://en.wikipedia.org/wiki/Kernel_(statistics)">https://en.wikipedia.org/wiki/Kernel_(statistics)</a></p><p>sklearn.cluster.MeanShift套件：<a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.MeanShift.html">https://scikit-learn.org/stable/modules/generated/sklearn.cluster.MeanShift.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd9bb883a0cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-academy-taiwan/clustering-method-2-cd9bb883a0cb">Clustering method 2</a> was originally published in <a href="https://medium.com/ai-academy-taiwan">Taiwan AI Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>