<?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 Eric Tsai on Medium]]></title>
        <description><![CDATA[Stories by Eric Tsai on Medium]]></description>
        <link>https://medium.com/@erictsai492718?source=rss-d5f83f0bd9c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2URm76VZVSvCir6pfeLKvw@2x.jpeg</url>
            <title>Stories by Eric Tsai on Medium</title>
            <link>https://medium.com/@erictsai492718?source=rss-d5f83f0bd9c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:16:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erictsai492718/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[透過 Bias 和 Variance 判斷模型是否有Overfitting 或 Underfitting]]></title>
            <link>https://erictsai492718.medium.com/%E9%80%8F%E9%81%8E-bias-%E5%92%8C-variance-%E5%88%A4%E6%96%B7%E6%A8%A1%E5%9E%8B%E6%98%AF%E5%90%A6%E6%9C%89overfitting-%E6%88%96-underfitting-4294284e54a7?source=rss-d5f83f0bd9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4294284e54a7</guid>
            <category><![CDATA[bias]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[underfitting]]></category>
            <dc:creator><![CDATA[Eric Tsai]]></dc:creator>
            <pubDate>Sat, 10 Apr 2021 18:37:49 GMT</pubDate>
            <atom:updated>2021-04-14T15:25:41.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*On4lm5P4Koxfhe1M" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>最近在上 Coursera 的<a href="https://www.coursera.org/learn/aws-machine-learning">課程</a>，裡面提到了用 Bias 和 Variance 去辨別是否有 overfitting 和 underfitting，當下真的覺得過去的我都是以感覺在訓練模型，沒有用明確指標去輔助模型的建置，因此決定寫這篇文章，紀錄一下過去的我對 overfitting 和 underfitting 的判斷有多麼的隨便。我們先來看一下<a href="https://zh.wikipedia.org/wiki/%E9%81%8E%E9%81%A9">維基百科</a>對兩者的定義:</p><h4>在統計學中</h4><p><strong>過適</strong>（英語：<strong>overfitting</strong>，或稱<strong>擬合過度</strong>）是指過於緊密或精確地匹配特定資料集，以致於無法良好地調適其他資料或預測未來的觀察結果的現象。</p><p><strong>乏適</strong>（英語：<strong>underfitting</strong>，或稱：<strong>擬合不足</strong>）；它是指相較於資料而言，模型參數過少或者模型結構過於簡單，以至於無法捕捉到資料中的規律的現象。</p><p>相信很多人在上網找資料時總會看到有人判斷 overfitting 的方式是觀察訓練結果是否很大的優於測試結果，如果有就將其判斷成 overfitting，但造成訓練和測試結果有差距的原因有很多，overfitting 只是其中一種。舉一個例，如果你資料切分的不乾淨，也很可能造成訓練資料和測試資料的 pattern 有較大的差異，造成結果上有顯著的不同，或是其實我根本沒有把模型訓練好，測試結果當然不會好，甚至更差。</p><p>因此實務上與其透過訓練和測試結果的差距去判斷模型是否有 overfitting 和 underfitting，不如用 bias 和 variance 更好的收斂模型現況問題。其實學過統計學的人應該對 bias 和 variance 都不陌生，對數學推導有興趣的人可以去看<a href="https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff">這篇</a>，我這邊用實證的方式展示給各位看。</p><h3>步驟一 產生假資料</h3><p>目標是產生一個上半圓來當作我們的資料集。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*xrzjREHZihJhR8qxLOWUMA.png" /></figure><h3>步驟二 切分資料</h3><p>藍色的是 training data，橘色的是 test data。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*cMlMElb6Aiy15DFP7UW84g.png" /></figure><h3>步驟三 訓練模型</h3><p>這邊用了四個模型，依序是線性回歸、決策樹回歸、多項式回歸(degree=2) 、多項式回歸(degree=8)，模型訓練結果如下:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdMnZYUtAyeKPpG_Kewh9w.png" /></figure><h3>步驟四 找出 Bias 和 Variance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*O0gTAGW6kMoneUH--cwT9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*l6xx9EyFnexaKInnll-3GA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*7ovyluXAqN2AQXQhc8urKQ.png" /></figure><p>上面是兩者的公式，看起來很熟悉吧~學過統計的人一定推導過。bias 簡單來說就是模型估計值與真實值整體的平均誤差(亦可視為預測模型與真實資料 pattern 的平均誤差)，而 variance 就是模型自身的變異程度。</p><p>這裡值得一提的是，一般我們在做機器學習的專案時，不會特別假設什麼函數或分配，所以有時候你可能會無法輕易的將統計模型與機器學習的模型連結在一起，實際上他們的概念是一樣的，區別只在於求解的方法，統計學擅長推導求出公式解，機器學習擅長透過近似求解，還有統計上的真實資料是透過假定一個真實函數所產生的隨機變數而來，而機器學習是透過蒐集大量的數據做為真實資料的集合，這也是為何大數據與機器學習密不可分的原因。</p><p>從步驟三我們可以發現，線性回歸和degree=2的多項式回歸當自變數(feature)小幅變動時，模型的估計值並無劇烈的高低起伏，但右邊的決策樹和degree=8 的多項式回歸 ，相對而言比較容易因為自變數（feature)的變動而大起大落，這也反映了有些時候如果你用相對複雜的模型去解釋簡單的 pattern ，會導致模型去追求與訓練資料非常擬合(overfitting)，導致估計模型的 variance 很大，且 bias(測試結果)不好，不過 bias 也不至於太大，如果太大可能就是資料沒切乾淨，訓練和測試集 pattern 有顯著差距，或是模型未收斂導致。反過來說，在 bias 很大的情況下，variance 很小，代表模型太過簡單，沒有辦法讓模型好好的擬合訓練資料，更別提能夠有好的測試結果，這時就是發生 underfitting 的現象了。</p><p>想要了解更多，可以去看 mlxtend 套件的 <a href="http://rasbt.github.io/mlxtend/user_guide/evaluate/bias_variance_decomp/">Bias-Variance Decomposition</a> 函數說明，我也是用此套件計算模型的 bias 和 variance。</p><h4>模型 Bias 和 Variance 計算結果如下</h4><h4>Linear Regression :</h4><pre>Average expected loss(MSE): 0.070<br>Average bias: 0.068<br>Average variance: 0.002</pre><p>結論: 低 varience，高 bias =&gt; 為 underfitting 的特徵</p><h4>Decision Tree Regressor:</h4><pre>Average expected loss(MSE): 0.015<br>Average bias: 0.007<br>Average variance: 0.009</pre><p>結論: 低 bias，高 varience=&gt; 為 overfitting 的特徵</p><h4>Polynomial Basis Model(degree=2):</h4><pre>Average expected loss(MSE): 0.006 <br>Average bias: 0.004 <br>Average variance: 0.002</pre><p>結論: 低 bias，低 varience =&gt; 通常這種情況 mse 很可能也很低！</p><h4>Polynomial Basis Model(degree=8):</h4><pre>Average expected loss(MSE): 140.643 <br>Average bias: 1.412 <br>Average variance: 139.231</pre><p>結論: 高 bias，高 varience =&gt; 模型架構不適合此資料集導致模型並未收斂，當然有時候也可能是模型訓練的不夠久而導致</p><p>下面這張圖常被用來解釋 bias 和 variance(我用 draw.io 畫了一張)，讀者可以思考一下，哪一種是 overfitting 哪一種是 underfitting 呢?(上面就有答案了)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*3GP19bfsCnJgMKfZ7Dq3rw.png" /></figure><h3>結論:</h3><p>不知道各位有沒有經歷過，模型太強，導致 overfitting 的現象，因此加入一些可以干擾模型收斂的參數或是透過降低訓練疊代次數等方法讓模型不要過度擬合訓練資料，結果重新訓練的模型效果很差，又要加強模型的複雜度，讓模型預測能力更強，像這種拉扯的過程，其實就是所謂的<a href="https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff"> Bias–variance tradeof</a>f，也是資料科學家必須跨過的重要難題😱，完整的程式碼放在我的 <a href="https://github.com/EricTsai83/machine_learning/blob/main/model_performance/ML_bias_and_varience.ipynb">GitHub</a>，謝謝 !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4294284e54a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[透過 Python 與 Excel 巨集自動化產出 Excel 報表]]></title>
            <link>https://erictsai492718.medium.com/%E9%80%8F%E9%81%8E-python-%E8%88%87-excel-%E5%B7%A8%E9%9B%86%E8%87%AA%E5%8B%95%E5%8C%96%E7%94%A2%E5%87%BA-excel-%E5%A0%B1%E8%A1%A8-67b14f2c4bd9?source=rss-d5f83f0bd9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/67b14f2c4bd9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[vba]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Eric Tsai]]></dc:creator>
            <pubDate>Fri, 02 Apr 2021 16:06:51 GMT</pubDate>
            <atom:updated>2021-06-20T13:23:34.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NvTtRf9cf8AFJYK7" /><figcaption>Photo by <a href="https://unsplash.com/@agk42?utm_source=medium&amp;utm_medium=referral">Alex Knight</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>為何需要把 Excel 巨集加入自動化產生報表的流程？ 全部都用 Python 不香嗎？</h3><p>很多時候分析師與資料科學家在產出報表時，需要考慮到報表使用者的習慣，例如是否進行資料篩選、產出樞紐報表和資料排序...等。而 Excel 正是非程式專業的人最常用的資料分析工具，特別是樞紐分析表，給了分析者在敘述統計領域上很大的操作空間。</p><p>以下我會透過一個實作專案講解怎麼建立一個自動化流程，首先專案需求是這樣：</p><p>公司每天會產出一份 Excel 的資料(假日除外)，長官不定期會需要你產出樞紐分析報表，但你不想每次都拉同樣形式的樞紐表跟調整版面與顏色，因此想自動化去做這件事，實作方式如下:</p><p>底下是我的工作目錄結構:</p><pre>deal_with_excel<br>    |<br>    --Code<br>    |<br>    --Data<br>    |   |<br>    |   --meta_data<br>    |<br>    --Output</pre><h4>透過 Python 自動化產出樞紐分析報表</h4><h4>Note</h4><ol><li>初始自動化程序時會需要先錄製 Excel 巨集，之後就不用了</li><li>展示的程式碼均在 notebook 中執行(也可用 script)</li></ol><h4>Import 套件</h4><pre># deal with data<br>import pandas as pd<br>import numpy as np  # only used for synthetic data<br>import random  # only used for synthetic data<br>from datetime import datetime  # only used for synthetic data<br>import re</pre><pre># load data<br>import glob</pre><pre># deal with excel<br>import xlsxwriter<br>import os<br>import shutil<br>import win32com.client as win32</pre><p>輸入 initial 或 auto 告訴電腦你是要初始自動化專案還是要自動產出樞紐報表</p><pre>procss = input(&#39;Mode:(initial/auto): &#39;)</pre><h4>取得資料與資料處理</h4><p>假設我們是從 Data 的資料夾取得我們要的資料</p><pre># extract file date<br>def extract_date(x):<br>    return re.sub(r&#39;[^\d-]&#39;, &#39;&#39;, x)</pre><pre># run several date<br>product_expense = pd.DataFrame()<br>date_li = []<br>for file in glob.glob(&quot;../Data/product_expense*.csv&quot;):<br>    print(f&quot;load file: {file}&quot;)<br>    date_li.append(extract_date(file))<br>    df = pd.read_csv(file)<br>    product_expense = pd.concat([product_expense, df])<br>    print(f&quot;all data len: {len(product_expense)}&quot;)<br>product_expense = product_expense.reset_index(drop=True)</pre><pre># 資料排序<br>date_li.sort()</pre><pre># 取得資料期間(當作最終產出的檔名用的)<br>date_interval_str = date_li[0] + &#39;_&#39; + date_li[-1]</pre><h4>初始自動化程序</h4><p>步驟如下：<br>1. 透過 pd.ExcelWriter，將上面跑的資料作為樣板，建一個 xlsx file 在 meta_data 資料夾當中</p><p>2. 程式會自動打開步驟一建立的檔案，然後請手動建立 Excel 巨集（可以用VBA寫，也可以用錄製的方式，我個人覺得後者更加方便），並另存新檔（副檔名要是xlsm，檔案才會包含巨集 )，完成後輸入Y，程式會先檢查你是否真的建立一個含有巨集的 Excel</p><p>3. 找到此腳本(vba_extract.py) 在你電腦的位置，我的電腦是在 D:\Anaconda3\Scripts 當中，將當前目錄更改到 D:\Anaconda3\Scripts</p><p>4. 透過 D:\Anaconda3\Scripts 當中的 vba_extract.py ，從含有巨集的 Excel 當中萃取出巨集檔 (vbaProject.bin)在當前目錄(D:\Anaconda3\Scripts)</p><ul><li>將 vbaProject.bin 改成你喜歡的名子，並移動到此 notebook 所處的資料夾</li><li>將當前目錄更改回此 notebook 所處的資料夾</li></ul><p>程式碼如下：</p><pre>excel_macro_template_name = &#39;excel_macro_template&#39;</pre><pre>Code_abspath = os.getcwd()<br>meta_data_abspath = os.path.abspath(os.path.join(os.getcwd(), &quot;..&quot;))+&#39;\\Data\\meta_data&#39;<br>Output_abspath = os.path.abspath(os.path.join(os.getcwd(), &quot;..&quot;))+&#39;\\Output&#39;<br>macro_name = input(&#39;Type excel macro name: &#39;)</pre><pre>if procss==&#39;initial&#39;:<br>    print(&#39;Initial mode\n=================================================&#39;)<br>    <br>    ### Step 1<br>    xlsx_macro_template_path = os.path.abspath(f&#39;../Data/meta_data/{excel_macro_template_name}.xlsx&#39;)<br>    writer = pd.ExcelWriter(xlsx_macro_template_path)<br>    product_expense.to_excel(writer, index=False, sheet_name=f&#39;data_{date_interval_str}&#39;, header=True)<br>    writer.save()</pre><pre>### Step 2<br>    xl= win32.Dispatch(&quot;Excel.Application&quot;)<br>    wb = xl.Workbooks.Open(xlsx_macro_template_path)  # , ReadOnly=1<br>    xl.Visible = True<br>    print(&#39;1. please record a macro in Excel\n2. Save as xlsm file in the same path&#39;)<br>    complete_step = input(&#39;Whether the above step is complete?(Y/N)&#39;)</pre><pre>if complete_step == &#39;Y&#39; or complete_step == &#39;y&#39;:<br>        # check excel which has macro whether exist<br>        if os.path.exists(f&#39;../Data/meta_data/{excel_macro_template_name}.xlsm&#39;):<br>            pass<br>        else:<br>            raise FileNotFoundError(&quot;You didn&#39;t create a macro template&quot;)<br>    else:<br>        raise ValueError(&#39;Step not completed. Please restart kernel and run notebook again&#39;)</pre><pre>### Step 3<br>    #### Extract a macro from Excel<br>    if complete_step == &#39;Y&#39; or complete_step == &#39;y&#39;:<br>        file_path = &#39;D:\Anaconda3\Scripts&#39;<br>        os.chdir(file_path)</pre><pre>run_script = f&quot;python vba_extract.py {meta_data_abspath + &#39;/&#39; + excel_macro_template_name + &#39;.xlsm&#39;}&quot;<br>        os.system(run_script)</pre><pre>#     meta_data_file_path = &#39;D:\python\deal_with_excel\Data\meta_data&#39;<br>        os.rename(&#39;vbaProject.bin&#39;, meta_data_abspath+&#39;\\&#39;+ macro_name+&#39;.bin&#39;)</pre><pre>#     code_file_path = &#39;D:\python\deal_with_excel\Code&#39;<br>        os.chdir(Code_abspath)<br>    else:<br>        raise ValueError(&#39;Step not completed. Please restart kernel and run notebook again&#39;)<br>else:<br>    print(&#39;Auto mode\n=================================================&#39;)</pre><h4>自動化程序</h4><p>步驟如下：<br>1. 建立一個 Excel，將上方所得的 data frame 寫入 xlsx file，然後修改副檔名成 xlsm，在 load Excel 巨集檔(vbaProject.bin)到 Excel 中，並儲存</p><p>2. 透過 win32 套件連接 Excel 應用程式</p><p>3. 打開上一步驟儲存的應用程式</p><p>4. 運行巨集</p><p>5. 儲存結果到 Output 資料夾</p><p>6. 關閉 Excel 應用程式</p><p>程式碼如下：</p><pre># 步驟1<br>writer = pd.ExcelWriter(meta_data_abspath + f&#39;\\{excel_macro_template_name}.xlsx&#39;)<br>product_expense.to_excel(writer, index=False, sheet_name = f&#39;data_{date_interval_str}&#39;, header=True)  <em># 這裡會覆蓋原本是 template 的資料</em></pre><pre>wb = writer.book<br>wb.filename = os.path.abspath(meta_data_abspath + f&#39;\\{excel_macro_template_name}.xlsm&#39;)<br>if os.path.exists(meta_data_abspath + f&#39;\\{macro_name}.bin&#39;):<br>    wb.add_vba_project(os.path.abspath(meta_data_abspath + f&#39;\\{macro_name}.bin&#39;))<br>else:<br>    raise ValueError(&quot;Can&#39;t found macro file&quot;)<br>writer.save()</pre><pre># 步驟2-6<br>if os.path.exists(meta_data_abspath+f&#39;\\{excel_macro_template_name}.xlsm&#39;):<br>    try:<br>        xl= win32.Dispatch(&quot;Excel.Application&quot;)<br>        wb = xl.Workbooks.Open(os.path.abspath(meta_data_abspath + f&quot;\\{excel_macro_template_name}.xlsm&quot;))  # , ReadOnly=1<br>        xl.Application.Run(f&quot;{excel_macro_template_name}.xlsm!Module1.create_pivot_table&quot;)<br>        # if you want to save then uncomment this line and change delete the &quot;, ReadOnly=1&quot; part from the open function.<br>        xl.Visible = True<br>        wb.SaveAs(os.path.abspath(Output_abspath + f&quot;\\product_expense_{date_interval_str}.xlsm&quot;))<br>    finally:    <br>        xl.Application.Quit() # Comment this out if your excel script closes</pre><pre>del xl</pre><p>完整的程式碼放在我的 <a href="https://github.com/EricTsai83/excel_auto_pivot_table">github</a> 當中，謝謝大家😱!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67b14f2c4bd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用 Pandas DataFrame 常用的 26 個基本技巧]]></title>
            <link>https://erictsai492718.medium.com/%E4%BD%BF%E7%94%A8-pandas-dataframe-%E5%B8%B8%E7%94%A8%E7%9A%84-26-%E5%80%8B%E5%9F%BA%E6%9C%AC%E6%8A%80%E5%B7%A7-acf83105dcf4?source=rss-d5f83f0bd9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/acf83105dcf4</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Eric Tsai]]></dc:creator>
            <pubDate>Sun, 28 Mar 2021 10:19:54 GMT</pubDate>
            <atom:updated>2021-06-20T15:25:32.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BKJ1ZvHlCewJugun" /><figcaption>Photo by <a href="https://unsplash.com/@mpayne66?utm_source=medium&amp;utm_medium=referral">Michael Payne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>使用 Pandas DataFrame 常用的 27 個基本技巧</h3><p>本篇文章主要分四個部分，第一個部分是 dataframe 的基本操作，第二是過濾資料或找特定資料的方法，第三是 dataframe 資料分組的操作，最後一個部分則是我個人常用到的資料處理技巧</p><h3>Dataframe 的基本操作</h3><ol><li>在本地主機載入和儲存 dataframe</li></ol><pre>import pandas</pre><pre># csv<br>df = pd.read_csv(&#39;./file_name.csv&#39;)<br># json<br>df = pd.read_json (&#39;./file_name.json&#39;)<br># pikle<br>df = pd.read_pickle(&#39;./file_name.pkl&#39;)<br># excel<br>df = pd.read_excel(&#39;./file_name.xlsx&#39;, sheet_name=&#39;sheet_name_1&#39;)</pre><p>2. 從SQL Server 載入 dataframe</p><pre>import pyodbc</pre><pre>cnxn = pyodbc.connect(&#39;Trusted_Connection=yes&#39;, driver=&#39;{SQL Server}&#39;, server=&#39;tcp:myserver&#39;)<br>cursor = cnxn.cursor()<br>sql = f&#39;&#39;&#39;<br>sql code here<br>&#39;&#39;&#39;<br>df = pd.read_sql(sql, cnxn)<br>cursor.close()<br>cnxn.close()</pre><p>3. 將 data frame 輸出到本地主機</p><pre># csv<br>df.to_csv(&#39;./file_name.csv&#39;)<br># json<br>df.to_json(&#39;./file_name.json&#39;)<br># pikle<br>df.to_pickle(&#39;./file_name.pkl&#39;)<br># excel<br>df.to_excel(&quot;file_name.xlsx&quot;, sheet_name=&#39;Sheet_name_1&#39;)</pre><p>4. 手動建立 data frame</p><p>分別有兩種方法，一種是用矩陣表達資料樣式，另一種是用字典方式將資料轉換成 data frame</p><pre># create dataframe by matrix<br>data = [[1,2,3],<br>        [4,5,6],<br>        [7,8,9]]<br>pd.DataFrame(data, columns=[&#39;A&#39;,&#39;b&#39;,&#39;c&#39;])</pre><pre># create dataframe by dictionary<br>dic = {&#39;A&#39;:[1,4,7],<br>       &#39;b&#39;:[2,5,8],<br>       &#39;c&#39;:[3,6,9]}<br>pd.DataFrame(dic)</pre><p>5. 檢查 data frame 的資料</p><p>通常都是檢查前五列或後五列，展示的列數可以在括號內做調整</p><pre>df.head()<br>df.tail()</pre><p>6. data frame 重新命名</p><pre>df.columns = [&#39;name1&#39;, &#39;name2&#39;, &#39;name3&#39;]</pre><p>7. 將特定欄位作為 data frame 的 index</p><pre>df.set_index(&#39;A&#39;,inplace=True)</pre><p>8. 透過特定欄位來合併兩個 data frame</p><p>df1 和 df2 都為 dataframe，how 為 data frame 合併的方式，比較常用的參數有 &#39;inner&#39; 、&#39; left&#39; 和 &#39;right&#39;，如果熟悉 SQL 的人，這些合併方法應該不陌生，至於 left_on 和 right_on 則是合併兩個 data frame 所需要的 key 值</p><pre>df1.merge(df2, how, left_on, right_on)</pre><p>9. 串聯兩個 data frame</p><pre>df3 = pd.concat([df1,df2], axis=1)</pre><p>10. 重置 data frame 的 index，</p><p>data frame 的資料經過篩選後，index 會有跳號的情形，通常我們會透過下面的方法，重置 index</p><pre>new_df = df.reset_index(drop=True,inplace=False)</pre><p>11. 新增欄位到 data frame</p><pre># 我習慣的做法(會新增欄位到最後一欄)<br>df[&#39;new_col_name&#39;] = data</pre><pre># 但有時候你希望新增的欄位在指定的順序位置(ex.新增到第一欄)<br>df.insert(loc=0, column=’new_col_name’, value=1)</pre><h3>過濾資料和找特定資料的方法</h3><p>12. 過濾 data frame 的資料</p><pre># 你想要A欄位大於10的資料，寫法如下<br>df.query(&quot;A&gt;10&quot;)</pre><pre>#  你想要A欄位大於10，且B欄位小於12的資料，寫法如下<br>df.query(&quot;A&gt;10 &amp; B&lt;12&quot;)</pre><p>13. 透過 boolean(布林) 值，作為篩選指標</p><pre># 只回傳 column_name 等於 1 的資料列<br>df[df[&#39;column_name&#39;]==1]</pre><pre># 只回傳 column_name1 和 column_name2 不是空值的資料列<br>df[df[&#39;column_name1&#39;].notnull() &amp; df[&#39;column_name2&#39;].notnull()]</pre><pre># 只回傳 column_name 有在出現在列表中的資料列<br>value_list = [1,3,5,7,9]<br>mask = df[&#39;column_name&#39;].isin(value_list)<br>df[mask]</pre><p>14. 透過 index 或欄位名稱找到 data frame 中的資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*GjvZ3k7-LaqPHL5LAu2K6g.png" /><figcaption>Table1</figcaption></figure><pre>df.iat[1,2]<br>out: 20</pre><pre>df.at[3,&#39;A&#39;]<br>out: 2</pre><pre>df.loc[[1,3],[&#39;B&#39;,&#39;C&#39;]]<br>df.iloc[[1,3],[1,2]]<br>out:<br>   B   C<br>---------<br>1  0   20<br>3  0   0</pre><h3>Data Frame 資料分組的操作</h3><p>15. data frame 資料分組</p><p>Data Frame 可以透過一個或多個欄位中的值進行分組，以上面 Table1的資料為例，如果透過A欄位進行分組，而A欄位只有 0, 1, 2 三種值的話，透過 groupby 可以將 data frame 分成相應的三組資料</p><pre>df_groupby_A = df.groupby(&#39;A&#39;)<br>df_groupby_AB = df.groupby([&#39;A&#39; ,&#39;B&#39;])</pre><pre># 我個人很常會用到 groupby 加 size 回傳 groupby 後欄位中各個數值的資料數量<br>df.groupby(&#39;A&#39;).size()</pre><p>16. 取得分組資料</p><pre># 取得 A 欄數值是1的資料(列)<br>df_group_A.get_group(1)</pre><p>17. 透過特定欄位來聚合其他欄位的資料</p><p>無論是分組進行統計相關計算(平均數、標準差等)或將其他欄位的資料透過列表儲存在 cell 當中，都是非常實用的技巧</p><pre>test_group = df.groupby(&#39;A&#39;).agg({&#39;A&#39;:sum, &#39;B&#39;: list})<br>test_group.reset_index(drop=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*5XfFo6A0Mia7KWt6-Y21fA.png" /><figcaption>Table2</figcaption></figure><p>18. 轉置 data frame</p><pre>df.T</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*GjvZ3k7-LaqPHL5LAu2K6g.png" /><figcaption>Table1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/1*jfPOmgBOyq-VL_5OGvbFmg.png" /><figcaption>Table3</figcaption></figure><h3>資料處理技巧</h3><p>19. apply</p><p>透過 apply 可以利用 function 一列一列的進行資料處理。另外有一個叫 <a href="https://github.com/jmcarpenter2/swifter">swifter</a> 的套件可以在 apply 的基礎上直接使用。</p><pre>df[&#39;column_name1&#39;].apply(function, axis=0)<br>df[[&#39;column_name1&#39;, &#39;column_name2&#39;]].apply(function, axis=1)</pre><pre># use swifter<br>df[&#39;column_name&#39;].swifter.progress_bar(False).apply(function)</pre><p>20. np.vectorize</p><p>用法上幾乎跟 apply 一樣，主要差別在於 np.vectorize 有透過 numpy 套件在運算效能上進行優化，所以如果你撰寫的 function 裡面有越多東西可以轉移到 numpy，你運算的速度就會越快，但如果沒有，直接用 apply 會是更好的方法，有興趣可以參考<a href="https://stackoverflow.com/questions/52673285/performance-of-pandas-apply-vs-np-vectorize-to-create-new-column-from-existing-c">這裡</a></p><pre>np.vectorize(function)(df[&#39;column_name1&#39;])</pre><p>21. 依序疊代 data frame 的 row</p><p>請注意: 這不是一個好的資料處理方法，特別是資料龐大的時候，如果你確定要這麼做，請先確保其它更快的解決方案你都嘗試過了</p><pre># 透過 enumerate 可以依序回傳疊代的index(疊代到第幾次)和資料列<br>for index, row in enumerate(df[&#39;A&#39;]):<br>    print(f&#39;index: {index}, row: {row}&#39;)</pre><pre># 透過 iterrows 和 itertuples 依序還傳資料列<br>for index, row in df.iterrows():<br>    print(row[&#39;A&#39;], row[&#39;B&#39;])</pre><pre>for row in df.itertuples(index=True, name=&#39;Pandas&#39;):<br>    print(row.A, row.B)</pre><p>22. 將有NA 值的列或欄丟棄</p><pre># axis=0 丟棄列，axis=1 丟棄欄<br>df.dropna(axis=0,inplace=True)</pre><pre># 丟棄特定欄位<br>df.dropna(subset=[&#39;column_name&#39;])</pre><p>23. 重塑 data frame</p><p>將資料重塑成兩欄</p><pre>pd.DataFrame(df.values.reshape(-1,2), columns=[&#39;A&#39;,&#39;B&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*rVJ2QpMQjBCFQbd3Wc3jQw.png" /><figcaption>Original Table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/78/1*ajul2P1w77BkYKWwWFah2g.png" /><figcaption>Reshape Table</figcaption></figure><p>24. 資料排序</p><pre>df.sort_values(by=&#39;A&#39;, ascending = False)</pre><h3>資料處理技巧-進階</h3><p>25. 丟棄滿足欄位名稱特定條件的欄位</p><p>假設今天有一個 data frame，欄位名稱分別為A_TW、B、C，但我們不想要結尾有 TW 的欄位，我們可以透過建構一個丟棄列表(其中包含所有結尾為TW 的欄位名稱)</p><pre>droplist = [i for i in df.columns if i.endswith(&#39;TW&#39;)]<br>df.drop(droplist, axis=1, inplace=True)</pre><p>26. 如果你有讀取 excel(xlsx file) 的經驗，有時候會出現以下狀況，這時你可以透過filter，過濾掉你不需要的欄位，跟上一個技巧有異曲同工之妙</p><pre>df.drop(df.filter(regex=&quot;Unname&quot;),axis=1, inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*fxgPi-G8jaAg7V_d_yr32Q.png" /></figure><p>27. 如果您習慣用 daat frame 整理資料的話，有時候你會遇到一種現象，如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*wdoa62pyuEHfxwDsP23vXg.png" /><figcaption>Original Table</figcaption></figure><p>這時如果你想要將 prefer_thing 欄位資料展開，以下提供兩個 function 幫助你垂直或水平展開欄位:</p><h4>垂直展開</h4><pre>def flattenColumn(df, column):<br>    &quot;&quot;&quot;<br>    column is a string of the column&#39;s name.<br>    for each value of the column&#39;s element (which might be a list),<br>    duplicate the rest of columns at the corresponding row with the (each) value.<br>    &quot;&quot;&quot;<br>    column_flat = pd.DataFrame(<br>        [<br>            [i, c_flattened]<br>            for i, y in df[column].apply(list).iteritems()<br>            for c_flattened in y<br>        ],<br>        columns=[&#39;I&#39;, column]<br>    )<br>    column_flat = column_flat.set_index(&#39;I&#39;)<br>    return (<br>        df.drop(column, 1)<br>             .merge(column_flat, left_index=True, right_index=True)<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*Pyq6hmabtt8dIFlfTsqNrA.png" /><figcaption>Flatten column</figcaption></figure><h4>水平展開</h4><pre>df = pd.DataFrame([pd.Series(x) for x in df.prefer_thing])<br>df.columns = [&#39;team_{}&#39;.format(x+1) for x in df.columns]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*f2lrOC8Zw2Y1gtEJoxJMnA.png" /></figure><p>謝謝大家😱!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acf83105dcf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[如何使用 Python 的 Generator ?]]></title>
            <link>https://erictsai492718.medium.com/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8-python-%E7%9A%84-generator-30581ac9effd?source=rss-d5f83f0bd9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/30581ac9effd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[generator]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[toturial]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Eric Tsai]]></dc:creator>
            <pubDate>Sat, 20 Mar 2021 17:03:09 GMT</pubDate>
            <atom:updated>2021-03-20T17:20:29.181Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yaFIfpEuAx7r5h_q" /><figcaption>Photo by <a href="https://unsplash.com/@qmikola?utm_source=medium&amp;utm_medium=referral">Mikołaj</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>如何使用 Python 的 Generator ?</h3><h4>如果你的電腦沒有足夠的內存幫你處理大量的數據，也許Python 的 Generator 可以幫助到你</h4><h3>為何會需要使用 Generator？</h3><p>如果你是一名資料科學家，也許你時常會需要處理大量的資料，但如果電腦沒有足夠的內存時，就會容易發生 memory error，以下就舉兩個可能的情境（我瞎想的）：</p><h4>例一</h4><p>假設今天有一部小說要改編成電影，電影公司想要藉由機器學習的方法預測哪一些章節串連起來可能可以讓觀看者在觀看電影時有足夠的情緒起伏，但一本小說會有多個章節，每個章節又都有大量的文字，若想要一次讀取整本小說進行分析將必須擁有很大的內存記憶體(一般電腦應該是沒有)。</p><p>如果今天我們已經建好一個模型，模型的 input 是一段文字，output 會是這段文字情緒起伏的分數，這時我們會需要依序讀取章節內容並進行辨識與儲存結果，然後釋放章節內容所佔的內存，然後再讀取下一個章節內容並進行辨識與儲存結果，直到整個劇本的章節都被我們辨識完畢。透過 generator 我們可以輕鬆寫出以上的處理流程，詳細作法如下：</p><p>以下是一本小說的文字檔，假設它很大:)</p><pre>chapter1.<br>angry angry angry angry<br>chapter2.<br>happy happy happy<br>chapter3.<br>hurt hurt<br>chapter4.<br>sad<br>chapterEnd</pre><p>這麼大的檔案:)，一次讀取再進行分析，內存一定不夠，這時我們就可以寫一個 generator ，讓它透過迴圈或 __next__函數，來依序幫我們產出每一行的文字，且產出下一行文字時，若不特別去記下產出結果的話，機器並不會自己記住上一行的產出結果，因此不會讓機器一直消耗內存，詳細作法如下:</p><p>底下是一個逐行讀取文字檔的 generator，可以看出只要在定義 function 時，不使用 return 改用 yield 就可以輕鬆寫出一個 generator。</p><pre>def txt_reader(file_name):<br>    for row in open(file_name, &quot;r&quot;):<br>        yield row</pre><p>這裡有一個細節要注意，就是當我們要應用 generator 時，一定要將其 assign 一個名稱，如下:</p><pre>g = txt_reader(&#39;./large_file.txt&#39;)</pre><p>不然每次呼叫 txt_reader 時，都會進行初始化，導致你在取值時，只會回傳generator 第一個會產生的結果(在這個例子下會是第一行的文字)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*v71vH5X0ksQOVyL8yeL9HQ.png" /></figure><p>從上方程式碼的展示，我們可以發現 generator 可以透過 __next__ 函數依序產生每一行的文字，但其實 generator 不只一種產生方法，還可以透過 for 迴圈及 list 函數的方式取得產生器產出的結果，原因是 generator 支援 iterator 的操作模式，這裡不做 iterator 的相關解釋，若有興趣可以去看這篇<a href="http://changlt.blogspot.com/2017/05/pythoniteratoriterablegenerator.html">文章</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*RBJb3SMN7oIJuSyFbOZvYQ.png" /></figure><p>回到讀取小說章節的例子，我們再來要寫一個 function 來獲取需要的資料</p><pre>def return_chapter_content():<br>    content_li = []<br>    for row in g:<br>        temp = row        <br>        if not &#39;chapter&#39; in temp:<br>            content_li.append(temp)<br>            return content_li<br>        else:<br>            if temp == &#39;chapterEnd&#39;:<br>                print(&#39;No content anymore&#39;)<br>            else:<br>                pass</pre><p>從下方運行程式碼的結果，可以看出 generator 可以輕易地透過呼叫相同的 function，讓機器吐章節的內容給我們，透過這個 function 我們可以很方便的取得章節內容，而不用擔心大量資料一次讀取所造成的 memory error 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*BJ320KHlQrB8tuxTDsSh9Q.gif" /></figure><h4>例子二</h4><p>建構一個無限循環的 function，我想這個部分在資料分析上應該比較少遇到，但還是提一下，也許哪天會用到 :)，網路上有一個很常見的例子就是<a href="https://zh.wikipedia.org/wiki/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0%E5%88%97">費氏數列</a>，定義如下</p><p>F0=0</p><p>𝐹1=1</p><p>𝐹𝑛=𝐹𝑛−1+𝐹𝑛−2（𝑛≧2）</p><p>因為費氏數列是一個無限長度的數列，假設你知道到你會用到很大量費氏數列中的值，但無法確定是多少，這時候就很適合使用 generator ，避免一開始要先產出一個很大的 list 去紀錄費氏數列的數值以備不時之需，所以建立一個產生器，等要用到費氏數列時，再透過 function 呼叫的方式，依序產出序列中的數值會是一個不錯的解決方案，程式碼如下:</p><pre>def fibonacci():<br>    first = 0<br>    second = 1<br>    yield first<br>    yield second</pre><pre>    while True:<br>        after_num = first + second<br>        yield after_num<br>        first = second<br>        second = after_num</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*BORwYMHA4YisklY4_jy02w.gif" /></figure><p>但這裡值得一提的是，如果你沒有要用到很大量的費氏數列數值，其實你直接建構一個有限且長度短的費氏數列來使用，會是一個更有效率的方法，邏輯上也很容易理解，就是在不佔太多內存記憶體的狀況下，直接產出完整的數列加以運用，會比用 generator 一次一次產出數值還快的多。</p><p>第一次用中文的方式寫文章，希望大家喜歡!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30581ac9effd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Python Multithreading and Multiprocessing by visualization]]></title>
            <link>https://erictsai492718.medium.com/understanding-python-multithreading-and-multiprocessing-by-visualization-41e529f2da6a?source=rss-d5f83f0bd9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/41e529f2da6a</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[multiprocessing]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Eric Tsai]]></dc:creator>
            <pubDate>Sun, 14 Mar 2021 10:55:01 GMT</pubDate>
            <atom:updated>2021-09-21T09:15:13.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tUo6mtOA0wTGXN7p" /><figcaption>Photo by <a href="https://unsplash.com/@artisanalphoto?utm_source=medium&amp;utm_medium=referral">ArtisanalPhoto</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>If you want to know the visualization method, please refer to this <a href="https://medium.com/@bfortuner/python-multithreading-vs-multiprocessing-73072ce5600b">article</a>. I will only present the results and my findings. Or you can find the code on my <a href="https://github.com/EricTsai83/parallel_processing/blob/main/multithreading_multiprocessing.ipynb">Github</a>.</h4><h3>Why do we need to understand parallel processing?</h3><p>I think the direct reason is we can use computational resources sufficiently on our machines. It is meant to reduce the overall processing time. But not every task is suitable for parallel processing. Even it is feasible, ways of parallel processing have different timing to apply.</p><h3>Explain the principle of parallel processing</h3><p>In Python, we have two ways to use parallel operations. One is multithreading, and the other is multiprocessing. I draw a diagram to display how multithreading and multiprocessing work roughly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*EDU6OpbJ1n9vyrSfhNPDlQ.png" /></figure><h3>The critical difference between multithreading and multiprocessing</h3><h4>Different ways to increasing computing power</h4><p>Multiprocessing adds CPUs(or processors) for increasing computing power. And multithreading creates many threads in a single processor to get the same effect.</p><h4>Multiprocessing process creation is time-consuming work. While in Multithreading, process creation is economical.</h4><p>Multiprocessing will copy a virtual memory space to each processor. But multithreading does not. It let each thread share a memory space.</p><h3>Let me show you some cases.</h3><blockquote>I use two evaluation indexes. One is multithreading or multiprocessing whether can reduce computation time. The other is which way is better for reduce run time. It can help you to understand application timing for multithreading and multiprocessing.</blockquote><h4>API Calls (download task):</h4><pre>from urllib.request import urlopen<br>url_N = 10<br>URL=&#39;<a href="http://scholar.princeton.edu/sites/default/files/oversize_pdf_test_0.pdf&#39;">http://scholar.princeton.edu/sites/default/files/oversize_pdf_test_0.pdf&#39;</a><br>urls = [URL for i in range(url_N)]<br>resp = urlopen(url)<br></pre><p>Get time benefit from both multithreading and multiprocessing. The performances seem almost equal, but multithreading doesn’t need to create more processes (use less memory). So multithreading is better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*snEbWA3rw5fau_L61o1j5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*I_LcLKSK-5j-qKVcUBaXXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*z2F8JfGHUIOuWr1aOMAWQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*L-4FB2AUSX_jSO5zK2Kb7A.png" /></figure><h4>IO Heavy (write a big string into a file)</h4><pre>TEXT = &#39;&#39;.join(random.choice(string.ascii_lowercase) for i in range(10**7*5))<br>text_N = 12</pre><pre>f <strong>=</strong> open(&#39;output.txt&#39;, &#39;wt&#39;, encoding<strong>=</strong>&#39;utf-8&#39;)<br>f.write(text)<br>f.close() </pre><p>Multithreading is better than multiprocessing. It seems like multithreading can parallel processing without waiting for other tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*yiN6rZeHqyWqLVXTAqc7KA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*vWJgkExi4vDDdJpGoMLpzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*TLjF1_JLoMxkSQ-QK0lVvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*SK1Y19SGcEi3gI3Cv1vJ0g.png" /></figure><h4>Numpy Functions</h4><p>In this case, multithreading and multiprocessing can both reduce run time. Using multiprocessing, we find that process creation is pretty time-consuming when your NumPy array is enormous. So depend on total run time, multithreading is better than multiprocessing no matter whether you use Numpy to Addition or Dot Product. But when tasks are many, I think multiprocessing might be better.</p><ol><li><strong>Numpy Addition</strong></li></ol><pre>DIMS <strong>=</strong> 8000<br>numpy_add_N <strong>=</strong> 20<br>DIMS_ARR <strong>=</strong> [DIMS <strong>for</strong> i <strong>in</strong> range(numpy_add_N)]<br>a <strong>=</strong> np.random.rand(DIMS,DIMS)<br>b <strong>=</strong> np.random.rand(DIMS,DIMS)<br>res = a <strong>+</strong> b</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*dcMDZGVknpq3QDgvkdeYZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*fONXObUrh6XBf-6EMJ8fyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*-mMek3KOg-1ynDlf6NZ0lQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*KpqYPietB4RZSfvfui1b2A.png" /></figure><p><strong>2. Dot Product</strong></p><pre>DIMS <strong>=</strong> 1500<br>dot_N <strong>=</strong> 10<br>DIMS_ARR <strong>=</strong> [DIMS <strong>for</strong> i <strong>in</strong> range(dot_N)]<br>a <strong>=</strong> np.random.rand(DIMS,DIMS)<br>b <strong>=</strong> np.random.rand(DIMS,DIMS)<br>res <strong>=</strong> np.dot(a,b)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*csolZSs4KkBDi9LiJmqBwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*wM9jWGDHqr-3Uubr0Q_JHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*9HMrG96_Rlvcv9xfa0knlQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*leIaECSVuNe-7vYfyS6wyg.png" /></figure><h4>CPU Intensive</h4><p>When we meet CPU-intensive cases, let several processors run simultaneously will improve your speed. Even you need to create many processes. Multiprocessing is still better than multithreading. Of course, this is base on the fact that the memory capacity of your current computing environment is not significant.</p><pre>n = 10**7<br>ITERS = 10</pre><pre>count <strong>=</strong> 0<br><strong>for</strong> i <strong>in</strong> range(n):<br>    count <strong>+=</strong> i</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*YAqBGelZeyfgo6C2btIqvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*-6dzSEYqmIFPnKVNtLzLgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*IusVRGtedyl3gq9f72HiLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*kdr-sKaVpt-hoO79pPGjdg.png" /></figure><h3>Conclusions</h3><p>Sometimes you can’t easily define what type of your case is. So maybe you can quickly run a sample and find out which parallel processing way is better. I hope you guys can benefit from this article.</p><p>In the end, I want to recommend an <a href="http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html">article</a>. It uses good diagrams to tell readers how multithreading and multiprocessing work. And the complete code will be in my <a href="https://github.com/EricTsai83/parallel_processing">Github</a>. Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41e529f2da6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create an Interactive Report By Using Plotly]]></title>
            <link>https://medium.com/geekculture/create-an-interactive-report-by-using-plotly-981a513fdec4?source=rss-d5f83f0bd9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/981a513fdec4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[interactive-report]]></category>
            <dc:creator><![CDATA[Eric Tsai]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 13:48:23 GMT</pubDate>
            <atom:updated>2021-09-21T09:21:11.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pi3CCpvhmgmOOCet" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Create an Offline Interactive Report By Using Plotly</h3><h4>If your company doesn’t want to develop a dashboard but needs you to monitor complex data for a long time. Maybe this is a way to help you.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*9Utr4D6ZXq9hXzE9nDHkYA.gif" /><figcaption>Fig1 Offline Interactive Report</figcaption></figure><h3>Why using Plotly to draw a graph?</h3><p>There are many other tools out there that can create an interactive graph. However, I won’t debate which tool is better in this article. If someone interesting in it, you can check the <a href="https://towardsdatascience.com/the-sweet-spot-of-plotly-c6e1342e3544">link</a>.</p><h3>The advantages of offline interactive reports</h3><ul><li>A creation process can be fully automatic because interactive UI will let you easily compare each item by different conditions.</li><li>Offline interactive report no needs to launch a server, but the dashboard does. It is perfect for those who used to receive information by email.</li><li>Plotly&#39;s interactive features are helpful, such as a download button, hidden line, and zoom graph.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*hUk2BJ_gPijsIcY7VVZGHA.gif" /><figcaption>Fig2 Download</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*KMpIpf5QGki-CmWkzL38Fg.gif" /><figcaption>Fig3 Zoom Graph</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*qpt6Y3n4PnhN5ZKyuthpvQ.gif" /><figcaption>Fig4 Hidden Line</figcaption></figure><h3>Simple tutorial for creating an interactive report</h3><p>First, I generate some fake data for this article. The code is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8adee778a54bd966ae8102997aa9a373/href">https://medium.com/media/8adee778a54bd966ae8102997aa9a373/href</a></iframe><figure><img alt="weblog dataset: 2000 rows × 4 columns" src="https://cdn-images-1.medium.com/max/424/1*HXx1zSSiwNqhGALInqhsHw.png" /><figcaption>weblog dataset: 2000 rows × 4 columns / keyword(search term): 520 rows × 1 columns</figcaption></figure><p>Second, open the other script to import your package and load the dataset you generated before.</p><pre># plotly<br>import plotly.graph_objects as go<br>import plotly<br>from plotly.subplots import make_subplots<br># basic package<br>import pandas as pd<br>import glob<br>import config<br>import numpy as np<br>import re<br>from datetime import date<br>import os<br>import pickle<br># wordcloud<br>from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator<br># plot<br>import matplotlib.pyplot as plt<br>from matplotlib.font_manager import FontProperties<br>import base64<br>from io import BytesIO<br>from os import path<br>from PIL import Image<br># from pivottablejs import pivot_ui<br>from IPython.display import IFrame<br>import json, io<br># html<br>from IPython.display import HTML</pre><pre>df = pd.read_pickle(‘../Data/web_lod_data.pkl’)<br>df.head()</pre><p>After doing this, you can start to think about what graph or table you want to display. I will give you two examples below.</p><p><strong>Case 1: compare the usage of different web browsing devices by counting the number of actions</strong></p><p>Our dataset has two websites, so we need to create a button that can switch to each other.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59b1367403c8904adcbe0f45262669bf/href">https://medium.com/media/59b1367403c8904adcbe0f45262669bf/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkAodFvfp6aW9cbsSYPPaQ.gif" /><figcaption>Fig5 Number of Actions</figcaption></figure><p><strong>Case 2: create an interactive table to display the number of search term occurrences</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ca9adbbed41756d6ce7208ed9b77253/href">https://medium.com/media/7ca9adbbed41756d6ce7208ed9b77253/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*UWQbMEmW8D9kzMAuPjUrNg.gif" /><figcaption>Fig6 Interactive Table</figcaption></figure><p>Finally, open the new script and following the code below, and then you can embed the HTML files we created before to the basic HTML template quickly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d34c78165db3e877c9e5f2c3a8ef18c1/href">https://medium.com/media/d34c78165db3e877c9e5f2c3a8ef18c1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*1kw4eNHaAALKYut_s0u6nw.gif" /></figure><h3>Conclusion</h3><p>I think most of the time online dashboard is the better solution for interactive reports. But sometimes, it is probably not an optimal solution for your company. For example, If you are the only one who needs to monitor the data, creating an online dashboard is wasteful. The other case is your boss or supervisors are not used to explore data insight on the dashboard. Offline interactive reports may be a good option for you. It can add your view or commend inside the report readily.</p><p>My final thought is finding a suitable way to show your analysis result is an important thing you need to keep in mind. Otherwise, your suggestions or efforts may be difficult to be seen. Especially if you are a data scientist, your boss or supervisor may not have an engineering or data analysis background. The complete code is on my <a href="https://github.com/EricTsai83/offline_interactive_report">GitHub</a>. Thanks for your time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=981a513fdec4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/create-an-interactive-report-by-using-plotly-981a513fdec4">Create an Interactive Report By Using Plotly</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis With NLP Project]]></title>
            <link>https://erictsai492718.medium.com/exploratory-data-analysis-with-nlp-project-6f8c31aae2f1?source=rss-d5f83f0bd9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f8c31aae2f1</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Eric Tsai]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 18:25:36 GMT</pubDate>
            <atom:updated>2021-09-21T09:33:49.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PjF6ZmPQ0ygYCLte" /><figcaption>Photo by <a href="https://unsplash.com/@sincerelymedia?utm_source=medium&amp;utm_medium=referral">Sincerely Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>“I hope this article can help someone who interesting in natural language processing (NLP).”</h4><p>I use data provided by the <a href="https://www.kaggle.com/c/home-depot-product-search-relevance"><strong>Home Depot Product Search Relevance</strong></a><strong> </strong>competition on Kaggle.</p><h3>1. import libraries and load data</h3><pre><em># basic libraries<br>import pandas as pd<br>import numpy as np</em></pre><pre><em># help data frame can show side by side <br>from IPython.display import display,HTML</em></pre><pre><em># statistic libraries<br>import seaborn as sns<br>from scipy import stats</em></pre><pre><em># plot<br>import matplotlib.pyplot as plt</em></pre><pre><em># loop step<br>from tqdm import tqdm</em></pre><pre># load data<br>df_train = pd.read_csv(&#39;../Data/train.csv&#39;, encoding=&quot;ISO-8859-1&quot;)<br>df_test = pd.read_csv(&#39;../Data/test.csv&#39;, encoding=&quot;ISO-8859-1&quot;)<br>df_attributes = pd.read_csv(&#39;../Data/attributes.csv&#39;)<br>df_product_descriptions = pd.read_csv(&#39;../Data/product_descriptions.csv&#39;)</pre><h3>2. Exploratory Data Analysis</h3><h4>To-Do List:</h4><ul><li>Generate data frame table. It will let you know more specifically what the data looks like. Code is showing below:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20e497e43bf49d33deaebdb6fd5a1344/href">https://medium.com/media/20e497e43bf49d33deaebdb6fd5a1344/href</a></iframe><pre>grid_df_display(<br>    list_df = [df_train, df_attributes, df_test,               <br>               df_product_descriptions], <br>    list_df_name = [‘Traing Data’, ‘Attributes’, ‘Test Data’,      <br>                    ‘Product Descriptions’],<br>    list_number_of_data = [5, 28, 6, 5], <br>    row = 2, col = 2, fill = ‘col’<br>)</pre><figure><img alt="This data set contains a number of products and real customer search terms from Home Depot’s website." src="https://cdn-images-1.medium.com/max/1024/1*AudDZvvOt8qiLLKr4P6TFQ.png" /><figcaption>This data set contains several products and customer search terms from Home Depot’s website.</figcaption></figure><ul><li>Check the shape of the data. It will let you know more precisely how big the data it is.</li><li>Checking missing values in each column and confirm that the missing values are redundant or not. Sometimes, missing values have some critical information. For example, if some products’ waterproof attribution is ‘yes’, the other was `null` or even doesn’t have the attribution. It probably means these products don’t have any water-resistant ability.</li><li>Check the column type and covert feature to the right type.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*oW3I8qPoXPFxg2Kzqg451A.png" /><figcaption>In this case, we must convert the <strong>id</strong> and <strong>product_uid’s </strong>column<strong> </strong>type to object.</figcaption></figure><ul><li>Checking duplicates<em> </em>by row and confirm that duplicates<em> </em>are redundant or not.</li></ul><blockquote><em>Note: sometimes duplicates are not redundant. In some cases, we even add duplicate data through the </em><a href="https://en.wikipedia.org/wiki/Resampling_(statistics)"><em>resampling</em></a><em> method.</em></blockquote><ul><li>To understand the basic patterns of data through descriptive statistics.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*-z-00na5h_nk6Bv09DDSJQ.png" /><figcaption>Image displays the training data descriptive statistics index</figcaption></figure><ul><li>Checking distribution for the target and important features. We usually use the normal distribution as a benchmark for comparison. If the data is the normal distribution, the <a href="https://en.wikipedia.org/wiki/P%E2%80%93P_plot">probability plot</a> will show that two 45-degree lines overlap.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*VoT1Y16dzc1uPglIkertDQ.png" /><figcaption>The image shows the pattern of the target variable.</figcaption></figure><ul><li>Find out product attributes that have a lot of frequency from the attribute data set.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*w3xKB6LQOzKo48BQN-OYCA.png" /></figure><p><em>By looking at the table on the left, we can see that product attributes such as ‘MFG Brand Name’, ‘Color Family’, ‘Material’, ‘Color/Finish’, and ‘Certifications and Listings’ have a large frequency. I think these attributes are meaningful to website users.</em></p><p><em>So, we got the idea to extract critical information from each product. It helps us to predict the relevance between the search term and products on the website.</em></p><h3>Conclusions</h3><p>This article is my first try. I hope you guys can find something you need. And I will do my best to improve my writing skill and English. The whole analysis process will be put on my <a href="https://github.com/EricTsai83/Home_Depot_Product_Search_Relevance/blob/main/EDA/EDA.ipynb">Github</a>. Next time I will more dig into NLP-related skills. Thanks a lot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f8c31aae2f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>