<?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 Jason on Medium]]></title>
        <description><![CDATA[Stories by Jason on Medium]]></description>
        <link>https://medium.com/@jason8410271027?source=rss-effe333bc878------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6BX34tAk8Yz09cP2JzEk5A.jpeg</url>
            <title>Stories by Jason on Medium</title>
            <link>https://medium.com/@jason8410271027?source=rss-effe333bc878------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 17:01:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jason8410271027/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[小白專屬的快速入門Podman小筆記]]></title>
            <link>https://medium.com/@jason8410271027/%E5%B0%8F%E7%99%BD%E5%B0%88%E5%B1%AC%E7%9A%84%E5%BF%AB%E9%80%9F%E5%85%A5%E9%96%80podman%E5%B0%8F%E7%AD%86%E8%A8%98-bedee85ef512?source=rss-effe333bc878------2</link>
            <guid isPermaLink="false">https://medium.com/p/bedee85ef512</guid>
            <category><![CDATA[podman]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 07:20:28 GMT</pubDate>
            <atom:updated>2024-10-12T07:20:28.126Z</atom:updated>
            <content:encoded><![CDATA[<p>這篇學習筆記，是專門給像我一樣，完全沒碰過Docker和Podman的人，來快速的學習Podman的基本操作與實務流程。所以整篇的含金量可能不高，但還是希望可以幫助像我一樣，想學習、了解但卻又不知道如何下手的人。</p><p>相信會來看這篇的朋友，無疑已經在網路上爬過文了，也大概知道Docker與Podman之間的差異，以及為甚麼開始有些人跳槽到podman去。如果不知道也沒關西，以下簡單的懶人包：</p><p>●K8s棄用Docker(但也不是整個棄用，有興趣的可以去爬文一下)</p><p>●Docker要開始對商業使用行為收費</p><p>●Podman跟Docker用起來幾乎一樣</p><p>●Podman不用錢</p><p>●K8s支援Podman</p><p>其實有其他人解釋得更精確啦，畢竟自己真的是小白，在這之前也沒碰過Docker，所以很難詳細解釋上述的原因。有興趣的可以再針對上述幾點去研究一下。</p><p>廢話不多說，直接來講解一下我要帶的實務範例：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3737dmwZDmbk28ltiePkw.png" /><figcaption>範例圖示</figcaption></figure><p>這次我的範例是想要寫一個簡單的程式，程式功能是可以把某資料夾內jpg檔，全部複製到另一個資料夾內。所以當程式寫好後，我必須用Podman把這程式包起來存成image，並且把這個image裝進Container裡面。接著我再把包裝好的程式，載入到另一台電腦，來模擬我程式寫好後，部屬到其他電腦執行的過程。</p><p>範例中的A、B電腦，分別為我的本機和虛擬機，虛擬機的話我用Linux。當然如果剛好你有兩台電腦，而且安裝Podman的過程相當順利的話，你也可以依照你的方式。差異只是在於安裝方法，會有些小地方要注意而已。這裡我也會帶到Windows安裝，和Linux安裝方式。至於虛擬機怎麼安裝，就不是本篇文章的重點了，如果想安裝可以先去下載VirtualBox，和Ubuntu的印象檔。然後再選擇Ubuntu印象檔的時候請注意！！！請安裝「20.10」以上的版本，不然Linux會裝不起來。</p><h3>Windows安裝：</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6k1kNWm44UuQg5ENH-qiQ.png" /><figcaption>Podman desktop</figcaption></figure><p>首先先到<a href="https://podman-desktop.io/">Podman Desktop</a>的官網，然後中間大大的Download Now給他按下安裝。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zeJV6jBrO6oJhmefve5Xyg.png" /><figcaption>開啟Podman Desktop，並讓他跑一下，然後點選Set up</figcaption></figure><p>下載並安裝完成後，原則上你的桌面就會出現Podman Desktop的圖示。接著直接開啟，這時候請先稍微等一下，Podman Desktop這時候會自動偵測，目前你還缺少甚麼東西，完成後他會告訴你，如上圖所示。這時候你就只要點下Set up，他就會自動幫你完成一些設定。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ah2SmllbvciPVpwZtkaaQ.png" /><figcaption>偵測到還沒有安裝Podman，這時候點Next就好</figcaption></figure><p>如果你是第一次安裝Podman，那你應該會看到跟上圖一樣的警示，告訴你還沒有真的裝Podman。這時候就只要照著他的步驟，點「Next」即可。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KozIKf6r402-JTPlQIMX2A.png" /><figcaption>Podman安裝確認，點選Yes即可</figcaption></figure><p>點「Next」後還會跳出安裝確認訊息，這時候點「Yes」。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50lCUA8aKygJhiZ6Q0-EjA.png" /><figcaption>Podman安裝</figcaption></figure><p>Podman會使用到wsl，所以「Install WSL if not present」記得要勾選。勾選完後直接按Install。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTp0xZtOfIkX1zrccoMhxw.png" /></figure><p>安裝完Podman後，回到Podman Desktop，會看到還有一些流程要確認。但大多都是說明等等之類的，反正到這裡一直無腦案Next即可，後面我就不一一列出來拖檯費了。以上就是Podman在Windows的安裝方式。</p><h3>Linux安裝：</h3><p>在講解步驟之前，先跟大家再次講一下我這邊的Linux環境。我這邊是透過VirtualBox開啟Linux，然後是使用Ubuntu 20.10以上的版本。版本的部分很重要所以一定要注意。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6k1kNWm44UuQg5ENH-qiQ.png" /><figcaption>Podman desktop</figcaption></figure><p>首先一樣到<a href="https://podman-desktop.io/">Podman Desktop</a>的官網，然後點選下載。下載的時候請確認一下是否為Linux版本，雖然照理來說，這邊它會自動幫你偵測你的作業系統。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*gWLPW9L23sFG2jnIMeJWpQ.png" /><figcaption>安裝flatpak</figcaption></figure><p>當你下載完Podman Desktop後，你會發現安裝檔是一個名為flatpak的東西。這東西主要就是拿來包裝程式、應用軟體用的，讓你在Linux可以快速地安裝。所以想安裝Podman Desktop前，請先上網找Flatpak，並點選「<a href="https://flatpak.org/setup/Ubuntu">Ubuntu Quick Setup</a>」。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tws6PA2jX3P2dV__OYMCzQ.png" /><figcaption>Ubuntu Quick Setup頁面</figcaption></figure><pre>sudo apt install flatpak</pre><pre>flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo</pre><p>進來後會發現裡面要你執行以上指令，所以原則上只要開啟終端機，然後執行頁面裡要執行的東西就好了。如果不確定要執行哪些的話，上面這兩行是懶人包。不過這有可能隨著版本，或自身電腦環境而有所差異，所以還是建議大家直接點進<a href="https://flatpak.org/setup/Ubuntu">flatpak官網</a>，並且依據你當前的需求和環境來安裝。然後安裝完後，<strong><em>請記得「重新啟動」虛擬機</em></strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*PAIeGiqXWhOApLYpXkIkwg.png" /><figcaption>安裝podman-desktop示意圖</figcaption></figure><pre>cd Downloads</pre><pre>flatpak install podman-desktop-1.12.0.flatpak</pre><p>下一個步驟，就是來安裝Podman Desktop。首先開啟終端機，並且輸入「cd Downloads」，意即進入到Downloads的資料夾裡。因為沒意外的話，大家剛剛下載的Podman Desktop安裝檔，都會被預設裝在Downloads的資料夾裡。</p><p>接著再輸入「flatpak install podman-desktop-1.12.0.flatpak」。這裡注意一下指令的組成，基本上「flatpak install」這一句是固定的，而後面接著就是你這<strong><em>Podman Desktop安裝檔的全名</em></strong>。所以<strong><em>這裡不要真的傻傻的照抄</em></strong>。尤其你是隔了好幾年才來看這篇的話。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjvXrA4-C9ybHHsyqS2a0w.png" /><figcaption>安裝完成</figcaption></figure><p>安裝完成後，開啟Ubuntu類似Windows的「開始」按鈕，你就會發現Podman-Desktop的icon。這時候就可以開啟他。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4f-o4koAyjk31J6E2yoYA.png" /><figcaption>開啟畫面</figcaption></figure><p>開啟後Podman-Desktop一樣會幫你檢查環境，看來缺漏那些東西，或是建議你安裝甚麼。其實在這裏最重要的，是最右邊的Podman。所以不想裝那麼多的話，可以指勾選最右邊的Podman。我自已是都全部裝拉，免得之後要用到。如果像我一樣全都裝的話，原則上一直無腦按確認跟下一步即可。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WBxdJ9Anq5goQAk09_pxA.png" /><figcaption>安裝podman</figcaption></figure><p>輪到安裝Podman的時候，就會出現以上的圖示，然後你也會發現沒辦法無腦按下一步。所以這時候時候，請點選紅色框方的連結。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f4WgRqwj3xqIlSGey197jg.png" /><figcaption>安裝Podman指令</figcaption></figure><p>點選上方連結後，會自動開啟上圖的網站。這時候請往下找「Ubuntu」的安裝方式，然後就照著說明，開啟終端機並一行一行的執行安裝指令。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bWi7XpIjgZCnUAHPwRPeQ.png" /></figure><p>當你都執行完以上指令後，就代表你完成了podman的安裝。這時候回到Podman Desktop也會發現。視窗的右下角多了「Next」可以按，這時候就只要「Next」一直按下去就好了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PVrQ5M1nTHnBRwoDVklS1Q.png" /><figcaption>Linux的Podman Desktop成功示意圖</figcaption></figure><p>當我們在Windows 和Linux上安裝完Podman後，我們就可以開始前面所講的範例，首先程式如下：</p><pre>import os<br>import shutil<br><br>source_folder = &quot;/Downloads&quot; #路徑麻煩請先跟我一樣<br>destination_folder = &quot;/Podman_testing&quot; #路徑麻煩請先跟我一樣<br>for filename in os.listdir(source_folder):<br>    if filename.endswith(&quot;jpg&quot;) or filename.endswith(&#39;JPG&#39;):<br>        file_path = os.path.join(source_folder, filename)<br>        dest_path = os.path.join(destination_folder, filename)<br>        shutil.copy2(file_path, dest_path)<br>        print(f&quot;已複製檔案: {file_path}&quot;)</pre><p>上面是一個簡單的Python程式，就如前面的範例說明。它能夠將某資料夾內的jpg檔，複製到另一個資料夾內。當這個程式寫好，而且在你local端確定可以執行後，接著我們就必須寫一個Dockerfile。Dockerfile可以現在跟你程式同一個目錄下，以我為例我是將程式寫在名為podmanPractice的目錄。所以我就直接在podmanPractice目錄下，建立一個Dockerfile。然後這裡要注意的是，你就直接建立名為「Dockerfile」的檔案，然後不須副檔名：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*5H1ogqOBO5nK_tIoM0nkYQ.png" /><figcaption>檔名直接叫做Dockerfile，不需要副檔名</figcaption></figure><p>接著我們在Dockerfile必須設定以下幾個東西：</p><pre># 基礎鏡像(image)，container的操作環境<br>FROM python:3.9-slim<br><br># Container的工作目錄<br>WORKDIR /podmanPractice<br><br># 把當前目錄下的檔案，複製到Container內的目錄下<br>COPY . .<br><br># 安裝Python所需的套件<br># RUN pip install --no-cache-dir -r requirements.txt<br><br>#讓Container對外連接的port，需而外在Podman設定。<br>#EXPOSE 5000<br><br># 啟動Container的指令。<br>CMD [&quot;python&quot;, &quot;testing.py&quot;]</pre><p>簡單說一下每行指令代表甚麼意思。「FROM python:3.9-slim」就是指你這個Container的操作環境。因為我這裡是要執行Python的程式，所以理所當然的我用Python 3.9。</p><p>「WORKDIR /podmanPractice」是指Container內的目錄。Container你可以想像成就是一個虛擬機(虛擬的電腦)，所以裡面也會有它自己的目錄。因此我們的程式，就必須放在它的目錄下。</p><p>「COPY . .」這句就如前面剛剛說的，我們要把程式放在這個Container裡面，這樣Container才可以去run這隻程式。</p><p>「RUN pip install — no-cache-dir -r requirements.txt」。這句代表我要安裝Python的附加套件。例如我這隻程式有用到pandas、statsmodels、 sklearn...etc。那我就必須先開啟一個txt檔，然後把這些套件的安裝指令寫進去，並且儲存在同一個目錄下。這樣Container在執行程式的時候，就會會順便安裝這些東西。不過在這邊剛好我的程式不會用到，所以就先給它註解起來。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*N9iaZHRiFUJYfXQ5VA2bHw.png" /><figcaption>把有使用到的套件名稱寫進去.txt檔</figcaption></figure><p>「EXPOSE 5000」簡單來說就是，如果你這個Container要對外開放，那你就必須開一個Port讓它可以取得。不過這功能我倒是沒實際用過，有興趣的可以在自己專研一下。就chatGPT的解釋，它也不是真的像API一樣真的在網路上對外開放連結，實際使用還是要去Podman那邊去做些設定。</p><p>「CMD [“python”, “testing.py”]」，就是啟動Container的指令。誇號內第一個參數，簡單來說就是告訴Container，現在要執行甚麼程式。例如現在是要執行Python的程式，你就直接寫python。如果是C#，那可能就是dotnet。第二個參數就是你程式的檔名。</p><p>當程式和Dockerfile寫完後，我們就要來建立這個image，以本範例來說，建立方式就是在終端機上輸入：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*QqIiKk3SoKmoz3bmhGHHGw.png" /><figcaption>建立image</figcaption></figure><pre>podman build -t copy-pic-image .<br>#podman build -t &lt;image name&gt; .</pre><p>指令當中，podman build -t 是固定的語法，接著後面就是你要儲存的檔名。最後最後，一定要記得這個「.」，這代表在當前目錄下尋找Dockerfile，這樣才可以產生對應的image。</p><p>執行成功後，我們就可以打開Podman Desktop，然後點開image(下圖紅色方框)就可以發現我們建立好的image：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ufvy0kxz3ixQc1BEppegbg.png" /><figcaption>image列表</figcaption></figure><p>這時候你就可以稍微執行看看，首先點選上圖的執行按鈕，然後會跳出以下的畫面：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pN2i5A1SMea5yOV01JFyg.png" /><figcaption>Create Container</figcaption></figure><p>上圖畫面斗大的標題，相信不難知道接著我們要建立Container，來去執行我們的image。如果你不理它直接執行的話也是可以，它就會隨機幫你建立一個Container來去執行，然後這Container也會保留，所以你下次要再Run一次程式的時候，就只要去執行這個Container就好，不需要再創立一個。不過它給你的Container名子就挺奇怪的，所以還是建議自己設定一下Container名稱：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*0WY2WxsXvB3QQiXTbbD3-A.png" /></figure><p>接著麻煩幫我特別注意上圖。首先Container name就設定你自己的Container名稱，這沒什麼大問題，但下面的Volumns就要特別留意。首先Container就是一個虛擬環境，相信這句話已經聽到不想再聽了。但不過想想我們的範例程式，要把某資料夾內所有的jpg檔，複製到另一個檔案。以我目前的範例就是，把Downloads資料夾內的所有jpg，複製到桌面名為Podman_testing的資料夾。上面的範例，在Windows上很好理解，但是在Container裡面，根本沒有所謂的C槽和D槽。所以你給他去執行它會告訴你根本沒這些路徑：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZPRJXaFfai9JufTe87stg.png" /></figure><p>所以這要怎麼解？很簡單，找個替身給它就好：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HocWDkdKsBQaTdRLyDQQag.png" /></figure><p>這個替身的意思就是，我在Container那邊建立一個名為「/Downloads」的路徑，來代替Windows這邊的「C:\Users\User\Downloads」。「/Podman_testing」就是來代替Windows的「C:\Users\User\Desktop\Podman_testing」。所以這也是為甚麼最一開始Python的程式，我有特別註解：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1hfTtD-HDkbJIdV-YBfeQ.png" /><figcaption>程式裡的路徑不是以你本機為主，要以你Container裡的路徑為主！！！</figcaption></figure><p>至於怎麼建立？很簡單，左邊設定你本機的路徑，右邊就設定你Container的代替路徑：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWhKoub1ibukTdWH6_f3Xw.png" /></figure><p>設定完後，就可以直接點選下面的「Start Container」，然後畫面就會直接跳到這裡：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*CWh121F-Owwz0grBloiYpQ.png" /></figure><p>因為這隻程式run完就結束，所以你看到上面的畫面不用害怕，這很正常。如果想看運行結果，可以點選上方的Logs：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6iM0TlA5hocD_5ZDB2PW1Q.png" /><figcaption>運行結果</figcaption></figure><p>Ok，講那麼多。那如果今天我要在別台電腦運行這程式怎麼辦？這是就可以派出我們剛剛建立的Linux來模擬。首先先把這個image載下來：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHPMvcKsxGXZqbOBJW3K6w.png" /></figure><p>下載完後，會有一個副檔名為.tar的檔案，接著你可以把這個檔案先暫存到你的雲端。完成後你可以開啟你的Linux，並下載你上傳的image到任一路徑，接著打開你Linux的Podman Desktop，並匯入這個image：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-YXhjnrsIN-ws5WlGib5g.png" /></figure><p>image載入完以後，就跟前面在Windows的操作一樣。唯一一樣要注意的是，路徑的設定。在Linux這裡就很明顯與Windows路徑不同。但不用緊張，原理都一樣。以我這邊為例，我的照片存放在「/home/jason/Pictures」裡，然後我照片想要複製到「/home/jason/Desktop/CopyPicture」的路徑下，所以我在建立Container時，設定就會如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0SqC_JDO7tGbt74DYx4ZA.png" /></figure><p>這時候按下面的「Start Container」，就可以看到照片成功的複製到另一個資料夾。以上就是如何在別台電腦上，透過Podman執行同一支程式的範例。</p><p>以上內容，主要是以新手做筆記的角度，來記錄如何快速學習Podman的基本操作與實務範例。所以內容或許挺「水」的。簡單來說，我只是也順便帶領大家入門而已，至於要走多深，還是必須透過大家自己的努力，我自己也會繼續鑽研這塊。總之希望這篇有幫助到大家，如果內容有不清楚、有誤。也歡迎理性提出與指教，來幫助更多人。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bedee85ef512" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Python & C#】Quick Sort]]></title>
            <link>https://medium.com/@jason8410271027/python-c-quick-sort-696f045874a2?source=rss-effe333bc878------2</link>
            <guid isPermaLink="false">https://medium.com/p/696f045874a2</guid>
            <category><![CDATA[algotrading]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[quicksort]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 09:37:04 GMT</pubDate>
            <atom:updated>2024-04-27T09:37:04.949Z</atom:updated>
            <content:encoded><![CDATA[<p>Quick Sort is also a very powerful and high performance Sorting Algorithm. And guest what? It’s similar to Merge Sort based on the Divide and Conquer. So, let’s take a look at how this powerful algorithm works.</p><p>By the way, today’s content all refers to:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpM-6r5xsNEY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpM-6r5xsNEY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpM-6r5xsNEY%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/d2e09f35e76c879d2d847422fee1b8c6/href">https://medium.com/media/d2e09f35e76c879d2d847422fee1b8c6/href</a></iframe><p>This video helped me a lot! So, I’m just using his content and making a notes, while also practicing my English at the same time. As you know, I’m not a English native speaker.</p><p>You can see Quick Sort as playing the partition game just like the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yeA_5LmVmJLrfXc1t837mA.png" /></figure><p>The regulation of this game is that we need to choose one of the number become <strong>pivot</strong>. After that, we need to think about how to let all of the number on the left smaller than the pivot, and all of the numbers on the right greater than pivot.</p><p>You might ask: How to choose the pivot? Actually, you can choose any number to become pivot. In other words, you can just like the video, let the medium number become the pivot. Or you can choose the first or last number to become the pivot. Due to the video have already choose medium number. So I decide to choose the first number to become pivot.</p><p>For example this is our data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*gV8REsh9gpwlr81j-fnLvg.png" /><figcaption>Original Data</figcaption></figure><h3>Step1: Set up 「l」, 「r」 and 「pivot」</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*uYKVs-r-zkGtnjX5cShZbQ.png" /></figure><p>「l」 means the left. Initially, it starts from the first element. The same goes for 「r」. Pivot also at the same place with 「l」, I marked it in green.</p><h3>Step2: Let 「l」 and 「r」 compare with pivot</h3><p>In here we can break down few steps:</p><p><strong>Step2.1: Find the number greater or equal the pivot.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*JSKmLY7Bpw2U_fOuvFsWEg.png" /></figure><p>Based on the example above. Number of 「l」 and pivot all are the 5. So, let the 「l」 just stay at the same place. But if 「l」 is not greater than the pivot, then 「l」 need to step forward until find it.</p><p><strong>Step2.2: Find the number smaller or equal the pivot.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*60yna_3WvvPBw8s9ei3BeQ.png" /></figure><p>Luckily, the number of「r」 already smaller than pivot. So, let 「r」 just stay right here. Also same as last step, if 「r」 is not small than the pivot, then 「r」 need to step forward until find it.</p><h3>Step3: Compare 「l」 and 「r」 together.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*JOCt9oIQPUyQW__DFJrsLw.png" /></figure><p>In this step, we need to compare number of 「l」 with number of 「r」. If number of 「l」 greater than 「r」, then swap these two data. After swap these two data, 「l」 and 「r」 need to move step forward.</p><h3>Step4: Repeating Step2 until 「l」 and「r」 have cross each other</h3><p>Maybe some people will get confused in this step, so let me keep demonstrating how it works:</p><p><strong>Step2.1: Find the number greater or equal the pivot.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*sgpwAL0CofytYbdc3lefkg.png" /></figure><p>Just like what I said before, 「l」 needs to find the number which greater or equal pivot. So, in this case we find the 5.</p><p><strong>Step2.2: Find the number smaller or equal the pivot.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Nrq1z-jWvcBrenLfMTzJww.png" /></figure><p>The number of 「r」 is already smaller then the pivot. However, 「l」 and「r」 have already crossed each other, so it means this round already finished. Then, we need to remember the index value of 「l」, which is 5.</p><p>After finish round 1, you can easily see that we not only placed the 5 in the correct position, but also divide this array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*EG8zyr58113SCLRJpV2Rpg.png" /></figure><p>In other words, in the next round we have two sets of data that need to be sorted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*c99xaM6BBcXGuc0i-R1ntg.png" /></figure><p>So, how about round 2? Let me keep demonstrating for you:</p><h3>Step1: Set up 「l」, 「r」 and 「pivot」</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*Pzg3WQSTSzsBRUgxTN8Smg.png" /></figure><h3>Step2: Let 「l」 and 「r」 compare with pivot</h3><p><strong>Step2.1: Find the number greater or equal the pivot.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*8V-HG2tfiq5p_cGVstUdeA.png" /></figure><p><strong>Step2.2: Find the number smaller or equal the pivot.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*f-RKlaDWzBT-va1KEXHwPg.png" /></figure><h3>Step3: Compare 「l」 and 「r」 together.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*WQuG3fJeVoAG9bgEBMIiTg.png" /></figure><h3>Step4: Repeating Step2 until 「l」 and「r」 have cross each other</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*c5_OkiEfGQqMMdeEJB47qw.png" /></figure><p>So, Is round 2 finish yet? The answer is no. Why? Because we just finished sorting set 1 data, and we still have set 2 data needs to be sorted. But luckily, in set 2 there is only one data in it, which means that no matter whether 「l」,「r」 or the pivot, they are all the same. So, just let it swap with itself.</p><p>After that, you can find out we not already placed 1 in the correct position, but also that this data has already been divide into 3 sets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*mdXL1zKtGqYpemHV_wrZ7g.png" /></figure><p>Alright, so we just need to repeat these four steps, then we can easily get the answer we want.</p><p>If don’t have any problems about the concept of Quick Sort, then we can take a look at how to implement in Python and C#:</p><pre>#Python<br>def QuickSort(Data, l, r):       <br>    if l&lt;r:    <br>        pivot = Data[l] <br>        index = Partition(l , r, pivot)<br>        QuickSort(Data, l, index-1)<br>        QuickSort(Data, index, r)             <br>    return Data<br>       <br>def Partition(l, r, pivot):<br>    while l&lt;=r:<br>        while Data[l] &lt; pivot: #find the number which greater than pivot.<br>            l=l+1<br>        while Data[r] &gt; pivot: #find the number which smaller than pivot.<br>            r = r-1<br>        if l &lt;= r: #if l and r haven&#39;t cross each other, than swap the data.<br>            temp = Data[l]<br>            Data[l] = Data[r]<br>            Data[r] = temp<br>            l = l+1<br>            r = r-1<br>    return l #retun the l that the computer now how to divide this data.<br>            <br>Data = [5,4,1,3,2]<br>print(QuickSort(Data, 0, len(Data)-1))</pre><pre>//C#<br>static void Main(string[] args)<br>{<br>    int[] Data = new int[] { 5,4,1,3,2};<br>    var Ans = QuickSort(Data, 0, Data.Length-1);<br>}<br>static int[] QuickSort(int[] Data, int l, int r)<br>{<br>    if (l &lt; r)<br>    {<br>        int pivot = Data[l];<br>        int index = Partiton(Data, l, r, pivot);<br>        QuickSort(Data, l, index - 1);<br>        QuickSort(Data, index, r);<br>    }<br>    return Data;<br>    <br>}<br>static int Partiton(int[] Data ,int l, int r, int pivot)<br>{<br>    while (l &lt;= r)<br>    {<br>        while (Data[l] &lt; pivot) //find the number which greater than pivot.<br>        {<br>            l++;<br>        }<br>        while (Data[r] &gt; pivot) //find the number which smaller than pivot.<br>        {<br>            r--;<br>        }<br>        if (l &lt;= r) //if l and r haven&#39;t cross each other, than swap the data.<br>        {<br>            int temp = Data[l];<br>            Data[l] = Data[r];<br>            Data[r] = temp;<br>            l++;<br>            r--;<br>        }<br>    }<br>    return l;//#retun the l that the computer now how to divide this data.<br>}</pre><p>Finally, let’s take a look at performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*ikS_hzV_ZDeMseUZEWlOhg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=696f045874a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【C# & Python】Merge Sort]]></title>
            <link>https://medium.com/@jason8410271027/c-python-merge-sort-19e781c76157?source=rss-effe333bc878------2</link>
            <guid isPermaLink="false">https://medium.com/p/19e781c76157</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[merge-sort]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 15:01:40 GMT</pubDate>
            <atom:updated>2024-04-19T15:04:54.440Z</atom:updated>
            <content:encoded><![CDATA[<p>Merge Sort is one of the powerful Sorting Algorithms. Many interviewers use it to test their interviewees. So, let’s take a look at this powerful Sorting Algorithm and see how smart it is.</p><p>Merge Sort is the algorithm that based on the divide and conquer. So, what does &quot;divide and conquer&quot; means? Briefly speaking, divide and conquer means braking the problem into many small and easy to solve problems, then solving each of these problems and combining all of the answers to get the final answer. We can take a look at the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEoNEW3wsPCezFLTcLuNkg.png" /></figure><p>This picture illustrate how Merge Sort works based on the divide and conquer. As you can see, Before start to sort all of these data, we need to break down the entire data. After that, we can begin sorting and combining these data until we get the answers.</p><p>After know about the divide and conquer, we can take a look at how Merge Sort exactly works：</p><h4>Step 1: Break down the data.</h4><p>For example this is the original data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*1kF-NMxmAL-wamFx2pg-1g.png" /><figcaption>Original Data</figcaption></figure><p>So, the way to break down this data is to find the medium number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*cEsoXz33kIhp0gp8_APA4g.png" /><figcaption>Break down the data</figcaption></figure><p>After break down the data, we can get the data like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJT1e8FljorJQRxSCwbXzQ.png" /><figcaption>After break down the data</figcaption></figure><p>But we haven’t break down all of the data yet. So, based on the algorithm, let’s continue to break down the data on the left side first:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fi2svG3Q6YV-alLSLPQ01w.png" /><figcaption>Keep break down the data on the left.</figcaption></figure><h4>Step 2: Sort and merge data.</h4><p>Okay, we have already broken down all the data on the left. So, we can start to sort these data and merge it together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQJTMlt1_7Yad25A2-Asmg.png" /><figcaption>Sort and merge</figcaption></figure><p>As you can see, we have already sorted 4 and 5. But {1,3,2} these three data haven’t been sorted yet. So, we just need to repeat step 1 and step 2：</p><h4>Step 1: Break down the data.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Q5yAhOeN41R9iOaTzoXgA.png" /><figcaption>Break down the data</figcaption></figure><p>This time, we find out the data on the right haven’t been completely broken down. So, we continue to break down the data on the right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3-MwJ1F2T87u6jHrAZMpw.png" /><figcaption>Continue to break down the data on the right</figcaption></figure><h4>Step 2: Sort and merge data.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CxzZYDNYloVpap2YblcDg.png" /><figcaption>Sort and merge</figcaption></figure><p>Okay, the next few steps are very crucial. Also I believe lots of people get confused. Right now, we have already sorted 2 and 3 and let these two data combined together. So, the next step is to combine 2 and 3 with the {1}. But be careful! we need to sort these data first, and then combine them together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ox6Z6AyNruJZURZygJ3S8Q.png" /></figure><p>As you can see, we have already combined the data as shown in the picture above. So right now we only have {4,5} and {1,2,3} these two datasets need to be sorted and merged:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0csuX9vwL90KXA-sj8qJ8A.png" /></figure><p>Overall, this is how Merge Sort works. So let’s take a look at how to implement Merge Sort in Python and C#:</p><pre>#Python:<br>def Divide(Data):<br>    if(len(Data)==1):<br>        return Data<br>    medium = len(Data) // 2<br>    left=[]<br>    right=[]<br>    for i in range(0, medium):<br>        left.append(Data[i])<br>        <br>    for i in range(medium, len(Data)):<br>        right.append(Data[i])<br>        <br>    left = Divide(left)<br>    right = Divide(right)<br>    return Merge(left,right)<br>    <br>def Merge(left,right):<br>    temp = []<br>    while(len(left)&gt;0 and len(right)&gt;0):<br>        if(left[0] &gt; right[0]):<br>            temp.append(right[0])<br>            right.pop(0)<br>        else:<br>            temp.append(left[0])<br>            left.pop(0)<br>    if(len(left)!=0):<br>        for i in range(0, len(left)):<br>            temp.append(left[i])<br>            <br>    if(len(right)!=0):<br>        for i in range(0, len(right)):<br>            temp.append(right[i])<br>            <br>    return temp<br>        <br>Data = [5,4,1,3,2]<br>print(Divide(Data))</pre><pre>//C#<br>static void Main(string[] args)<br>{<br>    List&lt;int&gt; Data = new List&lt;int&gt;() { 5,4,1,3,2 };           <br>    Output(Divide(Data));<br>    Console.ReadKey();<br>}<br>static List&lt;int&gt; Divide(List&lt;int&gt; Data)<br>{<br>    if (Data.Count == 1)<br>    {<br>        return Data;<br>    }<br>    int medium = Data.Count / 2;<br>    List&lt;int&gt; left = new List&lt;int&gt;();<br>    List&lt;int&gt; right = new List&lt;int&gt;();<br>    for (int i = 0; i &lt; medium; i++)<br>    {<br>        left.Add(Data[i]);<br>    }<br>    for (int i = medium; i &lt; Data.Count; i++)<br>    {<br>        right.Add(Data[i]);<br>    }<br>    left = Divide(left);<br>    right = Divide(right);<br>    return Merge(left, right);          <br>}<br><br>static List&lt;int&gt; Merge(List&lt;int&gt; left, List&lt;int&gt; right)<br>{<br>    List&lt;int&gt; temp = new List&lt;int&gt;();<br>    while (left.Count &gt; 0 &amp;&amp; right.Count &gt; 0)<br>    {<br>        if (left[0] &gt; right[0])<br>        {<br>            temp.Add(right[0]);<br>            right.RemoveAt(0);<br>        }<br>        else<br>        {<br>            temp.Add(left[0]);<br>            left.RemoveAt(0);<br>        }<br>    }<br>    if (left.Count != 0)<br>    { <br>        for (int i = 0;i &lt; left.Count;i++) <br>        {<br>            temp.Add(left[i]);<br>        }<br>    }<br>    if (right.Count != 0)<br>    {<br>        for (int i = 0; i &lt; right.Count; i++)<br>        {<br>            temp.Add(right[i]);<br>        }<br>    }<br>    return temp;<br>}<br><br>//This function is just for showing the answer.<br>static void Output(List&lt;int&gt; Data)<br>{<br>    string res = &quot;&quot;;<br>    for (int i = 0; i &lt; Data.Count; i++)<br>    {<br>        res = res + Data[i] + &quot;,&quot;;        <br>    }<br>    res = res.Substring(0, res.Length - 1);<br>    Console.WriteLine(res);<br>}</pre><p>As you can see, Merge Sort needs to be implemented by recursively. It might be not easy to understand for beginners. So I highly recommend trying to execute these codes one by one, it will help you understand how Merge Sort works.</p><p>In the ended, let’s take a look at how powerful Merge Sort is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*kVFkG1lgW_46-ZN--BUaNQ.png" /><figcaption>performance of Merge Sort</figcaption></figure><p>This is today’s topic. I hope it can help you understand Merge Sort. If I have any mistakes, don’t be hesitate to correct me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19e781c76157" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Python & C#】Bubble Sort]]></title>
            <link>https://medium.com/@jason8410271027/python-c-bubble-sort-0df0a1f0727b?source=rss-effe333bc878------2</link>
            <guid isPermaLink="false">https://medium.com/p/0df0a1f0727b</guid>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[bubble-sort]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 07:08:48 GMT</pubDate>
            <atom:updated>2024-04-05T07:08:48.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Bubble Sort was the first algorithm I learned in my life. Even though it’s the simplest algorithm among sorting algorithms, I still spent all night trying to understand and implement it in C# when I first time to study it. So, let’s see what Bubble Sort is and how it works.</p><p>Step 1: Find the j and j+1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QOT_1X5xoSFAFIjkOs0cA.png" /></figure><p>In round 1, j starts from the first element, and j+1 is after j.</p><p>Step 2: Compare j and j+1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnTH-M_JwfkwtSzKXCtzNA.png" /></figure><p>In step 2, if j+1 smaller than j, swap these two data directly.</p><p>Step 3: Moving j and j+1 to the next position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*_PLAN1y7HuDpgj0iDabZEw.png" /></figure><p>After moving j and j+1 to the next position, we simply return to the step 1. In other words, Bubble Sort just repeats these 3 steps. So, is not that hard, is it?</p><p>So, let’s take a look how to implement Bubble Sort in Python and C#：</p><pre>#Python<br>Data = [4,5,1,3,2]<br>for i in range(0, len(Data)):<br>    for j in range(0, len(Data)-1):<br>        if(Data[j] &gt; Data[j+1]):<br>            temp = Data[j]<br>            Data[j] = Data[j+1]<br>            Data[j+1] = temp<br>    print(Data)</pre><pre>//C#<br>static void Main(string[] args)<br>{          <br>    int[] arr = new int[] { 5, 4, 1, 3, 2 };<br>    for (int i = 0; i &lt; arr.Length-1; i++)<br>    {<br>        for ( int j = 0; j &lt; arr.Length - 1 - i; j++)<br>        {<br>            if (arr[j] &gt; arr[j+1])<br>            {<br>                int temp = arr[j];<br>                arr[j] = arr[j+1];<br>                arr[j+1] = temp;<br>            }<br>        }<br>        Output(arr);<br>    }            <br>    Console.ReadKey();<br>}<br>static void Output(int[] arr)<br>{<br>    string ans = &quot;&quot;;<br>    for (int i = 0; i &lt; arr.Length; i++)<br>    { <br>        ans += arr[i] + &quot;,&quot;;<br>    }<br>    ans = ans.Substring(0, ans.Length - 1);<br>    Console.WriteLine(ans);<br>}</pre><p>Based on the logic of Bubble Sort, we can make sure it need to be designed with nested for loop. So, the efficiency of Bubble Sort:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*VEP_o62An-Nsw6v58bXHvg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0df0a1f0727b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【C# & Python】Insertion Sort]]></title>
            <link>https://medium.com/@jason8410271027/c-python-insertion-sort-4a7f0518d4ec?source=rss-effe333bc878------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a7f0518d4ec</guid>
            <category><![CDATA[insertion-sort]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 04:58:28 GMT</pubDate>
            <atom:updated>2024-03-31T04:58:28.059Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, I want to talks about Insertion Sort. This algorithm seems a little hard to understand for the beginners. However, I promise that after you read this article, you will find out it’s not that hard.</p><p>Briefly speaking, Insertion Sort just only two steps:</p><p>Step 1: Choose the data we want to sort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*_6lyaF62G4R1u6vYHuLY9Q.png" /></figure><p>Be careful, the number we choose start from the second element. Then, we can call this number is「i」.</p><p>Step 2: Compare all the number before 「i」.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*Hp-JfnhOEzIbWQmnDrBfeQ.png" /></figure><p>If i smaller than the number we are comparing it to, then we can swap these two data directly.</p><p>Based on the example above, we have already finished round 1. So, round 2 also the same:</p><p>Step 1: Choose the data we want to sort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*wie0lXYuTYP_Fq2L3PLnzw.png" /></figure><p>Step 2: Compare all the number before 「i」.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*wKDjcgvrCoLhNFB2hBn9Ug.png" /></figure><p>Okay, I believe lots of people get stuck right here. As you can see, 4 and 5 are greater than 1, so how do we sort or swap these data? The answer is to swap them one by one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*5CMlx195OiYU6fylMGndhg.png" /></figure><p>Now, we have already how Insertion Sort working, so we can take a look at how to implement this algorithm in Python and C#:</p><pre>#Python<br><br>Data = [5,4,1,3,2]<br>for i in range(1, len(Data)):<br>    j = i-1<br>    flag_val = Data[i]<br>    while(j&gt;=0 and flag_val&lt;Data[j]):        <br>        Data[j+1] = Data[j]<br>        Data[j] = flag_val<br>        j = j-1<br>    print(Data)</pre><pre>//C#<br><br>static void Main(string[] args)<br>{<br>    int[] Data = new int[] { 5,4,1,3,2 };<br>    for (int i = 1; i &lt; Data.Length; i++)<br>    {<br>        int j = i - 1;<br>        int flag_val = Data[i];<br>        while (j &gt;= 0 &amp;&amp; flag_val &lt; Data[j])<br>        {<br>            Data[j + 1] = Data[j];<br>            Data[j] = flag_val;<br>            j--;<br>        }<br>        Output(Data);<br>    }<br>    Console.ReadKey();<br>}<br>static void Output(int[] Data)<br>{<br>    string Res = &quot;&quot;;           <br>    for (int i = 0; i &lt; Data.Length; i++)<br>    {<br>        Res = Res + Data[i] + &quot;,&quot;;<br>    }<br>    Res = Res.Substring(0, Res.Length - 1);<br>    Console.WriteLine(Res);   <br>}</pre><p>Based on the way Insertion Sort works, obviously it have to be designed with nested loop. The for loop represents the data of 「i」, the number we need to choose in step 1. While loop represents the step 2. In other words, the while loop is used to allow the data of 「i」to be compared with other numbers.</p><p>In C#, you can discover it’s a bit more complex than python. Actually, you just need to focus on the main function. The Output function is just the way I can output the result like: 「1,2,3,4,5」.</p><p>Efficiency of Insertion Sort:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*9BxEJMVIFk4xBc4PROaruQ.png" /></figure><p>Overall, this is today’s topic, I hope it’s easy enough to understand. By the way, I’m not an English native speaker, so don’t hesitate to correct me if I have some grammar problem or even the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a7f0518d4ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【C# & Python】Selection Sort]]></title>
            <link>https://medium.com/@jason8410271027/c-python-selection-sort-85926c8a0dad?source=rss-effe333bc878------2</link>
            <guid isPermaLink="false">https://medium.com/p/85926c8a0dad</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[selection-sort]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 12:59:20 GMT</pubDate>
            <atom:updated>2024-03-19T13:15:30.178Z</atom:updated>
            <content:encoded><![CDATA[<p>Being a software engineer, of course we know about the algorithms. But guess what? I hadn’t really focused on them when I was in college. So, to improve myself and hope get hired by famous tech companies, I decide to relearn all of this. At the same time, I start to try using English to write articles, just because I want to practice English at the same time. So, if I make any mistakes, whether the content or my English, don’t hesitate, just correct me, I will very appreciate it.</p><p>Alright, back to today’s topic, I want to talk about “Selection Sort”, a basic sorting algorithm that we all learned, especially if you studied Computer Science before. Briefly speaking, Selection Sort can be divided into few steps：</p><ol><li>Choose the data hasn’t been sorted：</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*F7qza37gYXCn4QTMO4fpug.png" /></figure><p>I let the ‘i’ represent the data that hasn’t been sorted yet. In other words, ‘i’ needs to iterate through all the data.</p><p>2. Find the minimum data after ‘i’：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*lb42Kn_eUP_OlMHZCyKiJw.png" /></figure><p>In the last step, we already chose the data we want to sort. So now we have to find the minimum data expect for ‘i’</p><p>3. Compare the minimum data with ‘i’：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RI7b4gRj8xvp-fxB--0JEA.png" /></figure><p>If ‘i’ greater than the minimum data, then swap these two data.</p><p>Based on the example above, you can see that we already placed 「1」 in the correct position. So, what should we do in round 2? Obviously, the data still hasn’t been completely sorted yet. Right? In round 2, everything remains the same as in round 1, expect that ‘i’ needs to start from the second data：</p><p>Step 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hr470clhyfG6twiRMiRabw.png" /></figure><p>Step 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VV7rDwv4EJ3umY24yJ9DcA.png" /></figure><p>Step 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*wxS2_TPOXJNhaxByzv5Paw.png" /></figure><p>Overall, Selection Sort just uses these 3 steps to sort the data. it’s quite easy, isn’t it? So right now, we can take a look at how to implement this algorithm by programming</p><p>C#：</p><pre>int[] Input = new int[] { 5,4,1,3,2};            <br>for (int i = 0; i &lt; Input.Length - 1; i++)<br>{<br>    int current_min_index = i;<br>    for (int j = i + 1; j &lt; Input.Length; j++)<br>    {<br>        if (Input[current_min_index] &gt; Input[j])<br>        {<br>            current_min_index = j;                      <br>        }                   <br>    }<br>    int temp = Input[i];<br>    Input[i] = Input[current_min_index];<br>    Input[current_min_index] = temp;<br>}</pre><p>Python：</p><pre>Data = [5,4,1,3,2]<br>for i in range(0, len(Data)):<br>    current_min_index = i<br>    for j in range(i+1, len(Data)):<br>        if(Data[current_min_index] &gt; Data[j]):<br>            current_min_index = j<br>    temp = Data[i]<br>    Data[i] = Data[current_min_index]<br>    Data[current_min_index] = temp</pre><p>Here I provide the code of Python and C#. As you can see, no matter which programming language, they are all using nested for loop. The first for loop is means we need to sort all the data. And second for loop is for finding the minimum data. Moreover, the codes after second for loop, are the way how to swap the data.</p><p>Efficiency of Selection Sort:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*cKBIh-970-H7cafG_xYMTQ.png" /></figure><p>So, this is today’s topic, I hope it’s easy enough to understand the Selection Sort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85926c8a0dad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【學習筆記】K近鄰演算法-理論&Python實作]]></title>
            <link>https://medium.com/@jason8410271027/%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-k%E8%BF%91%E9%84%B0%E6%BC%94%E7%AE%97%E6%B3%95-%E7%90%86%E8%AB%96-python%E5%AF%A6%E4%BD%9C-73c9bc9251c8?source=rss-effe333bc878------2</link>
            <guid isPermaLink="false">https://medium.com/p/73c9bc9251c8</guid>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[crossvalidation]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 04:05:54 GMT</pubDate>
            <atom:updated>2023-07-12T04:05:54.727Z</atom:updated>
            <content:encoded><![CDATA[<p>K近鄰演算法，又稱KNN(K Nearest Neighbor)，它跟我們先前介紹的K-means相當相似，都是「物以類聚」的機器學習演算法，而之間最大的差異，就在於KNN屬於監督是學習，K-means則為非監督式學習。</p><p>首先在使用KNN之前，必須先定義K值，而所謂的K值，代表要尋找K個鄰近的資料來做比較。直接來看到範例：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*i8SUbgHrQnW4m85vXlF77w.png" /><figcaption>範例資料</figcaption></figure><p>上圖範例中的圓圈、三角形、星號，都是我們的資料，不過當中的星號，是我們要預測的資料，因為還不知道它是圓圈還是三角形，所以就先用星號來做代替。因此KNN的概念，就是找K個離星號最近的資料，並以投票的方式來決定，星號的資料會是圓圈還是三角形。因此假若K為3，那就會找3個離星號最近的資料，因此結果會如下圖所示：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*BREnwsp6G8O0vi-AhLQYeQ.png" /></figure><p>根據上圖的結果，可以發現離星號最近的3個樣本，以圓圈占大多數，因此我們就可以認定，星號也會是圓圈：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*-UjC6D6e-L9itjBfkQynXA.png" /><figcaption>預測結果</figcaption></figure><p>以上就是KNN的整體概念，可以發現相當簡單。至於距離怎麼計算，其實也就是我們常看到的那幾種計算方式：</p><h4>歐式距離(Euclidean distance)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*wJTxfbgHYNUEqeLg8sG9ag.png" /><figcaption>Euclidean distance</figcaption></figure><h4>曼哈頓距離(Manhattan distance)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*ivsO6pwUcCi5P1RKdep3xw.png" /><figcaption>Manhattan distance</figcaption></figure><h4>明氏距離(Minkowski distance)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*Mwkod9I6rWsjg5wUufp4eA.png" /><figcaption>Minkowski distance</figcaption></figure><p>明氏距離這個比較特別一點，所以稍微介紹一下。公式中的p其實是任意常數，不過較特別的是可以發現，當p為1時就會變成曼哈頓距離；當p為二時就會變成歐式距離。</p><p>在此必須要注意一點，那就是K值應盡量為基數，因為萬一K值設為偶數，有可能會遇到以下情境：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*eE6bxU8jv8soCNTD2fIu5w.png" /><figcaption>k=4的範例</figcaption></figure><p>可以發現圓圈跟三角形各兩票，所以此時就會無法決定星號，會是圓形或是三角形。</p><p>接著馬上來看到如何用Python實作，首先載入我們的iris資料集，並進行一些處理：</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.model_selection import StratifiedKFold<br>from sklearn.model_selection import train_test_split<br>from sklearn.model_selection import cross_val_score<br>from sklearn.datasets import load_iris<br>RawData = load_iris()<br>df1 = pd.DataFrame(RawData[&#39;data&#39;], columns=RawData[&#39;feature_names&#39;])<br>df2 = pd.DataFrame(RawData[&#39;target&#39;], columns=[&#39;target&#39;])<br>df = pd.concat([df1,df2], axis=1)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*cQC7m-Nimhdg15K3ZJ7Ytg.png" /><figcaption>鳶尾花資料集</figcaption></figure><p>實作KNN並得出其正確率：</p><pre>x = df.iloc[:,0:4]<br>y = df.iloc[:,4:5]<br>x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3, random_state=1)<br>#KNN建模<br>model = KNeighborsClassifier(n_neighbors=3)<br>model.fit(x_train,np.ravel(y_train))<br>#正確率<br>print(model.score(x_test,y_test))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*8BoFkA00kFjmOKnM-rgv4g.png" /><figcaption>正確率</figcaption></figure><p>不過到這裡相信各位好奇，那這樣K值不就只能瞎猜？答案是錯的，其實K值有選定的技巧。通常在選定K值時，我們會取樣本數平方根：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/70/1*3oj-877nF5z-lQhkX-nnNQ.png" /><figcaption>K值選定</figcaption></figure><p>另外我們還可透過交驗證的方式，來輔助我們選定K值。簡單來說就是讓程式，一個一個幫我試，輔助我們找出最佳的K值：</p><pre>k = StratifiedKFold(n_splits=10, shuffle=True, random_state=1)<br>accuracy = []<br>#建立K值尋找範圍(1-12)<br>k_value = range(1,int(round(np.sqrt(len(x))))+1)<br>for i in k_value:<br>    knn = KNeighborsClassifier(n_neighbors=i)<br>    score = cross_val_score(knn,x,np.ravel(y),cv=k,scoring=&#39;accuracy&#39;)<br>    accuracy.append(score.mean())<br>plt.plot(k_value,accuracy)<br>plt.xticks(range(1,13,1))<br>plt.grid()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*sIlmeY2l16ukd3lTRD-TGw.png" /><figcaption>交叉驗證結果</figcaption></figure><p>上圖交叉驗證的結果，當中X軸就是所謂的K值，Y軸則為正確率(Accuracy)。故由此可以發現，當K值為10和11的時候，其正確率表現最好，但不過如先前所說的，K值應盡量為基數，故此我們就選定11為K值。</p><p>以上就是整體KNN的概念，以及其實作方式，若有其他疑問，或是想交流的部分，都歡迎各位底下留言。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73c9bc9251c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【學習筆記】Anova 理論&Python實作]]></title>
            <link>https://medium.com/@jason8410271027/%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-anova-%E7%90%86%E8%AB%96-python%E5%AF%A6%E4%BD%9C-a86dbbfee60?source=rss-effe333bc878------2</link>
            <guid isPermaLink="false">https://medium.com/p/a86dbbfee60</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[anova]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 11:28:38 GMT</pubDate>
            <atom:updated>2023-07-11T11:28:38.664Z</atom:updated>
            <content:encoded><![CDATA[<p>今天要來跟大家分享一個實用統計方法，那就叫做變異數分析(Anlysis of Variance, Anova)。其實簡單來說，Anova就是加強版的獨立樣本t檢定，之間不同之處，在於獨立樣本t檢定，只能兩組樣本之間來去做比較，而Anova可以進行兩組以上的樣本比較。</p><p>Anova的計算可以透過以下的表格來代表：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*EEeKR26Uq66n1r6OVTLtMg.png" /></figure><p>雖然看起很複雜，但其實最主要的重點，在於F值計算。換句話說，F值是我們最終要算出來的結果，而其他欄位內的計算，只是在告訴大家怎麼去推倒到&quot;F=MSB/MSW&quot;的式子而已。所以當F值求出後，我們就可以透過查表，或統計軟體，來輔助我們求出p value，這樣就可以知道組別之間是否有顯著差異了。</p><p>接著我們就來看看，如何用Python實作Anova。首先第一步，透過levene’s test進行同質性檢定：</p><pre>import pandas as pd<br>import numpy as np<br>from scipy.stats import levene<br>from scipy.stats import f_oneway<br>#Create samples<br>df = pd.DataFrame({<br>    &quot;A班&quot;:[90,85,70,88,77,93,84,88,85,96,95,93,100,94,86,70,87,73,72,69,82,93,81,89,83,80,80,79,62,81],<br>    &quot;B班&quot;:[70,54,73,74,67,43,74,80,95,96,55,73,77,84,76,90,80,93,60,61,72,73,91,99,88,60,79,90,82,71],<br>    &quot;C班&quot;:[66,64,93,60,97,93,94,80,85,86,55,83,97,74,76,70,70,77,90,61,65,80,65,77,78,72,71,82,43,70]<br>})<br>#levene&#39;s test<br>statistic, p_value=levene(df[&quot;A班&quot;], df[&quot;B班&quot;], df[&quot;C班&quot;])<br>print(&#39;statistic:%.2f&#39;%statistic)<br>print(&#39;p_value:%.2f&#39;%p_value)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*m1E-hpNf0Qifpe7oLOd55Q.png" /><figcaption>同質性檢定結果</figcaption></figure><p>根據結果，發現同質性檢結果不顯著(p&gt;.05)，因此可以接續進行Anova檢定：</p><pre>f_statistic, p_value = f_oneway(df[&quot;A班&quot;], df[&quot;B班&quot;], df[&quot;C班&quot;])<br>print(&quot;f_statistic:%.2f&quot;%f_statistic)<br>print(&quot;p_value:%.2f&quot;%p_value)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*zPE2cYvenu-dMu0MoemPgA.png" /><figcaption>Anova檢定結果</figcaption></figure><p>這裡一樣我們關注p值，所以根據結果，發現呈顯著差異(p&gt;.05)，代表三個班級的成績，擁有明顯的差異。不過到這裡一定會好奇，既然有顯著差異，那到底是哪一班的成績比較突出一點？或是是比較差？這時就可以進行事後檢定(Post-hoc)，來幫我們探知一切：</p><h4>Way 1</h4><pre>from scipy import stats<br><br>posthoc = stats.tukey_hsd(df[&quot;A班&quot;], df[&quot;B班&quot;], df[&quot;C班&quot;])<br>print(posthoc)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*_GvzjibHjrkxHLjnuDEfuw.png" /><figcaption>post-hoc</figcaption></figure><p>方式一比較單純，就是直接使用scipy裡的套件。直接來看到事後檢定結果，首先看到Comparison欄位，可以發現有(0-1)、(0-2)、(1-0)等，根據範例的資料，這裡依序的意思就是，A班與B班成績相比(A-B)、A班與C班成績相比(A-C)、B班與A班成績相比(B-A)。在此的0、1、2順序，其實就是依據tukey_hsd()裡的組別樣本順序安排的，所以這部分還需各位多加留意一下。</p><p>回到正題，所以可以看到第一列(編號1的紅色方框)，我們就可以得知A班的成績優於B班的成績，因為(0–1)，也就是A般的平均成績減掉B般的平均成績，因此之間平均差為7.5，且因為p&lt;.05，因此之間存在顯著差異。而第二列(編號2的紅色方框)的察看邏輯也相同，因此A班成績明顯優於C班成績，因為(0–2)，等同於A班平均成績，減去C班的平均成績，因此之間平均差異為7.7，且因其p&lt;.05，因此之間有顯著差異。</p><h4>Way 2</h4><pre>import statsmodels.api as sm<br>from statsmodels.stats.multicomp import pairwise_tukeyhsd<br>#轉換資料格式<br>new_df = pd.melt(df, var_name=&quot;組別&quot;, value_name=&quot;成績&quot;)<br>posthoc = pairwise_tukeyhsd(new_df[&quot;成績&quot;], new_df[&quot;組別&quot;])<br>print(posthoc.summary())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*a-yIznPo3jvTfp_8lrVUMw.png" /><figcaption>post-hoc</figcaption></figure><p>此方法必須先進行資料格式的轉換，轉換的方式就如上述程式碼註解之處，故轉換後的結果會如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*6aWeX8uvQTtNdlWMWRvXIA.png" /><figcaption>資料整理後格式</figcaption></figure><p>接著就可以直接來看事後檢定結果。首先可以發現這表格資訊又稍微豐富一點，不只擁有最基本的檢定資訊之外，還詳細列出組別名稱，以及之間是否有顯著差異(reject)。不過此表的meandiff，也就是組別間的平均差，都是group1 — group2，所以這就是為甚麼會與Way1產出的表格，些有差異的原因。不過其概念、結果完全都是相同的，只是在解釋部分需要特別注意，兩者之間的差異。</p><p>以上為Anova檢定的整體實作流程，不過這些全部都建立在，一切順利的條件下。然而人生哪有一直在一帆風順的，總是會有一些挫折，例如在最一開始的同質性檢定，就發現結果為顯著差異，那這時又該怎麼處理呢?此時我們就可以使用Welch’s Anova。</p><p>若要此用Welch’s Anova，首先要先求得每個組的平均數與變異數：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*0w8u68JzUMowXdKIN9fZJA.png" /><figcaption>個組平均數</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*sB3NNfbT-EQeHLoPAGJJZA.png" /><figcaption>各組標準差</figcaption></figure><p>接著計算每組權重，當中的n_i為該組的樣本總數：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/79/1*HeANiDMzAl9uA02blyy86g.png" /><figcaption>權重</figcaption></figure><p>接下來計算組間平方和。公式中的X_bar，為全部樣本數量：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*DMrNqwV83EoJ_c1Gp02gzA.png" /><figcaption>SSB</figcaption></figure><p>再來計算組間自由度：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*N3kIST3GLY_nSBWDXxEUSQ.png" /><figcaption>組間自由度</figcaption></figure><p>接著計算組內平方和：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*KeZK_IrWsPcy6EjTGxGWBw.png" /><figcaption>組內平方和</figcaption></figure><p>再來求出組內自由度：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*7NC0cq-_x9gRpbpeH2lnSg.png" /><figcaption>組內自由度</figcaption></figure><p>接著計算組間均方：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/1*yCijtqONR4wFXd84t2iH1Q.png" /><figcaption>組內均方</figcaption></figure><p>再來計算組內均方：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*qbarzLPCzVTbk1vHHXbdgg.png" /><figcaption>組內均方</figcaption></figure><p>最後求得F統計量：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/1*nzueQ3fNWBWnDO3UL2sRLw.png" /><figcaption>統計量</figcaption></figure><p>所以當F統計量求出後，我們就可以透過查表，或統計軟體，來求得p值結果，以上就是Welch’s Anova的運算與推導過程。接著來看看Python上如何實現，首先一樣進行Levene&#39;s test：</p><pre>import pandas as pd<br>import numpy as np<br>from scipy.stats import levene<br>df = pd.DataFrame({<br>    &quot;A班&quot;:[90,85,70,88,77,93,84,88,85,96,95,93,100,94,86,70,87,73,72,69,82,93,81,89,83,80,80,79,62,81],<br>    &quot;B班&quot;:[59,44,73,74,67,93,74,80,95,96,55,73,77,84,96,30,80,23,90,81,72,73,91,99,88,60,79,90,82,71],<br>    &quot;C班&quot;:[90,74,93,60,97,93,94,80,85,86,95,54,27,74,26,70,70,77,10,31,83,43,65,77,78,72,71,82,93,70]<br>})<br><br>statistic, p_value=levene(df[&quot;A班&quot;], df[&quot;B班&quot;], df[&quot;C班&quot;])<br>print(&#39;statistic:%.2f&#39;%statistic)<br>print(&#39;p_value:%.2f&#39;%p_value)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*a3Qnk4GoNmfGyhu2a5Btrw.png" /><figcaption>同質性結果</figcaption></figure><p>根據同質性檢定發現，樣本之間變異數有顯著差異(p&lt;.05)，因此使用Welch’s Anova進行後續的分析與探討：</p><pre>import pingouin as pg<br>new_df = pd.melt(df, var_name=&#39;班級&#39;, value_name=&#39;分數&#39;)<br>pg.welch_anova(dv=&#39;分數&#39;, between=&#39;班級&#39;, data=new_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*9drw6eBs-Eu5O0LUXr7F4Q.png" /><figcaption>Welch’s Anova檢定結果</figcaption></figure><p>由上範例可以看到，若要使用Welch’s Anova，則必須使用pingouin的套件。然後要使用前，資料的格式一樣必須進行轉換。所以可以直接來看到上圖的結果，在此我們主要要注意&quot;p-unc&quot;這個值，及代表Anova檢定後的結果。因此可以看到p&lt;.05，代表三個班級之間的成績表現有顯著差異，因此可以進行事後檢定：</p><pre>posthoc = pg.pairwise_gameshowell(data=new_df, dv=&#39;分數&#39;, between=&#39;班級&#39;)<br>posthoc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*klrFphAF3kL-VYN1aOKcUg.png" /><figcaption>事後檢定結果</figcaption></figure><p>因此由事後檢定可以發現，三個班級當中A班與C呈顯著差異，且很明顯可以發現A班成績優於B班。在此的事後檢定，也可以使用之前介紹的兩個方法來去做，並非一定要使用pingouin來實作。</p><p>以上就是這次的Anova理論，與Python實作的介紹，若有其他疑問或想交流的，也歡迎各位。</p><h3>Reference</h3><ul><li><a href="https://byjus.com/anova-formula/">Anova Formula in Statistics with Solved Example</a></li><li><a href="https://www.geeksforgeeks.org/how-to-perform-welchs-anova-in-python/">How to Perform Welch&#39;s ANOVA in Python - GeeksforGeeks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a86dbbfee60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【學習筆記】獨立樣本t檢定-理論+Python實作]]></title>
            <link>https://medium.com/@jason8410271027/%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E7%8D%A8%E7%AB%8B%E6%A8%A3%E6%9C%ACt%E6%AA%A2%E5%AE%9A-%E7%90%86%E8%AB%96-python%E5%AF%A6%E4%BD%9C-146699cf0bd9?source=rss-effe333bc878------2</link>
            <guid isPermaLink="false">https://medium.com/p/146699cf0bd9</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[t-test]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 04:45:54 GMT</pubDate>
            <atom:updated>2023-07-05T14:03:57.811Z</atom:updated>
            <content:encoded><![CDATA[<p>獨立樣本t檢定(Independent sample t-test)，是我們在學習統計時，必學的一個統計方式。雖然整體概念不複雜，但卻相當實用。在許多社會科學、醫學等相關論文，也常看到它的身影，所以這次就來深入探討一下，何謂獨立樣本t檢定。</p><p>獨立樣本t檢定，適用於比較兩組平均數，是否有存在差異的方法。例如：比較兩班成績時否有顯著差異、兩家分店的營收額是否有差異、兩個不同縣市的房價，之間是否有差異。原則上只要是「兩個互相比較」的情境，都適合使用獨立樣本t檢定進行探討。不過要注意！如果是前、後的比較，例如教育研究最常見的前、後測比較，那就必須使用相依樣本t檢定(Dependent Sample t-test)，又可稱之為成對樣本t檢定(Paired Sample t-test)。有關相依樣本t檢定內容，將在之後文章細談。</p><p>廢話不多說，直接來看該怎麼做。首先，我們必須做「同質性檢定」，所謂的同質性檢定，代表我們要必須知道兩個比較的樣本，是不是同樣的東西。舉個例子，當我們要比較兩班學生成績時，我們應該要先確保，這兩班的學生基礎、程度是相同的，而這就是所謂的同質性。不過這裡必須注意一點，即便樣本不同質，還是可以做獨立樣本t檢定，只是必須換另一種方式而已，這部分等等後面會提到。</p><p>同質性檢定，通常使用Levene檢定來進行，其公式如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*P--8KMYFD8yoWTQ8shZH8A.png" /><figcaption>Levene檢定</figcaption></figure><p>● N：所有組別樣本數量總和。若今天只分A、B兩組，A組有50人，B組60人，那麼N=110。</p><p>● k：組別數量。假若分有A、B、C三組，那麼k=3。</p><p>●N_i：第i組的樣本總數量。</p><p>●Z_i bar：每組樣本內的中心變化量，可以看到以下公式推倒：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*vsIcheJemOe3phPfSAxuzw.png" /><figcaption>Z_i bar</figcaption></figure><p>然後當中的Z_ij，是樣本內每個觀測值，與其樣本的平均數或中位數之間差異：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*8cX1Y0QaxPL_FCAUuO4czw.png" /></figure><p>所以假若有一樣本，資料為：「1,10,5,30,25」，那麼Y_i bar計算會如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*QtHihOyDdS5sBaJGivXvyg.png" /><figcaption>Z_i bar計算範例</figcaption></figure><p>●Z bar：跟上面的Z_i bar一樣，差異僅在於分母是所有組別樣本數和，所以公式會如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*T_qney9B3NiO0UJhIRIraQ.png" /><figcaption>Z bar</figcaption></figure><p>雖然上面公式講得頭昏眼花，但其實Python早就有套件來幫我們處理這些事情了，所以馬上就來看範例：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*UgfAT4hAwRF0hNC7bzv2CQ.png" /><figcaption>範例資料</figcaption></figure><p>以上範例就是A、B兩班，某次段考的成績，所以我們要用這個資料，來探討A、B兩班的成績是否有差異。因此我們現在第一件要做的事情，就是透過Levene檢定，來檢測本之間的變異數是否同值：</p><pre>import pandas as pd<br>import numpy as np<br>from scipy.stats import levene<br>df=pd.DataFrame({&#39;A班&#39;:[60,80,84,96,92,75,85,57,89,100],<br>                 &#39;B班&#39;:[77,63,50,93,75,90,51,88,70,99]})<br><br>statistic, p_value = levene(df[&#39;A班&#39;], df[&#39;B班&#39;])<br>print(&#39;統計量：%.2f&#39;%statistic)<br>print(&#39;p-value:%.2f&#39;%p_value)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*stljq6A7k4-f5K3aBhmCOA.png" /><figcaption>同質性檢定結果</figcaption></figure><p>由上述結果可以發現，p值&gt;0.05，因此之間未有顯著差異，所以接下來，就可以進行獨立樣本t檢定：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*EBk9QGVDV7GGJducM6hnqw.png" /><figcaption>獨立樣本t檢定公式</figcaption></figure><p>●S_p：兩個樣本合併的標準差，所以其公式會如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*nOK8N2EDbR-Ty17tnCfU8g.png" /></figure><p>●s_1 &amp; s_2：第一組和第二組樣本的標準差，標準差公式如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*JL4F3K9VW1BjJ0uvkE_3VQ.png" /><figcaption>SD</figcaption></figure><p>上述標準差公式中的x bar為平均數，像信這個大家已經很熟悉了，我就不再解釋其公式了。</p><p>因此簡單來說，如果剛剛在進行同質性檢定，且最後p值大於0.05的時候，就必須使用上述第一個公式，來求出t值。反之，就必須用第二個公式，來進行t值的計算。所以依據剛剛範例的結果，同質性解果不顯著，因此要使用第一個公式。接著就來看看，如何透過Python來實作：</p><pre>from scipy.stats import ttest_ind<br>ttest_ind(df[&#39;A班&#39;], df[&#39;B班&#39;], equal_var=True, alternative=&#39;two-sided&#39;)</pre><p>首先來介紹一些比較重要的參數：</p><p>●equal_var：同質性檢定結果為顯著，或不顯著。如果不顯著，則equal_var=False。反之，equal_var=True。</p><p>●alternative：雙尾檢定(two-sided)，左尾檢定(less)，右尾檢定(greater)。</p><p>在此也順便簡單講解一下上面的差異，首先是雙尾檢定，其假設檢定會如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*n3Re3CaKqqWC7LmGlHLMWQ.png" /><figcaption>雙尾假設檢定</figcaption></figure><p>如果是左尾檢定，其假設檢定會如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*9-RYdeopdPWMogLFnwguSw.png" /><figcaption>左尾檢定假設</figcaption></figure><p>如果是右尾檢定，其假設會如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*f0wWenDKiHl8iEv_rJvMFg.png" /><figcaption>右尾檢定架設</figcaption></figure><p>所以在回到上面的程式碼，這裡我們就使用雙尾檢定，所以其結果如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*k6j2FINe1Rq-mpghiZ68Hg.png" /><figcaption>獨立樣本t檢定結果</figcaption></figure><p>藉由上述結果可以發現，p &gt; 0.05，因此兩班成績無顯著差異。以上就是完整的獨立樣本t檢定流程。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=146699cf0bd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【學習筆記】K-means實作篇]]></title>
            <link>https://medium.com/@jason8410271027/%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-k-means%E5%AF%A6%E4%BD%9C%E7%AF%87-5c3fb9faf17?source=rss-effe333bc878------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c3fb9faf17</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[k-means]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 08:56:43 GMT</pubDate>
            <atom:updated>2023-06-27T08:56:43.260Z</atom:updated>
            <content:encoded><![CDATA[<p>上次介紹了K-means的基本原理，這次就來介紹一下Python的實作方式。首先介紹一下scikit-learne的KMeans套件，有哪些參數可以調整：</p><h4>n_cluster</h4><p>n_cluster是指說，今天你想要把資料分成幾類，這部分的資料必須要由使用者定義。</p><h4>init</h4><p>init意旨在給定中心點時，要用哪種方式給定。預設為「k-means++」，意旨會依據資料的分布，來決定中心點應放在何處。當然也可以使用「random」，以隨機的方式決定中心點位置。</p><p>除了「k-means++」和「random」兩個方式可以選擇外，亦可以讓使用者自行定義中心點的位置，而設定方式如例：np.asarry([[x1,y1],[x2,y2],[x3,y3],…])。</p><h4>n_init</h4><p>每個Cluster中心點的更新次數。使用者可以依據情況，自行定義更新次數。預設為10次，若設為「auto」的話，模型會自行依據情況，決定須更新的次數。</p><h4>max_iter</h4><p>一樣是設定中心點的更新次數，不過在此設定是，最大更新次數，也就是更新次數的上限值。預設值為300。</p><h4><strong>tol</strong></h4><p>每個Cluster的中心點收斂容忍度，預設為0.0001。根據K-means的特性，每個Cluster的中心點會不斷變動，直到不再變動為止。然而實務運算上，其實有機會中心點一直不斷變動。故此設定就在定義，當移動幅度不大於其設定值時，即可認定已達成收斂目標，以停止中心點的搜尋。</p><h4><strong>algorithm</strong></h4><p>其實K-means又可以再細分許多不同的方法，故在此可以選擇要使用的方式， 如：lloyd、elkan、auto、full。預設值為lloyd。</p><p>以上就是scikit-learn的KMeans套件，可以調整的參數內容。在大致上瞭解上述參數意義後，馬上就來看到如何進行實作。首先載入iris資料集，一個最典型的分類問題範例：</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from sklearn.datasets import load_iris<br><br>RawData = load_iris()<br>df = pd.DataFrame(RawData[&#39;data&#39;],columns= RawData[&#39;feature_names&#39;])<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*K1nHjeCm-AjP_HcgU4yYSw.png" /><figcaption>輸出結果</figcaption></figure><p>接著開始進行建模：</p><pre>from sklearn.cluster import KMeans<br>x = df.iloc[:,0:4] #x為所有特徵資料<br>model = KMeans(n_clusters=3, n_init=&#39;auto&#39;,random_state=1) #預計分為三群，迭代次數由模型自行定義<br>model.fit(x) #建立模型<br>plt.scatter(df[&#39;petal length (cm)&#39;],df[&#39;petal width (cm)&#39;], c=model.labels_) #根據花瓣的長度、寬度，來畫出之間關係。c=model.labels_:代表資料點的顏色，由模型分類出來的結果，來進行分類和定義。 <br>plt.xlabel(&#39;petal length&#39;)<br>plt.ylabel(&#39;petal width&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*KOEK6IFLQIjUqA8gMQuZvQ.png" /><figcaption>輸出結果</figcaption></figure><p>從上圖可以發現，其結果如我們所願，分出了三大群出來。此外根據此結果，可以明確解釋：「當花瓣的長度介於1~2公分，且寬度小於1公分時，可以獨自被分類為一品種。若花瓣長度介於3~5公分左右，且寬度介於1~2公分左右，也可以被定義為一品種。最後當花瓣長度介於約5~7公分內，且寬度介於約1.5~2.5之間，則可另外被定義成一品種。」。</p><p>這裡再介紹一個東西，那就是透過Elbow法找出最佳K值(資料群數)。上面的介紹例子，之所以很明確的定義三群資料，原因在於我們找就知道結果了。然而實務分析上，到底能夠分出幾群資料，我們可能毫無依據，所以這時候就會陷入，不知道n_clusters要設多少的窘境。因此我們就可以透過此方法，來找出最佳的n_clusters數量：</p><pre>DistanceList = []<br>for i in range(1,11): #測試將資料分為1~10群<br>    KM = KMeans(n_clusters=i, n_init=&#39;auto&#39;, random_state=1)<br>    KM.fit(x)<br>    DistanceList.append(KM.inertia_) #求出每個Cluster內的資料與其中心點之平方距離和，並用List記錄起來<br>plt.plot(range(1,11), DistanceList)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*KCQbYGi_xpVceD8TNsZ71Q.png" /><figcaption>輸出結果</figcaption></figure><p>上圖中的y軸，就是每個Cluster內的資料，與其群內中心點的平方距離總和。x軸則是分群數量。所以根據K-means的特性，y軸的值應當是越低越好。不過此時又有個問題，那就是有可能為了求最低的y，而耗費大量時間，且效果也不會很顯著的提升，那這樣反而本末倒置。所以Elbow Method的核心概念，就是「剛剛好就好」的概念。因此看到上圖，發現將資料分為1~3群時候，y軸的值都有很大幅度的下降，但當分到3群之後，可以發現其y軸下降的幅度就沒那麼大，甚至趨於平緩，因此我們就會判定，3是最佳的分群數量。</p><h3>Reference</h3><ul><li><a href="https://towardsdatascience.com/kmeans-hyper-parameters-explained-with-examples-c93505820cd3">KMeans Hyper-parameters Explained with Examples</a></li><li><a href="https://medium.com/analytics-vidhya/how-to-determine-the-optimal-k-for-k-means-708505d204eb">How to determine the optimal K for K-Means?</a></li><li><a href="https://www.geeksforgeeks.org/ml-determine-the-optimal-value-of-k-in-k-means-clustering/">ML | Determine the optimal value of K in K-Means Clustering - GeeksforGeeks</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html">KMeans</a></li><li><a href="https://pyecontech.com/2020/05/27/python_k-means_k-medoids/">[Python實作] 聚類分析 K-Means / K-Medoids</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c3fb9faf17" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>