<?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 Alex lin on Medium]]></title>
        <description><![CDATA[Stories by Alex lin on Medium]]></description>
        <link>https://medium.com/@SCU.Datascientist?source=rss-a13f3c011379------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BPGDvX0IfhJW9tFT0NUHFQ.jpeg</url>
            <title>Stories by Alex lin on Medium</title>
            <link>https://medium.com/@SCU.Datascientist?source=rss-a13f3c011379------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:46:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SCU.Datascientist/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[一篇文章帶你了解 RAG — 從流程到優化（概念探討）]]></title>
            <link>https://medium.com/@SCU.Datascientist/%E4%B8%80%E7%AF%87%E6%96%87%E7%AB%A0%E5%B8%B6%E4%BD%A0%E4%BA%86%E8%A7%A3-rag-%E5%BE%9E%E6%B5%81%E7%A8%8B%E5%88%B0%E5%84%AA%E5%8C%96-%E6%A6%82%E5%BF%B5%E6%8E%A2%E8%A8%8E-7dcdf67fd424?source=rss-a13f3c011379------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dcdf67fd424</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[evaluate]]></category>
            <category><![CDATA[優化]]></category>
            <category><![CDATA[n8n]]></category>
            <category><![CDATA[llamaindex]]></category>
            <dc:creator><![CDATA[Alex lin]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 04:15:43 GMT</pubDate>
            <atom:updated>2025-11-22T04:15:43.251Z</atom:updated>
            <content:encoded><![CDATA[<h3>一篇文章帶你了解 RAG — 從流程到優化（概念探討）</h3><p>近年來隨著大型語言模型（LLM）的迅速崛起，RAG 這個詞也頻繁出現在各種技術文章與應用討論之中。在還沒接觸前，這陌生的詞彙讓我覺得這是一項高深複雜的技術，但當實際應用後，才發現其原理其實再簡單不過。而且現也有許多開源的工具與平台，讓你就算不寫程式也能實現RAG的問答系統。</p><h3>一、什麼是RAG</h3><p><strong>RAG </strong>的全名為 <strong>Retrieval-Augmented Generation，</strong>從名字就可以看出其核心概念為<strong>資訊檢索 （Retrieval）</strong>與 <strong>AI 生成 （Generation）</strong>，簡單來說，就是讓系統根據使用的提問，去尋找相關的<strong>資訊（context）</strong>，並將這些額外的資訊提供給 AI 模型輔助他們作答。</p><h4>Why use RAG</h4><p>儘管現在的模型一直在進化，並且幾乎可以應用在各個領域上，但是有一些挑戰依然沒解決，主要可以分成 3 個面向</p><ul><li><strong>幻覺（Hallucination）<br></strong>這部分應該是最常遇到的，有時候在使用 LLM 時可以發現他回答了一堆文字，說的好像煞有其事，但仔細閱讀或查證時就會發現它根本在胡說八道，會有這樣的情況是因為 LLM 的生成原理，他會透過<strong>先前生成的 token（詞元）來預測下一個最可能 token，是建立在統計機率上的預測</strong>，因此如果模型的訓練資料中沒有足夠資訊、或生成過程逐漸偏離原始問題，他依然會按照機率生成看似合理的文字</li><li><strong>知識的時效性<br></strong>LLM 畢竟也是使用資料訓練出來的模型，即使訓練資料數以萬計甚至上億，<strong>但他的知識會被「定格」在模型完成訓練的那一刻，就像一個進了監獄的人一樣，對外界（新知識）完全一無所知</strong></li><li><strong>私有知識的存取<br></strong>LLM 訓練用的資料來源多來自網路上，像是各家企業內部的資訊，或是沒有公開的資料，模型完全學習不到，就像你不會知道隔壁鄰居午餐吃什麼，除非他上傳到IG上</li></ul><blockquote>RAG 的出現就是要解決上面的問題，通過給予額外資訊來幫助模型會答得更準確，<strong>就像是給學生課本讓他們看書考試一樣</strong></blockquote><h4>How RAG works</h4><p>當我們在建置 RAG 系統時，可以分成三個階段</p><ul><li><strong>索引階段 (Indexing)<br></strong>在這階段會將原始文件進行<strong>切塊（chunking）</strong>，<strong>轉換成可檢索的格式</strong>，並將這些資料存入<strong>向量資料庫（Vector Database）</strong>或是<strong>記憶體</strong>中，其中會使用到<strong> Embedding model，</strong>這個 <strong>model </strong>會將文字或圖片等格式<strong>轉換成帶有語意的向量（vector）</strong></li><li><strong>索階階段 (Retrieval)<br></strong>當我們擁有自己的<strong>向量資料庫，</strong>就可以在使用者輸入問題時，使用<strong>嵌入模型（embedding model ）將使用者輸入問題向量化</strong>，<strong>並去資料庫檢索相關的資料訊</strong></li><li><strong>生成階段 (Generation)<br></strong>最後我們將這些<strong>檢索</strong>回來的資訊給 LLM 幫助他進行作答</li></ul><p><strong>簡略的流程如下圖</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*RWnaR0HAwqsmfobFPgmK4Q.png" /></figure><p>較多的細節可以參考<strong> Hugging Face </strong>提供的 <strong>RAG 流程</strong>，個人認為是相當完整且清楚</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0F7zvxPYeb8lYKMFZhZJdA.png" /><figcaption><a href="https://huggingface.co/learn/cookbook/advanced_rag">source</a></figcaption></figure><h3><strong>二、如何評估 RAG</strong></h3><p>就如同平常模型的訓練一樣，當我們訓練好一個模型，就需要使用一些指標進行測試，這樣才可以繼續地去優化。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*WPynZAlHBJLOFQ57kzV4dA.png" /><figcaption><a href="https://deepeval.com/guides/guides-rag-triad">source</a></figcaption></figure><p><strong>常見用來評估指標的指標有 3 個其涵蓋了 input、retrieval context、actual output，如上圖</strong></p><ul><li><strong>回答相關性（Answer relevancy）<br></strong>用來衡量<strong>輸入（input）</strong>與<strong>RAG 產生的答案（actual output）</strong>兩者相關性，主要評估 <strong>prompt template </strong>是否能夠指示 <strong>LLM</strong> 根據提示輸出相關且有用的輸出</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*YnGZ9AZTeE1QikMWdob_Jg.png" /></figure><ul><li><strong>忠誠度（Faithfulness）<br></strong>評估 RAG 生成的答案 <strong>是否基於提供的相關上下文（related context）來回答問題</strong>，而不是憑空編造，<strong>可以透過該指標去調整 LLM 超參數</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*lSnRKcuUslHHrLcXGktuHQ.png" /></figure><ul><li><strong>上下文相關性（Contextual Relevancy）<br></strong>用於判斷 <strong>RAG 檢索器（Retriever）</strong>檢索到的<strong>上下文（Context）</strong>是否與使用者輸入生成理想答案相關，<strong>主要關連到 chunk size（索引時文本切分的單位大小）、 top-K （檢索器返回的最相似上下文數量）與 embedding model</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Sry0oRENE2A1hrT5u1mK8Q.png" /></figure><p>另外評估指標還有針對<strong>重排器（Reranker）的 Contextual Precision </strong>與 <strong>嵌入模型（embodding model）的 Contextual Recall</strong>，更多的詳細資訊可以參考<a href="https://deepeval.com/docs/metrics-introduction"><strong>DeepEval</strong></a></p><h3>三、該從哪裡改善 RAG</h3><p>上一節我們了解了如何對 RAG 進行評估，接下來就要看看我們可以從那些環節來改善你的系統，進而提升回答的品質。還記的前面我們使用 3 個階段來建置 RAG 系統嗎，現在就來看看每一個階段可以設定的部分</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*2ARqoMvm1y0PiSJe_2sodw.png" /><figcaption>Indexing</figcaption></figure><h4>索引階段 (Indexing)</h4><p>在這階段我們會對文件進行前處理，將其切分成適當的片段（chunks），並轉換為向量後存入資料庫。</p><p><strong>切塊策略算是這個階段的核心，常見的方式有</strong></p><ul><li>依 <strong>Token 長度</strong>切分</li><li>依<strong>文件結構</strong>（如段落、標題、章節）切分</li><li>依<strong>語意（Semantic）</strong>切分</li></ul><p><strong>切塊的品質會直接影響後續檢索效果</strong></p><ul><li><strong>如果切塊過大</strong>，同一段中可能包含過多無關內容，關鍵語意容易被雜訊稀釋，導致相似度計算不準確。</li><li><strong>如果切塊過小</strong>，一個完整概念可能被拆成多塊，可能會破壞語意連貫性，也可能導致檢索時找不到足夠資訊。</li></ul><p><strong>另外可以注意的還有 embedding model 的選擇、嵌入向量的維度與 meta data的設計等</strong></p><blockquote>如果不確定該如何設計切塊策略，建議一開始可以採用最簡單的做法 ─ 依 Token 長度切分。常用的設定是 <strong>chunk size 1024 tokens、chunk overlap 100~200</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*19FXH0xB1KsmY4sVg02HjQ.png" /><figcaption>Retrival</figcaption></figure><h4><strong>索階階段 (Retrieval)</strong></h4><p>這階段就是要去取得相關的<strong>上下文（context）</strong>給 LLM 進行輔助回答，所以在意的部分會是<strong>檢索回來的資訊是否足以回答使用者的訊息</strong></p><p><strong>個人認為高完成度的檢索流程會是</strong></p><ol><li>先透過<strong>擴展查詢 (Query Expansion) </strong>來改善使用者提問模糊或描述不完整的問題</li><li>再使用<strong>向量相似度（cosine similarity）</strong>搭配<strong>關鍵字模型（BM25）</strong>進行<strong>混和檢索（Hybrid Search）</strong>，這樣可以結<strong>合語意與關鍵字的訊息</strong>來提升返回的上下文品質</li><li>最後使用<strong>重排器（</strong><a href="https://www.google.com/search?sca_esv=6c99d299773109c4&amp;q=Reranker&amp;spell=1&amp;sa=X&amp;ved=2ahUKEwjM9cLG1ISRAxXNdvUHHfxCM-gQBSgAegQICxAB"><strong>Reranker</strong></a><strong>）</strong>來對檢索回來的上下文進行<strong>排序與篩選，</strong>可以過濾掉步一些步驟二檢索回來的的噪音片段，只保留最相關的資訊</li></ol><blockquote>根據筆者經驗，如果只是應用在簡單的場景，其實只需要使用<strong>向量相似度</strong>來進行檢所，<strong>Top-K 設置 5</strong> 就可以有很好的效果，其餘的步驟會增加整體流程運作的時間與複雜度，除非測試下來效果不佳，不然不用搞得這麼繁瑣</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*V_PI7eIjbpglnEirlVdAGA.png" /><figcaption>Generation</figcaption></figure><h4><strong>生成階段 (Generation)</strong></h4><p>這個部分要設定的相較於前面就很單純，可以分成兩項</p><ul><li><strong>LLM Model<br></strong>主要會調整的是<strong>溫度（Temperature）與生成長度（Max Length），</strong>溫度的高低取決於你應用的場景，如果需要穩定的答案，可以設定0~0.3，而生成長度可以防止產生冗長或無關的回應並控製成本</li><li><strong>Prompt Template<br></strong>提示詞是相當的重要，裡面會包含<strong>系統指令 (System Instructions)、檢索上下文 (Retrieved Context)、使用者查詢 (User Query)、輸出格式指示 (Output Format)</strong>等等，個人會使用 Markdown 格式進行撰寫，這樣可以清楚呈現整個架構與邏輯</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*om-ZRLzow5wGWZtm3utGwA.png" /><figcaption><strong>Prompt Template Example</strong></figcaption></figure><h3>四、該選擇 RAG 還是微調（Fine-tuning）</h3><p>以筆者個人使用微調的經驗來看，RAG 的輸出確實比較理想（也可能是我微調的技術不到位），但主要還是要看應用的情境</p><p>通常在企業中使用我還是會以推薦導入 RAG 為主，其入門門檻較低且效果通常可以達到預期，他在<strong>快速更新知識、自訂行為（調整模型的語氣、個性或回應方式）</strong>上的表現我認為是優於微調，但果說你的目標是要<strong>更快的回應、精通某個領域、或針對特定任務進行最佳化，</strong>那微調是不錯的選擇。</p><p>在<a href="https://zhuanlan.zhihu.com/p/1888902823573426902"><strong>吳恩達來信：如何決定是否該進行微調</strong></a>這篇文章中有提到，儘管微調是個重要且有價值的技術，但其實多數的應用都可以使用更簡單方式來達成目標，像是使用 RAG ，或是提示工程的優化，文章的內容我很贊同，也對應到先前說的 <strong>Prompt Template </strong>的設定至關重要</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*1wTDLik4XnW75dlf_SLzPg.jpeg" /><figcaption><a href="https://www.ampcome.com/articles/rag-vs-finetuning-which-is-best-for-your-llm-applications">source</a></figcaption></figure><h3>五、建置RAG系統的相關工具</h3><p>在建置 RAG 的路上也用過不少相關的<strong>工具/平台/框架</strong>，個人覺得不錯的工具如下</p><ul><li><strong>RAG<br>- 工具： </strong>LangChain、LlamaIndex、AnythingLLM、N8N<br>- <strong>比較：</strong>LangChain、LlamaIndex能更好的擴展功能與定義細節，但像是 N8N這樣的 no code 工具，其實在 AI 這塊地支援也很全面，也有整合LangChain 的部分功能。如果說想要立刻體驗RAG的功能，推薦AnythingLLM，他還提供 api 接口</li><li><strong>Vector DB<br>- 工具：</strong>Chroma、pgvector<br>- <strong>比較：</strong>Chroma適合快速本地部屬測試，pgvector 功能較多，像是meta data 能存放陣列，也可以整合 PostgreSQL，查詢上面就很方便</li><li><strong>Synthetic Data<br>- 工具：</strong>easy-dataset<br>- <strong>說明</strong>：開源的一個建立資料集的專案，可以透過 promt template 的設定來產生合成數據，供後續 RAG 測試或是微調訓練用</li><li><strong>Evaluate</strong><br><strong>- 工具：DeepEval<br></strong>- <strong>說明</strong>：評估RAG的套件，可以整合進入LangChain、LlamaIndex，也有提供合成數據</li></ul><blockquote>如果不想寫程式，又想要實現 RAG 應用，我推薦使用 N8N 搭配 pgvector，幾乎可以完成 9 成的任務，在功能擴充方面，N8N也提供 code node，算是進可攻退可守的方案</blockquote><p>感謝你閱讀完這篇文章，如果你覺得文章對你有幫助請給個掌聲，您的掌聲是創作者的動力:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dcdf67fd424" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[函數(Function)]]></title>
            <link>https://medium.com/@SCU.Datascientist/%E5%87%BD%E6%95%B8-function-a70e2589cc60?source=rss-a13f3c011379------2</link>
            <guid isPermaLink="false">https://medium.com/p/a70e2589cc60</guid>
            <category><![CDATA[scopes]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alex lin]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 05:49:46 GMT</pubDate>
            <atom:updated>2025-11-15T11:22:10.116Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>【Python筆記】函數(Function)</strong></h3><blockquote><strong>相關系列文章如下</strong></blockquote><blockquote><strong>基礎<br></strong><a href="https://medium.com/@SCU.Datascientist/python%E7%AD%86%E8%A8%98-%E8%AE%8A%E6%95%B8%E8%A7%A3%E6%9E%90-%E5%91%BD%E5%90%8D%E8%88%87%E5%8F%AF%E8%AE%8A%E7%89%A9%E4%BB%B6%E8%A1%8C%E7%82%BA-9b0b61ad1d92">變數解析 — 命名與可變物件行為</a><br><a href="https://medium.com/@SCU.Datascientist/python%E7%AD%86%E8%A8%98-%E5%9F%BA%E6%9C%AC%E8%B3%87%E6%96%99%E5%9E%8B%E5%88%A5-96b6be59b17c">基本資料型別</a><br><a href="https://medium.com/@SCU.Datascientist/%E5%87%BD%E6%95%B8-function-a70e2589cc60">函數(Function)</a></blockquote><p>在 python 中使用 def 關鍵字來定義一個函數，使用函數可以讓程式碼較好維護與增加可讀性，之後也更容易進行測試</p><p>這裡建立一個函數來計算所有參數的總和，如下</p><pre>def sum_numbers(num1:int, num2:int=5, *args, keyword:int, **kwargs) -&gt; int:<br>    &quot;&quot;&quot;<br>    將所有參數的數字進行總和<br><br>    Args:<br>        num1 (int): 第一個位置參數<br>        num2 (int): 第二個位置參數，預設為5。<br>        *args: 額外位置參數。<br>        keyword: 關鍵字參數，必須指名。<br>        **kwargs: 額外指命參數。<br><br>    Returns:<br>        float: 所有數字的總和。<br>    &quot;&quot;&quot;<br><br>    print(&quot;第一個位置參數:&quot;, num1)<br>    print(&quot;第二個位置參數:&quot;, num2)<br>    print(&quot;任意數量的額外整數位置參數:&quot;, args, &quot;類型&quot;, type(args))<br>    print(&quot;指名參數&quot;, keyword)<br>    print(&quot;額外關鍵字參數:&quot;, kwargs, &quot;類型&quot;, type(kwargs))<br><br>    # 收集所有數字<br>    all_numbers = [num1, num2] + list(args) + [keyword] + list(kwargs.values())<br>    # 計算總和<br>    total = sum(all_numbers)<br> <br>    return total<br><br><br>if __name__ == &quot;__main__&quot;:<br>    result = sum_numbers(1, 2, 3, 4, 5, keyword=10, extra1=100, extra2=200)<br>    print(f&quot;結果: {result}&quot;)<br><br><br># 第一個位置參數: 1<br># 第二個位置參數: 2<br># 任意數量的額外整數位置參數: (3, 4, 5) 類型 &lt;class &#39;tuple&#39;&gt;<br># 指名參數 10<br># 額外關鍵字參數: {&#39;extra1&#39;: 100, &#39;extra2&#39;: 200} 類型 &lt;class &#39;dict&#39;&gt;<br># 結果: 325</pre><h3>一、函數結構</h3><p>一個函數大致可以分成四塊區域，<strong>函數定義與參數、文件字串、主要邏輯與回傳結果</strong></p><h4><strong>1. </strong>函數定義</h4><p>這邊我們會定義函數名稱、輸入參數、預設值等</p><pre>def sum_numbers(num1:int, num2:int=5, *args, keyword:int, **kwargs) -&gt; int:</pre><p>參數的類型依照順序如下</p><ol><li><strong>positional parameters</strong>：按位置順序傳入</li><li><strong>keyword parameters</strong>：透過關鍵字傳入</li><li><strong>*arg</strong>：將額外傳入的 positional parameters 包進 tuple 中</li><li><strong>keyword parameters only</strong>：只能使用關鍵字傳入，放在 *args 後面</li><li><strong>*kwargs</strong>：將額外傳入的 keyword parameters 包進 dict 中</li></ol><h4>2.<strong>文件字串</strong></h4><p>文件字串(Docstring)會用來表示這個函數的<strong>主要用途、參數說明、回傳值或是使用範例</strong>等等，會使用三個雙引號&quot;&quot;&quot;來將文字說明做包覆，另外docstring 會成為該物件的特殊屬性，可以透過呼叫__doc__來查看</p><pre>print(sum_numbers.__doc__)<br><br><br># 將所有參數的數字進行總和<br><br># Args:<br>#     num1 (int): 第一個位置參數<br>#     num2 (int): 第二個位置參數，預設為5。<br>#     *args: 額外位置參數。<br>#     keyword: 關鍵字參數，必須指名。<br>#     **kwargs: 額外指命參數。<br><br># Returns:<br>#     float: 所有數字的總和。</pre><h4>3. <strong>主要邏輯</strong></h4><p>這部分就是實現函數功能的地方，以上面的範例而言，就是計算數字的總和</p><h4>4. <strong>回傳結果</strong></h4><p>每個函數都依定會有回傳結果，如果沒有定義任何回傳值，預設會是None</p><pre>def func():<br>    pass<br><br>result = func()<br>print(result)<br><br># None</pre><h4>二、參數(Parameter) VS 引數(Argument)</h4><p>說到函數，常常會有兩個名詞容易搞混，就是參數與引數，兩者的比較如下</p><ul><li><strong>參數(Parameter)</strong><br>- 說明: 函式「預留位置」的名字，也就是函數定義中的變數名稱</li><li><strong>引數(Argument)</strong><br>- 說明: 實際傳進去的資料，也就是實際在呼叫函式時傳入的值</li></ul><p>簡單來說就是實際函數實際在執行時，引數會將值傳入參數中</p><pre># 定義函數<br>def add(a, b):     &lt;-- a、b 是參數（Parameter）<br><br># 呼叫函數<br>add(10, 20)        &lt;-- 10、20 是引數（Argument）<br><br># 實際運行時，引數會將值傳入參數中<br>a = 10<br>b = 20</pre><h3>三、Python Scope</h3><p>變數的能使用的範圍稱作作用域，在 python 中遵循 LEGB 規則，依照作用域的層級劃分如下</p><ul><li><strong>L — Local<br></strong>說明：函數內的變數，<strong>只供該函數使用</strong>，若需<strong>修改</strong>外層變數，需使用 global或 nonlocal宣告</li><li><strong>E — Enclosing<br></strong>說明：內層函數預設只能<strong>讀取</strong>外層變數，若要<strong>修改</strong>，需使用 nonlocal宣告</li><li><strong>G — Global<br></strong>說明：定義在模組最外層，也就是不在函數內，可以讓整个模組都讀取，但如果要在函數內進行<strong>修改，</strong>需使用 global宣告</li><li><strong>B — Built-in<br></strong>說明：Python 內建的命名空間，包含如 len、print、int</li></ul><p>其查找順序為 L &gt; E &gt; G &gt; B，也就是由內往外去搜尋，如果都沒有找到就會報錯</p><pre>global_x = 0<br>def outer_function():<br>    outer_function_x = 5  # 外層函式的區域變數<br><br>    def inner_function():<br>        nonlocal outer_function_x  # 宣告使用外層函式的區域變數<br>        outer_function_x = &quot;以修改外層函式的區域變數&quot;<br>        global global_x # 宣告使用全域變數<br>        global_x = &quot;以修改全域變數&quot;   <br><br>    inner_function()<br>    print(outer_function_x)<br>    print(global_x)<br><br>outer_function()<br><br># 以修改外層函式的區域變數<br># 以修改全域變數</pre><h3>四、常見陷阱</h3><p>在之前一篇<a href="https://medium.com/@SCU.Datascientist/python%E7%AD%86%E8%A8%98-%E8%AE%8A%E6%95%B8%E8%A7%A3%E6%9E%90-%E5%91%BD%E5%90%8D%E8%88%87%E5%8F%AF%E8%AE%8A%E7%89%A9%E4%BB%B6%E8%A1%8C%E7%82%BA-9b0b61ad1d92"><strong>文章</strong></a>有提到，變數類型可分為「<strong>可變物件 (mutable)</strong>」與「<strong>不可變物件 (immutable)</strong>」，這時如果函數裡面的<strong>參數</strong>傳入的是<strong>可變物件</strong>，那該物件在函數內進行的操作都會對該原物件產生變化</p><pre>l = [1, 2, 3]<br>def func(list_param: list):<br>    list_param.append(100)  # 修改到列表物件<br><br>print(&quot;原始列表&quot;, l)<br>func(l)<br>print(&quot;修改後的列表&quot;, l)<br><br># 原始列表 [1, 2, 3]<br># 修改後的列表 [1, 2, 3, 100]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a70e2589cc60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Python筆記】 基本資料型別]]></title>
            <link>https://medium.com/@SCU.Datascientist/python%E7%AD%86%E8%A8%98-%E5%9F%BA%E6%9C%AC%E8%B3%87%E6%96%99%E5%9E%8B%E5%88%A5-96b6be59b17c?source=rss-a13f3c011379------2</link>
            <guid isPermaLink="false">https://medium.com/p/96b6be59b17c</guid>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alex lin]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 08:46:37 GMT</pubDate>
            <atom:updated>2025-11-15T11:21:48.617Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Python筆記】基本資料型別</h3><blockquote><strong>相關系列文章如下</strong></blockquote><blockquote><strong>基礎<br></strong><a href="https://medium.com/@SCU.Datascientist/python%E7%AD%86%E8%A8%98-%E8%AE%8A%E6%95%B8%E8%A7%A3%E6%9E%90-%E5%91%BD%E5%90%8D%E8%88%87%E5%8F%AF%E8%AE%8A%E7%89%A9%E4%BB%B6%E8%A1%8C%E7%82%BA-9b0b61ad1d92">變數解析 — 命名與可變物件行為</a><br><a href="https://medium.com/@SCU.Datascientist/python%E7%AD%86%E8%A8%98-%E5%9F%BA%E6%9C%AC%E8%B3%87%E6%96%99%E5%9E%8B%E5%88%A5-96b6be59b17c">基本資料型別</a><br><a href="https://medium.com/@SCU.Datascientist/%E5%87%BD%E6%95%B8-function-a70e2589cc60">函數(Function)</a></blockquote><h3><strong>List（列表）</strong></h3><ul><li><strong>有序集合，可存放任意型別元素，為可變物件</strong></li><li><strong>常用方法</strong><br>- len()<br>- append()<br>- extend()<br>- insert()<br>- remove()<br>- sort()<br>- sorted()<br>- index()<br>- count()</li><li><strong>重點關注<br>- </strong>切片索引為有頭無尾，好處是計算長度可以直接後-前，如 l[n:m] 的長度為 m-n<br>- 複製 list 時，如果 list 為多層，或是裡面元素有可變物件，建議使用深拷貝 (deepcopy)，如果內容皆為不可變物件，使用淺拷貝 (Shallow Copy)，另外拷貝 (copy) 與 參照 (reference) 是不一樣的概念</li></ul><h3>Tuple（元組）</h3><ul><li><strong>有序集合</strong>，<strong>元素不可修改，為不可變物件</strong></li><li><strong>重點關注</strong><br>- 單一元素需要加入逗號，如(2, )</li></ul><h3>Set（集合）</h3><ul><li><strong>無序且不重複的元素集合，為可變物件</strong></li><li><strong>重點關注</strong><br>- 內容元素皆須可變物件<br>- 可用 frozenset 來帶替 set 作為不可變物件</li></ul><h3>Dict（字典）</h3><ul><li><strong>key-value 配對集合，為可變物件</strong></li><li><strong>常用方法<br></strong>- keys()<br>- values()<br>- items()<br>- get()<br>- setdefault()<br>- copy()<br>- update()</li><li><strong>重點關注<br></strong>- key 值需要是不可變且可雜湊，tuple 原則上可以，但如果 tuple 中有可變物件則不行</li></ul><h3>Str（字串）</h3><ul><li><strong>字元序列，可當成不可變的列表，不可變物件</strong></li><li><strong>常用方法<br></strong>- upper()<br>- lower()<br>- title()<br>- find(), index()<br>- rfind(), rindex()<br>- startswith(), endswith()<br>- replace()<br>- strip(), rstrip(), lstrip()<br>- split()<br>- join()<br>- isdigit(), isalpha()<br>- encode()</li></ul><h3>比較</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*RriRdYnGNXP2zEkFRpPaeQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96b6be59b17c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Python筆記】變數解析 — 命名與可變物件行為]]></title>
            <link>https://medium.com/@SCU.Datascientist/python%E7%AD%86%E8%A8%98-%E8%AE%8A%E6%95%B8%E8%A7%A3%E6%9E%90-%E5%91%BD%E5%90%8D%E8%88%87%E5%8F%AF%E8%AE%8A%E7%89%A9%E4%BB%B6%E8%A1%8C%E7%82%BA-9b0b61ad1d92?source=rss-a13f3c011379------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b0b61ad1d92</guid>
            <category><![CDATA[immutable-objects]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mutable-objects]]></category>
            <category><![CDATA[basics]]></category>
            <dc:creator><![CDATA[Alex lin]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 07:15:39 GMT</pubDate>
            <atom:updated>2025-11-15T05:51:30.576Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Python筆記】變數解析 — 命名與可變物件行為</h3><h3>前言</h3><p>在這 AI 工具快速發展時代，從頭開始手寫程式碼的情形已經越來越少，取而代之的則是透過 AI 生成專業程式碼後，工程師審核後並做修正。</p><p>筆者想藉此機會將以往不管式透過書籍或是網上學習到的知識，做一個重點的整理與複習，以增加理解能力。</p><blockquote><strong>相關系列文章如下</strong></blockquote><blockquote><strong>基礎<br></strong><a href="https://medium.com/@SCU.Datascientist/python%E7%AD%86%E8%A8%98-%E8%AE%8A%E6%95%B8%E8%A7%A3%E6%9E%90-%E5%91%BD%E5%90%8D%E8%88%87%E5%8F%AF%E8%AE%8A%E7%89%A9%E4%BB%B6%E8%A1%8C%E7%82%BA-9b0b61ad1d92">變數解析 — 命名與可變物件行為</a><br><a href="https://medium.com/@SCU.Datascientist/python%E7%AD%86%E8%A8%98-%E5%9F%BA%E6%9C%AC%E8%B3%87%E6%96%99%E5%9E%8B%E5%88%A5-96b6be59b17c">基本資料型別</a><br><a href="https://medium.com/@SCU.Datascientist/%E5%87%BD%E6%95%B8-function-a70e2589cc60">函數(Function)</a></blockquote><h3>變數</h3><p>在 Python 中，變數不需要事先宣告型別，變數的型別是由它當前參照(reference)的物件決定的，這樣的方式稱作動態型別(dynamic type)</p><h4>1. 命名規則</h4><pre>* 普通變數<br>    - 格式: 全部小寫，使用底線來分隔單詞，注意不能是 python 保留字(keyword)<br>    - 範例: `user_name`、`total_price`<br><br>* 常數變數<br>    - 格式: 全部大寫，常數一旦賦值，就不應再被重新指向新的值<br>    - 範例: `PI`、`GRAVITY   ` <br><br>* 涵式名稱<br>    - 格式: 全部小寫，使用底線來分隔單詞<br>    - 範例: `calculate_user_age`、`format_user_info`<br><br>* 類別名稱<br>    - 格式: 每個英文單字開頭大寫<br>    - 範例: `UserProfile`、`OrderManager`<br><br>* 特殊用途<br>    - 前單底線<br>        - 格式: _var<br>        - 用途: 內部或私有變數或涵式，用於提示程式使用者這個變數是「內部使用」，不應直接訪問，但語言層面不強制，使用*匯入模組時會忽略<br>    - 前雙底線<br>        - 格式: __var<br>        - 用途: 類別內部專用變數或 method，會被 python 改名成_ClassName__var<br>    - 前後雙底線<br>        - 格式: __var_<br>        - 用途: Python 保留名稱，系統定義方法或屬性，通常用於魔術方法，命名時避免使用此格式<br>    - 後單底線<br>        - 格式: var_<br>        - 用途: 避免與 Python 關鍵字衝突<br>    - 純底線<br>        - 格式: _<br>        - 用途: 免洗或不重要的變數</pre><h4>2. 建立的機制</h4><pre>x = 2   # 整數物件<br>print(x)</pre><p>python 中所有東西都是物件，而變數的建立是將其參照到記憶體中的某個物件，以上面的例子而言，x 變數是參照 2 這個整數物件，另外也可以多個變數去參照到同一個物件，如下</p><pre>x = 2   # 整數物件<br>x1 = x<br>x2 = x<br><br>print(&quot;x1&quot;, x1)<br>print(&quot;x2&quot;, x2)<br>print(&quot;x1 與 x 是否是同一物件:&quot;, x1 is x)<br>print(&quot;x2 與 x 是否是同一物件:&quot;, x2 is x)<br><br># x1: 2<br># x2: 2<br># x1 與 x 是否是同一物件: True<br># x2 與 x 是否是同一物件: True</pre><p>而物件又可以分成「<strong>可變物件 (mutable)</strong>」與「<strong>不可變物件 (immutable)</strong>」</p><ul><li><strong>可變物件</strong><br>- 說明: 建立後內容可以被改變<br>- 常見類型: list、dict、set</li><li><strong>不可變物件</strong><br>- 說明: 建立後內容不能被改變<br>- 常見類型: int、float、str、tuple、bool</li></ul><pre>x = [1, 2, 3]   # 列表物件<br><br>print(&quot;=====x 變動前=====&quot;) <br>x1 = x<br>x2 = x<br>print(&quot;x: &quot;, x)<br>print(&quot;x1:&quot;, x1)<br>print(&quot;x2:&quot;, x2)<br><br>print(&quot;\n=====x 變動後=====&quot;) <br>x.append(4)  # 修改列表物件<br>print(&quot;x: &quot;, x)<br>print(&quot;x1:&quot;, x1)<br>print(&quot;x2:&quot;, x2)<br><br><br># =====x 變動前=====<br># x:  [1, 2, 3]<br># x1: [1, 2, 3]<br># x2: [1, 2, 3]<br><br># =====x 變動後=====<br># x:  [1, 2, 3, 4]<br># x1: [1, 2, 3, 4]<br># x2: [1, 2, 3, 4]</pre><p>如果要用簡單的方式理解，可以想像成3個朋友一起出遊，並共用同一個錢包，x、x1、x2 分別對應到 3 個人，列表物件則對應到錢包，而錢包的錢是可以變多變少，因此錢包的錢被誰拿走，3 人都會受到影響</p><ul><li><strong>錢包（物件）</strong>：代表可變的列表物件，它可以被「修改」（加錢或拿錢），不需要建立新錢包。</li><li><strong>三個朋友（變數）</strong>：x、x1、x2 都「共享」同一個錢包（指向同一個記憶體位置）。</li><li><strong>誰拿錢都影響大家</strong>：當一個人（x）從錢包拿錢或加錢時，其他人（x1、x2）也會看到變化，因為錢包本身被改了。</li></ul><p><strong>這就是可變物件的「共享修改」機制，如果沒注意可能會導致像是函式內修改而影響外部意外之類的意外發生。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*_ytCX4KhOWyFfAoVDqypVA.png" /></figure><p><strong>那如果參照的物件是不可變物件 (immutable) 呢，既然都是不可變了，因此當變數的值改變時，它一定是去參照另一個新的物件</strong></p><pre>x = 1   # 整數物件<br><br>print(&quot;=====x 變動前=====&quot;) <br>x1 = x<br>x2 = x<br>print(&quot;x: &quot;, x)<br>print(&quot;x1:&quot;, x1)<br>print(&quot;x2:&quot;, x2)<br><br><br>print(&quot;\n=====x 變動後=====&quot;) <br>x = 2  # x 改去參照 2(整數物件)<br>print(&quot;x: &quot;, x)<br>print(&quot;x1:&quot;, x1)<br>print(&quot;x2:&quot;, x2)<br><br># =====x 變動前=====<br># x:  1<br># x1: 1<br># x2: 1<br><br># =====x 變動後=====<br># x:  2<br># x1: 1<br># x2: 1</pre><p>這這邊可以想像成3個兄妹擁有一個紀念幣，而規定是每隔人當下只能擁有一個東西，因此當哥哥 X 想要擁有玩具熊而放棄擁有紀念幣時，其他兄妹不會受到影響</p><ul><li><strong>紀念幣（物件）</strong>：代表不可變的整數物件（如 1），它本身不能被「修改」（因為硬幣不會變成玩具，硬幣就是硬幣）。</li><li><strong>兄妹（變數）</strong>：x、x1、x2 都「共享」對紀念幣的所有權（指向同一個記憶體位置）。</li><li><strong>哥哥放棄所有權</strong>：當 x = 2 時，x 不再指向原來的紀念幣 1，而是轉向一個全新的玩具 2。其他兄妹 x1 和 x2 依然持有原來的紀念幣 1，不受影響。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*lAyACRpHA53cy19GCrCepw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b0b61ad1d92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alembic 介紹與設定]]></title>
            <link>https://medium.com/@SCU.Datascientist/alembic-%E4%BB%8B%E7%B4%B9%E8%88%87%E8%A8%AD%E5%AE%9A-54915ef5b6eb?source=rss-a13f3c011379------2</link>
            <guid isPermaLink="false">https://medium.com/p/54915ef5b6eb</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[alembic]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Alex lin]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 12:55:02 GMT</pubDate>
            <atom:updated>2025-11-07T12:55:02.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*84AABkp_pV5AyFocEXUhXg.jpeg" /><figcaption>generated by grok</figcaption></figure><h3>1. 介紹</h3><p>Alembic 是一個輕量級的資料庫遷移（Database Migration）工具，專為 Python 的 SQLAlchemy ORM 框架設計。它用於管理資料庫結構（schema）的變更，例如新增表格、修改欄位、添加索引或刪除約束。Alembic 透過生成 Python 格式的遷移腳本（migration scripts）來追蹤資料庫版本，並支援自動生成遷移、版本控制和回滾功能</p><h3>2. SQLAlchemy + Alembic 的使用設定</h3><p>官方文件<br><a href="https://alembic.sqlalchemy.org/en/latest/tutorial.html#the-migration-environment">https://alembic.sqlalchemy.org/en/latest/tutorial.html#the-migration-environment</a></p><h3>🔢步驟 1：安裝必要套件</h3><pre>pip install sqlalchemy alembic</pre><h3>🔢步驟 2：建立遷移環境的主目錄(migrations directory)</h3><p>執行完後會建立以下檔案</p><pre>yourproject/<br>├── alembic.ini<br>├── alembic/<br>│   ├── env.py<br>│   ├── README<br>│   ├── script.py.mako<br>│   └── versions/</pre><ul><li><strong>alembic.ini</strong>: 主配置文件</li><li><strong>alembic</strong>: 遷移環境的主目錄，可以被任意命名</li><li><strong>env.py</strong>: 呼叫 alembic 遷移工具時都會執行。至少包含一些指令，用於配置和產生 SQLAlchemy 引擎</li><li><strong>script.py.mako</strong>: Alembic 的 migration script 模板檔案，用來定義每次執行 alembic revision 時所產生的 .py 檔案內容</li></ul><h3>🔢步驟 3：常用 alembic.ini 設定</h3><ul><li><strong>script_location:<br></strong>說明: 遷移環境目錄位置<br>設定: <strong>script_location = %(here)s/alembic</strong></li><li><strong>file_template</strong>:<br>說明: 產生新遷移檔案的命名方式<br>設定: <strong>file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s</strong></li><li><strong>timezone:</strong><br>說明: 時區名稱<br>設定:<strong>timezone = Asia/Taipei</strong><br>要安裝 tzdata: <strong>pip install tzdata</strong></li><li><strong>sqlalchemy.url:</strong><br>說明: 透過 SQLAlchemy 連接資料庫的 URL。此配置值僅在env.py檔案呼叫時使用，如果 SQLAlchemy URL 應來自其他來源（例如環境變數或全域註冊表），需修改文件</li><li><strong>revision_environment</strong>: 說明: 當生成新 migration (alembic revision) 時，是否強制執行 env.py 設定: <strong>revision_environment = false</strong></li></ul><p><strong>alembic.ini(範例)</strong></p><pre>[alembic]<br>script_location = %(here)s/alembic<br>file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s<br>prepend_sys_path = .<br>timezone = Asia/Taipei<br>revision_environment = false<br>path_separator = os<br>sqlalchemy.url=your_url<br><br>[post_write_hooks]<br><br>[loggers]<br>keys = root,sqlalchemy,alembic<br><br>[handlers]<br>keys = console<br><br>[formatters]<br>keys = generic<br><br>[logger_root]<br>level = WARNING<br>handlers = console<br>qualname =<br><br>[logger_sqlalchemy]<br>level = WARNING<br>handlers =<br>qualname = sqlalchemy.engine<br><br>[logger_alembic]<br>level = INFO<br>handlers =<br>qualname = alembic<br><br>[handler_console]<br>class = StreamHandler<br>args = (sys.stderr,)<br>level = NOTSET<br>formatter = generic<br><br>[formatter_generic]<br>format = %(levelname)-5.5s [%(name)s] %(message)s<br>datefmt = %H:%M:%S</pre><h3>🔢 步驟 4：修改 env.py 設定(若要使用autogenerate功能)</h3><p><strong>--autogenerate</strong> 是 Alembic 的一個 自動比對功能，主要用來根據 SQLAlchemy ORM Model，自動生成 migration 的 SQL。它可以省去手動寫 CREATE TABLE、ALTER TABLE 等 SQL 的麻煩。</p><p>若要使用<strong>autogenerate</strong>功能，需在<strong>env.py</strong>新增</p><ol><li><strong>from models import Base</strong> (匯入 ORM 的基底類別 Base )</li><li><strong>target_metadata = Base.metadata</strong></li><li>新增<strong>include_object</strong>函數來管理能操作的 Table (如果有多專案共用同一個資料庫，可以通過此設定來定義要監控的table)</li></ol><p><strong>env.py</strong></p><pre>from logging.config import fileConfig<br><br>from sqlalchemy import engine_from_config<br>from sqlalchemy import pool<br><br>from alembic import context<br><br># ORM Model<br>from models import Base  <br><br># this is the Alembic Config object, which provides<br># access to the values within the .ini file in use.<br>config = context.config<br><br># Interpret the config file for Python logging.<br># This line sets up loggers basically.<br>if config.config_file_name is not None:<br>    fileConfig(config.config_file_name)<br><br># add your model&#39;s MetaData object here<br># for &#39;autogenerate&#39; support<br># from myapp import mymodel<br># target_metadata = mymodel.Base.metadata<br># target_metadata 用來比對現有資料庫，生成 migration<br>target_metadata = Base.metadata<br><br># other values from the config, defined by the needs of env.py,<br># can be acquired:<br># my_important_option = config.get_main_option(&quot;my_important_option&quot;)<br># ... etc.<br><br>def include_object(object_, name, type_, reflected, compare_to):<br>    &quot;&quot;&quot;限制 ORM table，允許新增 table &amp; 欄位增刪，但不刪除 table&quot;&quot;&quot;<br>    <br>    if type_ == &quot;table&quot;:<br>        # 允許 ORM 有定義的 table（不管資料庫中是否存在）<br>        if name in [&quot;example_table&quot;]:<br>            return True<br>        # 不允許刪除資料庫已有但 ORM 刪掉的 table<br>        if reflected and compare_to is None:<br>            return False<br>        return False  # 其他 table 都忽略<br>    <br>    if type_ == &quot;column&quot;:<br>        # 允許欄位新增或刪除<br>        return (reflected and compare_to is None) or (not reflected and compare_to is None)<br>    <br>    # 其他物件 (index, constraint) 忽略<br>    return False<br><br><br>def run_migrations_offline() -&gt; None:<br>    &quot;&quot;&quot;Run migrations in &#39;offline&#39; mode.<br><br>    This configures the context with just a URL<br>    and not an Engine, though an Engine is acceptable<br>    here as well.  By skipping the Engine creation<br>    we don&#39;t even need a DBAPI to be available.<br><br>    Calls to context.execute() here emit the given string to the<br>    script output.<br><br>    &quot;&quot;&quot;<br>    url = config.get_main_option(&quot;sqlalchemy.url&quot;)<br>    context.configure(<br>        url=url,<br>        target_metadata=target_metadata,<br>        literal_binds=True,<br>        dialect_opts={&quot;paramstyle&quot;: &quot;named&quot;},<br>        include_object=include_object<br>    )<br><br>    with context.begin_transaction():<br>        context.run_migrations()<br><br><br>def run_migrations_online() -&gt; None:<br>    &quot;&quot;&quot;Run migrations in &#39;online&#39; mode.<br><br>    In this scenario we need to create an Engine<br>    and associate a connection with the context.<br><br>    &quot;&quot;&quot;<br>    connectable = engine_from_config(<br>        config.get_section(config.config_ini_section, {}),<br>        prefix=&quot;sqlalchemy.&quot;,<br>        poolclass=pool.NullPool,<br>    )<br><br>    with connectable.connect() as connection:<br>        context.configure(<br>            connection=connection, <br>            target_metadata=target_metadata,<br>            include_object=include_object<br>        )<br><br>        with context.begin_transaction():<br>            context.run_migrations()<br><br><br>if context.is_offline_mode():<br>    run_migrations_offline()<br>else:<br>    run_migrations_online()</pre><h4>備註</h4><p>所有建立的 <strong>ORM Model</strong> 必須繼承同一個 <strong>Base</strong>，並在 <strong>models/__init__.py</strong> 中匯入所有模型，確保 <strong>Base.metadata</strong> 包含所有 table。Alembic 的 <strong>env.py</strong> 才能正確讀取 metadata 並產生 migration。</p><pre># models/__init__.py<br>from .example import ExampleTable<br>from .base import Base</pre><h3>🔢 步驟 5：生成第一次 migration</h3><h4><strong>手動生成 SQL (若有多個專案共用同個料庫，建議使用👈)</strong></h4><pre>alembic revision -m &quot;create table&quot;</pre><h4>自動生成 SQL</h4><p>⚠️ 注意 <br>預設如果使用 autogenerate 產生 migration，ORM Model的定義要與資料庫完全相同，假如說資料庫已經有建立50個table，程式就要定義出50個相對應的 ORM Model，不然如果定義少了會被判定table被刪掉，而遭 Alembic 移除。</p><p>以上可透過<strong>env.py</strong>來設定</p><pre>alembic revision --autogenerate -m &quot;create table&quot;</pre><h4>執行完後會在versions底下建立該版本的Migration Scripts</h4><pre>yourproject/<br>├── alembic.ini<br>├── alembic/<br>│   ├── env.py<br>│   ├── README<br>│   ├── script.py.mako<br>│   └── versions/<br>│       ├──2025_09_24_1254-03e429eb9bb6_create_table.py</pre><p><strong>2025_09_24_1254–03e429eb9bb65_create_table.py</strong></p><pre>&quot;&quot;&quot;create example table<br><br>Revision ID: 5623cd76e877<br>Revises: <br>Create Date: 2025-09-24 15:54:43.679446+08:00<br><br>&quot;&quot;&quot;<br>from typing import Sequence, Union<br><br>from alembic import op<br>import sqlalchemy as sa<br><br><br># revision identifiers, used by Alembic.<br>revision: str = &#39;5623cd76e877&#39;<br>down_revision: Union[str, Sequence[str], None] = None<br>branch_labels: Union[str, Sequence[str], None] = None<br>depends_on: Union[str, Sequence[str], None] = None<br><br><br>def upgrade() -&gt; None:<br>    &quot;&quot;&quot;Upgrade schema.&quot;&quot;&quot;<br>    # ### commands auto generated by Alembic - please adjust! ###<br>    op.drop_column(&#39;Documents&#39;, &#39;theme&#39;)<br>    # ### end Alembic commands ###<br><br><br>def downgrade() -&gt; None:<br>    &quot;&quot;&quot;Downgrade schema.&quot;&quot;&quot;<br>    # ### commands auto generated by Alembic - please adjust! ###<br>    op.add_column(&#39;Documents&#39;, sa.Column(&#39;theme&#39;, sa.VARCHAR(length=50, collation=&#39;Chinese_Taiwan_Stroke_CI_AS&#39;), autoincrement=False, nullable=True))<br>    # ### end Alembic commands ###</pre><h3>🔢 步驟 6：版本管理</h3><h4>進行操作前務必在檢查Migration Scripts裡面是否有危險操作，如誤刪資料表等</h4><p>查看當前版本</p><pre>alembic current</pre><p>升級至最新版本</p><pre>alembic upgrade head</pre><p>升級至指定版本</p><pre>lembic upgrade &lt;revision_id&gt;</pre><p>升級2個版本</p><pre>alembic upgrade +2</pre><p>降級1個版本</p><pre>alembic downgrade -1</pre><h3><strong>3. 結論</strong></h3><h4>Migration Script</h4><p>每次對資料庫 schema 做修改（新增/修改/刪除表格、欄位、索引等）時，都會建立一個 migration script。</p><p>Script 裡面定義了 升級 (upgrade) 和 降級 (downgrade) 的操作，來對資料庫進行異動。</p><h4>版本管理</h4><p>Alembic 會追蹤每個 migration script 的版本號，存放在資料表 alembic_version 裡。</p><p>可以使用 alembic upgrade 或 alembic downgrade 來控制資料庫升級或回退到指定版本。</p><blockquote>若您覺得這篇文章的內容對您有幫助，不妨給些掌聲，您的掌聲是創作者持續的動力 😃</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54915ef5b6eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【網路爬蟲】使用 API 方式爬取 Google 商家評論爬取（附Python程式碼）]]></title>
            <link>https://medium.com/@SCU.Datascientist/%E7%B6%B2%E8%B7%AF%E7%88%AC%E8%9F%B2-%E4%BD%BF%E7%94%A8-api-%E6%96%B9%E5%BC%8F%E7%88%AC%E5%8F%96-google-%E5%95%86%E5%AE%B6%E8%A9%95%E8%AB%96%E7%88%AC%E5%8F%96-%E9%99%84python%E7%A8%8B%E5%BC%8F%E7%A2%BC-5465a19a31b7?source=rss-a13f3c011379------2</link>
            <guid isPermaLink="false">https://medium.com/p/5465a19a31b7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google評論]]></category>
            <category><![CDATA[google-map-api]]></category>
            <category><![CDATA[教學]]></category>
            <category><![CDATA[python爬蟲]]></category>
            <dc:creator><![CDATA[Alex lin]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 10:23:58 GMT</pubDate>
            <atom:updated>2024-12-29T10:23:58.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUKGJFVGFzBBLG4_qBLxoQ.png" /><figcaption><strong>偷打廣告</strong></figcaption></figure><p>不廢話，直接進入正題，普遍大家在爬取 Google 商家評論會遇到的主要問題是，當我們搜尋店家名稱進入評論的頁面，如果要看更多的評論，必須手動往下滑，不然只能看到當前的內容目前經過爬文，要抓取所有評論的方法主要可以分成以下兩種</p><ol><li>使用網頁模擬人為操作，常見的使用工具有 Selenium，目前我是沒有試過，相關的做法可以參考 <a href="https://medium.com/marketingdatascience/google-map-review-%E5%8B%95%E6%85%8B%E7%88%AC%E8%9F%B2-%E5%9B%9B-%E5%A6%82%E4%BD%95%E7%8D%B2%E5%8F%96%E5%BA%97%E5%AE%B6%E8%A9%95%E8%AB%96%E5%85%A7%E5%AE%B9-%E5%9C%96%E7%89%87%E4%BB%A5%E5%8F%8A%E7%AF%A9%E9%81%B8%E8%A9%95%E8%AB%96-%E9%99%84python%E7%A8%8B%E5%BC%8F%E7%A2%BC-33a06a671d13"><strong>Google Map Review 動態爬蟲：如何獲取店家評論內容、圖片以及篩選評論（附Python程式碼）</strong></a></li><li>模擬網頁發起 AJAX 請求，透過 HTTP GET 方式獲取資料，相關做法可以參考 <a href="https://medium.com/%E8%AA%A4%E9%97%96%E6%95%B8%E6%93%9A%E5%8F%A2%E6%9E%97%E7%9A%84%E5%95%86%E7%AE%A1%E4%BA%BAzino/python-%E7%88%AC%E5%8F%96google-map%E6%9C%80%E6%96%B0%E5%95%86%E5%AE%B6%E8%B3%87%E8%A8%8A%E8%A9%95%E8%AB%96-%E5%AF%A6%E4%BD%9C-%E5%8B%95%E6%85%8B%E7%B6%B2%E9%A0%81-%E7%88%AC%E8%9F%B2-527d66a7e747"><strong><em>Python 爬取Google map最新商家資訊評論!- 實作”動態網頁”爬蟲</em></strong></a></li></ol><p>本篇的做法會使用後者，接下來就介紹作法，文末有附程式碼，歡迎取用</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*-xHgIud1F0QyHJDao-tFmg.gif" /><figcaption><a href="https://medium.com/%E8%AA%A4%E9%97%96%E6%95%B8%E6%93%9A%E5%8F%A2%E6%9E%97%E7%9A%84%E5%95%86%E7%AE%A1%E4%BA%BAzino/python-%E7%88%AC%E5%8F%96google-map%E6%9C%80%E6%96%B0%E5%95%86%E5%AE%B6%E8%B3%87%E8%A8%8A%E8%A9%95%E8%AB%96-%E5%AF%A6%E4%BD%9C-%E5%8B%95%E6%85%8B%E7%B6%B2%E9%A0%81-%E7%88%AC%E8%9F%B2-527d66a7e747">source</a></figcaption></figure><h3>什麼是AJAX</h3><p>AJAX（Asynchronous JavaScript and XML）是一種網頁開發技術，允許在不重新加載整個頁面的情況下，與伺服器進行數據交換和操作。它利用 JavaScript 來發送異步請求，並可以根據伺服器回應動態更新頁面的一部分內容。Google map 評論區就採取 AJAX 的方式，讓我們在往下滑動以加載更多評論時，不需要進行完全的頁面重載，其運作的過程大致如下</p><p><strong>1. 用戶滑動網頁</strong></p><p>當用戶滾動到頁面的底部時，瀏覽器會觸發一個事件來檢查用戶是否已經滾動到底部。可以使用 JavaScript 來監聽這個事件。</p><p><strong>2. 發送 AJAX 請求</strong></p><p>當用戶到達頁面底部，觸發滾動事件後，發送一個 AJAX 請求到後端，請求更多的數據，通常是通過 fetch 來完成。</p><p><strong>3. 後端返回 Response</strong></p><p>後端收到 AJAX 請求後，處理並返回數據</p><p><strong>4. 更新頁面</strong></p><p>當接收到後端的數據後，JavaScript 使用 DOM 操控技術來將這些數據添加到頁面中，完成頁面的動態更新。</p><h3>透過發送 AJAX 請求來獲取數據</h3><p>從以上步驟可以發現，如果想要使用程式來爬取新的頁面，我們可以直接發起 AJAX 請求，整個過程就像是<strong>透過 API 使用 GET 方式從伺服器獲取資料，</strong>只要我們知道目標 URL 與參數，就能實現<strong>網路自動爬蟲</strong></p><p>取得 URL 的方式，首先進入頻論區按下 F12 進入開發者工具，依序點擊 Network &gt; fetch/XOR ，上面輸入框搜尋 listugcposts，就可以看到很多listugcposts URL，如果沒看到的話，左側評論區持續往下滑，應該就會出現新的</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_wloTccwu8aFXUJx6JILw.png" /><figcaption><strong>圖一</strong></figcaption></figure><p>我們挑選其中一個來看裡面 Headers 內容 (<strong>圖二)</strong>，紅框的部分就是發送的請求格式，接著看到 Preview (<strong>圖三)，</strong>這裡用格式化方式呈現後端返回的數據，可以點進去看看，裡面包含了評論的各種資訊，也就是本篇爬蟲要爬取的目標</p><p>注意 ❗注意❗注意❗，很重要要說 3 次，(<strong>圖三) </strong>紅框的地方是關鍵，筆者當初在解讀請求參數是就卡在這邊，最後還是請 ChatGPT 大神來解惑，前面有提到每次滾動到頁面的底部時，瀏覽器就會發起請求來更新數據，那要如何知道下一次要請求的資料是什麼 ? 這時就需要一個 <strong>token </strong>來表示下次要 GET 的對象，這個 <strong>token </strong>就是紅框的部分，除了第一頁的請求不需要帶 <strong>token，</strong>其餘都需要加入<strong>，如果沒有返回 token，代表已經是評論的最後底部了</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WijGy3iSjiQLSFXfCycZMA.png" /><figcaption><strong>圖二</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CYIQxW_6JeuPOKVc6SuVQ.png" /><figcaption><strong>圖三</strong></figcaption></figure><h3>程式碼實現</h3><p>資料爬取流程可以參考下面流程圖，基本如下</p><ol><li>選擇要爬取的店家</li><li>使用 gms.get_store_id 來取得店家 id</li><li>使用 gms.get_comment 來取得店家評論</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*Q3Tw07m-ebaKhINzvg_vXw.png" /><figcaption><strong>運作流程圖</strong></figcaption></figure><pre>from bs4 import BeautifulSoup<br>from datetime import datetime<br>import requests<br>import json<br>import emoji<br>import re<br><br> <br>class GoogleMapSpider:<br>    def __init__(self):<br>        self.headers = {&quot;User-Agent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64)&quot;<br>                       &quot;AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36&quot;<br>        }<br>        self.store_id_url = &quot;https://www.google.com.tw/maps/search/{store_name}&quot;<br>        self.store_name_url = &quot;https://www.google.com.tw/maps/place/data=!4m5!3m4!1s{store_id}!8m2!3d25.0564743!4d121.5204167?authuser=0&amp;hl=zh-TW&amp;rclk=1&quot;<br>        self.comment_url = &quot;https://www.google.com.tw/maps/rpc/listugcposts&quot;<br>        <br>        <br>    def get_store_id(self, store_name):<br>        &#39;&#39;&#39;store_name必須與google地圖搜尋結果完全一致, 例如: 隱家拉麵 士林店&#39;&#39;&#39;<br>        url = self.store_id_url.format(store_name=store_name)<br>        response = requests.get(url, headers=self.headers)<br>        soup = BeautifulSoup(response.text, &quot;lxml&quot;)<br>        pattern = r&#39;0x.{16}:0x.{16}&#39;<br>        match = re.search(pattern, str(soup)) <br>        store_id = match.group()<br>        <br>        return store_id<br><br>    def get_store_name(self, store_id):<br>        url = self.store_name_url.format(store_id=store_id)<br>        response = requests.get(url, headers=self.headers)<br>        soup = BeautifulSoup(response.text, &quot;lxml&quot;)<br>        meta_list=soup.find_all(&#39;meta&#39;)<br>        store_name=[]<br>        for i in meta_list:<br>            if &#39;&#39;&#39;itemprop=&quot;name&quot;&#39;&#39;&#39; in str(i):<br>                store_name.append(re.search(&#39;&quot;.*·&#39;,str(i)).group()[1:-2])<br>        store_name=store_name[0]<br><br>        return store_name<br><br>    <br>    def get_related_store_names(self, store_name):<br>        &#39;&#39;&#39;輸入店名，返回與搜尋最相關的店名與id&#39;&#39;&#39;<br>        url = self.store_id_url.format(store_name=store_name)<br>        response = requests.get(url, headers=self.headers)<br>        soup = BeautifulSoup(response.text, &quot;lxml&quot;)<br>        pattern = r&#39;0x.{16}:0x.{16}&#39;<br>        store_id_list = set(re.findall(pattern, str(soup)))<br>        store_id_list = [store_id.replace(&#39;\\&#39;, &#39;&#39;) for store_id in store_id_list]<br>        store_name_list = []<br>        for store_id in store_id_list:<br>            try:<br>                store_name_list.append(self.get_store_name(store_id))<br>            except:<br>                pass<br><br>        store_dict = {index: letter for index,<br>                    letter in zip(store_name_list, store_id_list)}<br><br>        return store_dict<br>    <br>    def get_comment(self, store_id, page_count=1, sorted_by= 2):<br>        &#39;&#39;&#39;<br>        sorted_by 參數對應：<br>        1 - 最相關 (Most Relevant)<br>        2 - 最新 (Newest)<br>        3 - 評分最高 (Highest Rating)<br>        4 - 評分最低 (Lowest Rating)<br>        <br>        每個 page 會有10筆資料，除非評論數未達10筆<br><br>        &#39;&#39;&#39;<br>        next_token = &quot;&quot;<br>        commont_list = []<br>        for page in range(1, page_count+1):<br>            print(f&quot;第 {page} 頁開始抓取&quot;)<br>            <br>            params = {<br>                &quot;authuser&quot;: &quot;0&quot;,<br>                &quot;hl&quot;: &quot;zh-TW&quot;,<br>                &quot;gl&quot;: &quot;tw&quot;,<br>                &quot;pb&quot;: (<br>                    f&quot;!1m6!1s{store_id}!6m4!4m1!1e1!4m1!1e3!2m2!1i10!2s&quot;<br>                    f&quot;{next_token}&quot;<br>                    f&quot;!5m2!1s0OBwZ4OnGsrM1e8PxIjW6AI!7e81!8m5!1b1!2b1!3b1!5b1!7b1!11m0!13m1!1e{sorted_by}&quot;<br>                )<br>            }<br><br>            response = requests.get(self.comment_url, params=params, headers=self.headers)<br>            data = json.loads(emoji.demojize(response.text[4:]))<br>            print(f&quot;第 {page} 抓取結束&quot;)<br><br>            next_token = data[1]<br>            commont_list.extend(data[2])<br>            if not next_token:<br>                print(f&quot;所有評論以抓取完成，總共抓取 {len(commont_list)} 則評論&quot;)<br>                break<br>                <br>        # 提取需要的資料<br>        commont_dict_list = []<br>        for comment_data in commont_list:<br>            <br>            try:<br>                comment_date = comment_data[0][2][2][0][1][21][6][-1]<br>                comment_date = datetime(comment_date[0], comment_date[1], comment_date[2], comment_date[3]).strftime(&#39;%Y/%m/%d %H:%M:%S&#39;)<br>            except:<br>                comment_date = None<br><br><br>            try:<br>                comment_text = comment_data[0][2][-1][0][0]<br><br>            except:<br>                comment_text = None<br><br>                <br>            comment_info = {<br>                &quot;評論者&quot;: comment_data[0][1][4][5][0],<br>                &quot;評論者id&quot;: comment_data[0][0],<br>                &quot;評論者狀態&quot;: comment_data[0][1][4][5][10][0],<br>                &quot;評論者等級&quot;: comment_data[0][1][4][5][9],<br>                &quot;留言時間&quot;:comment_data[0][1][6],<br>                &quot;留言日期&quot;:comment_date,<br>                &quot;評論&quot;:comment_text,<br>                &quot;評論分數&quot;:comment_data[0][2][0][0]<br><br>            }<br>            commont_dict_list.append(comment_info)<br><br><br><br>        return commont_dict_list<br><br><br>if __name__ == &quot;__main__&quot;:<br><br>    gms = GoogleMapSpider()<br>    store_name = &quot;隱家拉麵 士林店&quot;<br>    store_id = gms.get_store_id(store_name)<br>    print(store_id)<br>    store_name = gms.get_store_name(store_id)<br>    print(store_name)<br>    store_dict = gms.get_related_store_names(store_name)<br>    print(store_dict)<br>    commont_dict_list = gms.get_comment(store_id=store_id, page_count=10, sorted_by=2)<br>    print(commont_dict_list)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOyUVWEyAfhEu7G7rLfNyw.png" /><figcaption><strong>輸出結果</strong></figcaption></figure><p>以上就是完整的程式碼，筆者之前也有<a href="https://medium.com/@SCU.Datascientist/%E4%B8%8D%E7%94%A8%E5%AF%AB%E7%A8%8B%E5%BC%8F%E4%B9%9F%E8%83%BD%E7%88%AC%E5%8F%96google%E8%A9%95%E8%AB%96-%E6%96%87%E6%9C%AB%E9%99%84python%E7%A8%8B%E5%BC%8F%E7%A2%BC-f512341d9e8f"><strong>實作</strong></a>過一次，並加入 GUI 介面來操作，但由於 google map 更換了 AJAX 的請求方式，過往的程式已無法運行，因此又再重新發一篇，之前請求的該開頭是</p><pre>https://www.google.com.tw/maps/preview/review/listentitiesreviews</pre><p>不知道什麼時候換成</p><pre>https://www.google.com.tw/maps/rpc/listugcposts</pre><p>新的請求參數較之前複雜許多，好在這次也成功完成，之後應該也會定期更改請求方式，但本質上都相同，照這篇文章的做法應該都能成功</p><blockquote>若您覺得這篇文章的內容對您有幫助，不妨給些掌聲，您的掌聲是創作者持續的動力 😃</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5465a19a31b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【機器學習筆記】物件偵測模型的效能評估：從 IoU 到 mAP]]></title>
            <link>https://medium.com/@SCU.Datascientist/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E7%89%A9%E4%BB%B6%E5%81%B5%E6%B8%AC%E6%A8%A1%E5%9E%8B%E7%9A%84%E6%95%88%E8%83%BD%E8%A9%95%E4%BC%B0-%E5%BE%9E-iou-%E5%88%B0-map-f5eaf691caea?source=rss-a13f3c011379------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5eaf691caea</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[yolov8]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Alex lin]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 17:01:33 GMT</pubDate>
            <atom:updated>2025-01-02T14:16:41.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UC_ddOxRxbHrzauPV9Juig.png" /><figcaption>generated by DALL·E</figcaption></figure><p><strong>物件偵測（Object Detection）</strong>與<strong>影像分類（Image Classification）</strong>最大的不同在於，物件偵測的目標不僅是識別圖像中的物體類別，還需要同時定位這些物體在圖像中的具體位置。透過模型的運算推理，物件偵測能根據結果生成<strong>邊界框（Bounding Box）</strong>，並進行視覺化展示，以清楚標示出每個物體的位置與類別</p><p>由於物件偵測的結果不僅包含物體的類別資訊，還涉及其在圖像中的位置，因此其評估指標與一般分類任務有所不同。以下為常見用來評估物件偵測模型的<strong>指標（metrics），</strong>接下來將會與各位一一介紹</p><ul><li><strong><em>IoU（Intersection over Union，交集與聯集比）</em></strong></li><li><strong><em>Box Precision（框精確度）&amp; Box Recall（框召回率）</em></strong></li><li><strong><em>AP（Average Precision，平均精確度）</em></strong></li><li><strong><em>mAP（mean Average Precision，平均平均精確度）</em></strong></li></ul><h4><strong><em>一、 IoU（Intersection over Union，交集與聯集比）</em></strong></h4><p>一般在評估模型預測的結果是否正確，會將其推理的結果與真實值( Ground Truth ) 進行比較，如果兩者一致，我們會說這是<strong>一個正確的預測（True Positive，TP），</strong>但是在物件偵測中，很難出現預測結果與真實值完全一樣，因此我們需要放寬標準，使用預測框與真實框的<strong>重疊程度</strong>來決定預測是否確，而IoU 就是評估兩者之間重疊率的指標</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*0Oj_EkBkb42dl7xVp-oDZQ.png" /><figcaption>IoU計算方式</figcaption></figure><p>IoU 的計算方式為<strong>預測框和真實框的交集面積 / 預測框和真實框聯集面積，</strong>其值範圍是介於 <strong>0</strong> 到 <strong>1</strong>，具體來說</p><ul><li><strong>IoU = 1</strong>：表示預測框與真實框完全重合，兩者的交集面積等於聯集面積，這是一個完美的預測結果。</li><li><strong>IoU = 0</strong>：表示預測框與真實框完全沒有重疊，兩者的交集面積為零，這表示預測完全錯誤</li></ul><p>當我們在評估模型時，會設置一個 <strong>IoU </strong>閾值來決定預測是否正確，舉例來說，<strong>IoU = 0.5</strong> 代表當預測框的重疊面積至少達到兩個框的聯集面積的50%時，這個預測會被視為正確（TP）</p><p>根據物件偵測的應用場景，所設的 IoU 閾值（threshold）可能會有所變化，以<strong>圖一</strong>為例，圖中的預測框與真實框的 IoU 差不多落在 0.55。我們的任務如果是要<strong>精準</strong>定位車輛位於馬路中的位置，將 IOU 設置為 0.75，那本次的預測將視為失敗，但情境轉換一下，目標改成計算圖中的車數，那麼 IOU 可以設置為 0.5，預測便轉為成功，常見的 IoU 閾值會落在 <strong>[ 0.5, 0.95 ] </strong>區間</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jV766Sn5G7EHqCZu4ToPqg.png" /><figcaption>圖一</figcaption></figure><h4>二 、<strong><em>Box Precision（框精確度）與 Box Recall（框召回率）</em></strong></h4><p>對於有接觸過分類任務的朋友來說，Precision 與 Recall 兩項指標應該在熟不過，不熟悉的人也可以參考我以前的<a href="https://medium.com/@SCU.Datascientist/python%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E5%B8%B8%E8%A6%8B%E7%9A%84%E4%BA%8C%E5%85%83%E5%88%86%E9%A1%9E%E8%A9%95%E4%BC%B0%E6%8C%87%E6%A8%99-%E6%B7%B7%E6%B7%86%E7%9F%A9%E9%99%A3-roc-%E6%9B%B2%E7%B7%9A-f214ecd84dab"><strong>文章</strong></a>，簡單來說</p><ul><li><strong>Precision ( 精確度 ) ，</strong>表示模型的預測結果中，有多少比例是真正正確的（真陽性），公式如下</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*xOPsVB64r7im2qgzLSHB1Q.png" /></figure><ul><li><strong>Recall ( 召回率 )，</strong>表示模型的預測結果中，有多少比例的物體被成功檢測出來，換句話說，它反映了模型對所有真實物體的識別能力，公式如下</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*s-7IzGfwBhB4Zm7OpIJJEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*fNgGuy_NK3662lT2oQP1Jg.jpeg" /><figcaption>混淆矩陣（confusion matrix）</figcaption></figure><p>看到這裡你可能會想問那 Box Precision 跟 Precision 與 Box Recall 跟 Recall 的關係是什麼，這時候就要提到前面所說的 IoU ，因為物件偵測在判定對錯是會考慮到<strong>邊界框（Bounding Box）的重疊率，</strong>因此在指標前面加入 Box 來做區分，基本上兩者的本質是一樣的，後面將會簡稱為 Precision 與 Recall</p><p>接下來就用<strong>圖二</strong>來示範如何計算 Box Precision 與 Box Recall，這邊我們 IoU 使用 0.7，紅色框為預測的結果，圖片中有 5 隻狗 ( TP + FN = 5)，我們正確的辨識出 3 隻 ( TP = 3)，並有一個背景的誤判 ( FP = 1)，根據公式計算，結果會是</p><p>Box Precision ⮕ (3 / 3 + 1 ) = 0.75</p><p>Box Recal ⮕ (3 / 5) = 0.6</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*Pp83gCM3p_GP6ijjj5T5Lg.png" /><figcaption>圖二</figcaption></figure><h4><strong><em>三、 AP（Average Precision，平均精確度）</em></strong></h4><p>先前的 Precision 和 Recall 之間其實存在著權衡（Trade-off）的問題，這意味著，為了提高一個指標，通常需要犧牲另一个指標的表現，而 AP 的計算結合了模型的 Precision 和 Recall，因此能全面反映模型在不同信心度閾值下的表現</p><p>AP 的計算主要可以分成以下 4 個步驟</p><ol><li>設定 IoU 閾值（threshold），讓模型根據 IoU 來判斷 TP 和 FP</li><li>計算不同的信心度 ( confidence ) 下模型的 Precision 與 Recall</li><li>繪製精度-召回率曲線（Precision-Recall Curve，PR 曲線）</li><li><strong>計算精度-召回率曲線下的面積，即為 AP （Average Precision )</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKUUG78Ho3ZSjeyYfjk0Fg.png" /><figcaption>PR curve</figcaption></figure><h4>四、<strong><em>mAP（mean Average Precision，平均平均精確度）</em></strong></h4><p>AP 只有針對某一個特定類別進行衡量，<strong>mAP</strong> 則是所有類別的 <strong>AP</strong> 的平均值。當我們進行多類別的物件偵測任務時，mAP 可以用來綜合評估模型在所有類別上的表現，mAP 更能反映模型在各個類別上的整體能力</p><p>在物件偵測中的評估指標，可能看到 mAP50 或是 mAP50–95，後面的數字其實就是 IoU 的閾值，兩者的差別在於閾值與計算次數的不同</p><ul><li>mAP50：在 IoU 閾值為 0.5 的情況下，所有類別的 <strong>AP</strong> 的平均</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*LfeXrljfVV-4HmM6U76D4g.png" /></figure><ul><li>mAP50–95：計算模型在 IoU 閾值範圍 [0.5:0.95]（以 0.05 為步長）下的 AP，然後求這些 AP 的平均值</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*aw9qMDJWIN7BrYnvwuoowg.png" /></figure><p>最後我們來看看目前各物件偵測模型在 <a href="https://www.kaggle.com/datasets/awsaf49/coco-2017-dataset">COCO 2017 Dataset</a> 上的表現</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGzhR72xi7ozO_lmomc0UQ.png" /><figcaption><a href="https://paperswithcode.com/sota/object-detection-on-coco?metric=AP50">source</a></figcaption></figure><ul><li><a href="https://medium.com/@SCU.Datascientist/python%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-vgg16%E4%BB%8B%E7%B4%B9%E5%8F%8A%E5%AF%A6%E4%BD%9C-e05d659f242f">【機器學習筆記】 VGG16介紹及實作</a></li><li><a href="https://medium.com/@SCU.Datascientist/python%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E8%81%9A%E9%A1%9E%E5%88%86%E6%9E%90k-means-clustering-63fd65027c98">【機器學習筆記】聚類分析K-means clustering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5eaf691caea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用Dash打造股市分析儀表板]]></title>
            <link>https://medium.com/@SCU.Datascientist/%E4%BD%BF%E7%94%A8dash%E6%89%93%E9%80%A0%E8%82%A1%E5%B8%82%E5%88%86%E6%9E%90%E5%84%80%E8%A1%A8%E6%9D%BF-c68d46a4e876?source=rss-a13f3c011379------2</link>
            <guid isPermaLink="false">https://medium.com/p/c68d46a4e876</guid>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alex lin]]></dc:creator>
            <pubDate>Sun, 25 Sep 2022 14:43:58 GMT</pubDate>
            <atom:updated>2022-09-25T14:43:58.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*afdbQ1J4OWl2EYYB" /><figcaption>Image by Unsplash</figcaption></figure><p>身為一個踏入股市不久的新手，對於股票的選擇以及進出場時機都還懵懵懂懂，透過網路的爬文大致了解股票的分析主要可以分為四大面向，分別為基本面、技術面、籌碼面及消息面</p><p><strong>基本面：根據財報、產業發展趨勢來衡量一家企業的價值</strong></p><p><strong>技術面：基於歷史會重演，去分析股票過去價格走勢去來預測未來</strong></p><p><strong>籌碼面：研究股票買賣動向，觀察三大法人、主力、大戶的操作方向</strong></p><p><strong>消息面：透過新聞媒體得知企業的各種消息</strong></p><p>其中<strong>技術面</strong>是最容易切入的面向，因此本人想嘗試以<strong>技術面</strong>作為出發點創建一個股市觀測儀表板，協助使用者在選股時能更有頭緒。</p><h3>製作流程</h3><p>此次的的專案使用Python作為開發工具，其中主要使用到的套件為<strong>Plotly</strong>與<strong>Dash。</strong>Plotly是一個高級的視覺化套件，相較於一般我們常會用到Matplotlib 和 Seaborn，它可以更有效的創建精緻的互動式圖表，而Dash則是一個建立在Plotly.js、React.js 與 Flask 之上的Web應用程序框架，因此他們可以搭配使用。</p><p>股市資料的部分使用<strong>Twstock</strong>套件來取得，由於個人在做股買賣時不會考慮上櫃類股，因此只抓取上市股票作為使用，抓取日期為2020/01/01至今。</p><p>整個儀表板的製作過程並不複雜，基本上只要先把想要呈現的圖表用Plotly做出來，之後再丟到Dash上做簡單的排版就可以完成了。</p><p><strong>整個專案的製作流程如下：</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YANH5j5GujDH8sudKFRPWA.png" /></figure><h3><strong>圖表介紹</strong></h3><p>此次的儀表板由六張圖表所組合而成，接下來會簡單介紹每張圖表的設計目的與解讀文末會放上github連結，這裡就不交代程式碼的部分了。</p><h4>交易量排行表格</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWTHQlxau4Oki7WV_kKzWw.png" /></figure><p>每日股票交易量排行，以表格方式呈現當下的熱門股票。</p><h4>股票K線圖</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoPn3zj0iCZVIuVn8Kip4A.png" /></figure><p>根據使用者輸入的股票以及觀測的天數返回K線圖，並配上<strong>技術分析</strong>常用的指標<strong>均線與布林通道</strong>讓使用者可以做進一步的分析。</p><h4>均線趨勢定位象限圖</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*LDMaZ-eXUAocj9f2Xn5JmQ.png" /></figure><p>以股票近5個交易日的ma值去計算其斜率，斜率為正象徵均線為向上趨勢，反之則下，以上圖為例，位於第四象限的股票其5ma向上，10ma向下，可能處於黃金交叉的階段，點的大小取決於交易量，此圖表能幫助使用者依據均線走勢快速找到合適進場的股票。</p><h4><strong>多空情勢直方圖</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*cvzzgMcB6LayPFO7Cb1Mwg.png" /></figure><p>統計近N日股票漲跌分布，從圖表中可以得知市場所處情勢，以上圖為例，在近5日多數股票的報酬率是負的，多軍與空軍的較量下屬於空軍的勝利。</p><h4>產業漲跌長條圖</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*zMDGlDgQvua8eemvQIt8Aw.png" /></figure><p>計算各類股在近N日的平均漲跌幅，找出當前的強勢類股。</p><p><strong>類股交易量樹狀圖</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*VQZE3dzmvO112bYKFEOeHg.png" /></figure><p>可以搭配<strong>產業漲跌長條圖</strong>做使用，以區塊大小來代表交易量，顏色代表漲跌幅，一眼就能看出該產業中的熱門類股。</p><h3>儀表板成果</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nd9jp3Qs4YxtKyMy_2r4tQ.png" /></figure><p><strong>附上github程式碼連結</strong></p><p><a href="https://github.com/alex6226/stockdash">GitHub - alex6226/stockdash</a></p><blockquote>以上為個人第一次製作網頁儀表板，如果覺得有趣的話不妨給我一些掌聲 : )</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c68d46a4e876" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【機器學習筆記】支援向量機(Support Vector Machine)]]></title>
            <link>https://medium.com/@SCU.Datascientist/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E6%94%AF%E6%8F%B4%E5%90%91%E9%87%8F%E6%A9%9F-support-vector-machine-80ad4266d592?source=rss-a13f3c011379------2</link>
            <guid isPermaLink="false">https://medium.com/p/80ad4266d592</guid>
            <category><![CDATA[支援向量機]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[機器學習]]></category>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alex lin]]></dc:creator>
            <pubDate>Sat, 18 Jun 2022 17:10:11 GMT</pubDate>
            <atom:updated>2023-06-20T06:48:19.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*yF3Fa4oUAxy24Xz4" /></figure><p><strong>支援向量機（Support Vector Machine）</strong>為機器學習中<strong>監督式學習（Supervised learning）</strong>的一種，與<a href="https://medium.com/@SCU.Datascientist/python%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E7%BE%85%E5%90%89%E6%96%AF%E5%9B%9E%E6%AD%B8-logistic-regression-7f3d47d35a"><strong>羅吉斯回歸</strong></a>一樣同屬<strong>線性分類器（Linear Classifier）</strong></p><p>線性分類器常遇到的問題在於現實中我們使用的資料通常不會只有二維，資料分佈也會相對複雜，這時就可能會遇到資料不是<strong>線性可分（Linear separable）</strong>的情況，資料無法使用一條線完全分割<strong> ，</strong>此時使用線性分類器的效果就會不如預期</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*mmwMCNFMKbsyIVY4nanwIg.png" /></figure><p>但<strong>支援向量機</strong>與其它線性分類不同，它不只可以應用於線性分割的問題，也可以處理非線性的問題，<strong>其核心架構是由核函數（Kernel function）</strong>與<strong>超平面（Hyperplane）組成，</strong>當遇到線性不可分的資料時，可以透過<strong>核函數將資料映射到高維度的空間，再找出能將資料進行分割的決策邊界（decision boundary），也就是這裡的超平面</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xghC2R69do3GTpX--59PJA.png" /></figure><p>而能將資料分割的<strong>超平面</strong>不會只有一個，支援向量機的主要任務就是要找到<strong>最佳的超平面</strong>，這裡的做法就是假設<strong>超平面</strong>為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*uAzbeXD3ByQN4yPUjsxSaQ.png" /></figure><p>其分類的條件可以看成</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*7rEkODs6GuOE1mBXubGitg.png" /></figure><p>透過上面的公式我們可以得兩個<strong>超平面，</strong>如下圖中的虛線，其中在虛線上的點稱之為<strong>支援向量（support vectors），</strong>要找到<strong>最佳的超平面</strong>就得找出最適的<strong>w（權重）</strong>使兩虛線的<strong>間距（Margin）</strong>盡可能的最大，因為越大的<strong>間距</strong>可以減少越多<strong>泛化誤差（Generalization Error）</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*KuRTTf-CPsSFZ6-YpFUwMA.png" /></figure><p>看到這裡我們可以知道<strong>支援向量機</strong>對於高維度資料的處理能有不錯的效果，且可以處理非線性的分類問題，但若是在面對大樣本的時候因為其計算的方式會導致效率不佳</p><h3><strong>實作</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea903db816315cd949af209f4e1d5e91/href">https://medium.com/media/ea903db816315cd949af209f4e1d5e91/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*0Tnnvp-9LBjtNBpSS-qitw.png" /></figure><blockquote>感謝你閱讀完這篇文章，喜歡文章的不妨給個讚：）</blockquote><ul><li><a href="https://medium.com/@SCU.Datascientist/python%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E5%B8%B8%E8%A6%8B%E7%9A%84%E4%BA%8C%E5%85%83%E5%88%86%E9%A1%9E%E8%A9%95%E4%BC%B0%E6%8C%87%E6%A8%99-%E6%B7%B7%E6%B7%86%E7%9F%A9%E9%99%A3-roc-%E6%9B%B2%E7%B7%9A-f214ecd84dab">【Python學習筆記】常見的二元分類評估指標 — 混淆矩陣、ROC 曲線</a></li><li><a href="https://medium.com/@SCU.Datascientist/python%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-knn-k-nearest-neighbor-531a95336f71">【機器學習筆記】 KNN( K Nearest Neighbor)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80ad4266d592" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Python學習筆記】常見的二元分類評估指標 — 混淆矩陣、ROC 曲線]]></title>
            <link>https://medium.com/@SCU.Datascientist/python%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E5%B8%B8%E8%A6%8B%E7%9A%84%E4%BA%8C%E5%85%83%E5%88%86%E9%A1%9E%E8%A9%95%E4%BC%B0%E6%8C%87%E6%A8%99-%E6%B7%B7%E6%B7%86%E7%9F%A9%E9%99%A3-roc-%E6%9B%B2%E7%B7%9A-f214ecd84dab?source=rss-a13f3c011379------2</link>
            <guid isPermaLink="false">https://medium.com/p/f214ecd84dab</guid>
            <category><![CDATA[機器學習]]></category>
            <category><![CDATA[roc-curve]]></category>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[混淆矩陣]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alex lin]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 03:10:30 GMT</pubDate>
            <atom:updated>2023-06-18T04:49:13.848Z</atom:updated>
            <content:encoded><![CDATA[<h3>【機器學習筆記】常見的二元分類評估指標 — 混淆矩陣、ROC 曲線</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ddAURl97zHA4FWNO" /></figure><p>大家在求學階段肯定都曾經歷過不少考試，也許有不少人在心裡對此有排斥感，但考試的本質其實是來評估我們的學習成果，測試我們辛苦的付出是否有成效</p><p>而在機器學習領域中也是如此，我們需要一些<strong>指標（metrics）</strong>去評估<strong>模型（model）</strong>是否有達到我們期望的成果，不同的演算法使用的指標也不盡相同，本篇會介紹針對<strong>二元分類（Binary classification）演算法</strong>我們常用到的評估指標 — <strong>混淆矩陣、ROC 曲線</strong></p><h4>▶<strong> 混淆矩陣（confusion matrix）</strong></h4><p>當初第一次接觸到混淆矩陣時就感受到其<strong>混淆</strong>的威力，不過在仔細看過一遍後便發現其實並沒有那麼複雜，該矩陣將我們的答案分成四個種情況：</p><ul><li><strong>TP（True Positive）</strong>：<strong>真實</strong>且預測為<strong>真實</strong>，即預測正確</li><li><strong>TN（True Negative）</strong>：<strong>錯誤</strong>且預測為<strong>錯誤</strong>，即預測正確</li><li><strong>FP（False Positive）</strong>：<strong>錯誤</strong>但預測為<strong>正確</strong>，即預測錯誤</li><li><strong>FN（False Negative）</strong>：<strong>正確</strong>但預測為<strong>錯誤</strong>，即預測錯誤</li></ul><p>光看文字解釋的話的確會使人混淆，這裡建議直接用<strong>第一個單字</strong>與<strong>第二個單字</strong>來看，<strong>第一個單字（True／Fales）決定預測的對錯，第二個單字（Positive／Negative）為預測的答案</strong></p><p>在錯誤的情況中，<strong>FP</strong>在統計學中稱為<strong>型一誤差（Type 1 Error），FN為型二誤差（Type ２Error），</strong>在大多數場合下<strong>型一誤差</strong>比較嚴重，該錯誤好比醫生將得癌症的病患判為身體健康的人，要盡量避免</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*ZcblqMXy3oK4BBRJpfQ4_w.png" /><figcaption><strong>混淆矩陣（confusion matrix）</strong></figcaption></figure><p>混淆矩陣的用處不止上述這些，其中還可以延伸出更多指標，以下就舉幾個大家常看到的</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzVy0EAeawVbRZFFGslESg.png" /></figure><h4>▶<strong> ROC曲線（Receiver operating characteristic curve）</strong></h4><p>在前面表格中有提到<strong>召回率（Recall），</strong>其實<strong>召回率也能稱作真陽率（True Positive Rate），</strong>那有真陽率也有<strong>假陽率（False Positive Rate）</strong>，其公式為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*lSObbTBjWiNocJxtj9guvw.png" /></figure><p>它代表的意義為實際為假（陽性）的樣本中預測錯誤的比重</p><p><strong>ROC曲線</strong>就是以<strong>FPR為X軸，TPR為Y軸</strong>所繪製而成的曲線，線上的點則是我們針對模型輸出的<strong>目標機率值</strong>設定不同的<strong>閾值（threshold），</strong>並利用閾值去判定目標類別，最後就能得到很多點連成一條線，如<strong>圖(一)，</strong>當<strong>threshold = 0.3 ，label = P 的樣本有4個大於等於0.3，而 label = N 的樣本只有1個，因此TPR = 4/4，FPR = 1/3</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*uc_5hyZ9nthZZTTrwjmC5w.png" /><figcaption><strong>圖(一)</strong></figcaption></figure><p>看到這裡可能你還不知道要如何用ROC曲線去評估模型，回想一下前面說到的，曲線上的每一個點代表的是不同 threshold 時模型的FPR與TPR，因此曲線越靠左上方移動，表示該模型對正樣本（P）的敏感度越高，且FPR越低，模型的效益較佳</p><p>另外也能透過ROC曲線下的區域，<strong>圖(二)</strong>灰色部分稱之<strong>AUC（Area Under Curve）</strong>去評估模型，其優點為較不受樣本均勻度影響，一般我們會認為：</p><ul><li><strong>AUC = 1 ：</strong>最理想的情況</li><li><strong>AUC &gt; 0.5 ：</strong>模型有效，越大性能越好</li><li><strong>AUC = 0.5：</strong>模型無鑑別力</li><li><strong>AUC &lt; 0.5：</strong>可透過反向預測來使用模型</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*wQQCDk45_l8NPie3TIc4xQ.png" /><figcaption><strong>圖(二)</strong></figcaption></figure><h3><strong>實作</strong></h3><p>這裡直接拿 scikit-learn 提供的<a href="https://ogrisel.github.io/scikit-learn.org/sklearn-tutorial/auto_examples/plot_roc.html"><strong>範本</strong></a>當範例，想了解更多的可以直接去看文檔</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1de423d92e8c5d0bbb6a69d08e0c579f/href">https://medium.com/media/1de423d92e8c5d0bbb6a69d08e0c579f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*oFq2gUixIAmPvFvfA3nohQ.png" /></figure><blockquote>感謝你閱讀完這篇文章，喜歡文章的不妨給個讚：）</blockquote><ul><li><a href="https://medium.com/@SCU.Datascientist/python%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-knn-k-nearest-neighbor-531a95336f71">【Python學習筆記】 KNN( K Nearest Neighbor)</a></li><li><a href="https://medium.com/@SCU.Datascientist/python%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E6%B1%BA%E7%AD%96%E6%A8%B9-decision-tree-b9acf11f0f84">【Python學習筆記】決策樹(Decision tree)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f214ecd84dab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>