Python context manager

內文管理器 python with 語句,能讓我們更輕易的實行資源管理,例如數據、開啟文件,或是各種會lock的行為。 要保證處理完相關事情,資源有被釋放。 簡單行為中,我們會這樣去開啟文件 test_file = open('test.txt', 'w') try: test_file.write('line one') finally: test_file.close() 上述行為除了是非慣用以外, 若try-finally裡面邏輯複雜,還面臨著維護的困難。 這裡有著使用 with 的簡單用法 with open('test.txt', 'w') as test_file: test_file.write('line one') 上述程式碼中,當 with 內的語句執行結束後,會自動關閉該資源,且變數test_file也會結束。 實現context manager 若想實現 context manager的功能,則要定義好__enter__ 與 __exit__ 兩個函式,分別管理with的進入行為和結束行為。

2020-04-14 · 1 min read · 38 words · KbWen · ZH

Python Iterable

要了解python 哪些對象是可以迭代的, 可以先了解兩個相似的名詞 Iterable Iterator Iterable 可以被迭代、遍歷(loop, iteration)的物件對象可以被稱為iterable, 從官方文件得知,要實現__iter__或是__getitem__的方法即可。 包含了常見的list、tuple、set、dict、str、range, >>> dir(str()) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', ......] 但若是使用collection去檢查是否是iterable 只有實現__getitem__的對象可以被迭代但不會是iterable Iterator https://docs.python.org/3.7/c-api/iter.html 從官方文件看出,含有__iter__和__next__的對象可稱為iterator, iterator是iterable的子集合, 上述提到的幾種方式是iterable但都不是iterator,可以使用上面用到的isinstance或是dir來確認, >>> from collections.abc import Iterable, Iterator >>> for i in ([1,2,3], "123", (1,2,3)): ... print(f"{i} is iterable: {isinstance(i, Iterable)}") ... print(f"{i} is iterator: {isinstance(i, Iterator)}") ... [1, 2, 3] is iterable: True [1, 2, 3] is iterator: False 123 is iterable: True 123 is iterator: False (1, 2, 3) is iterable: True (1, 2, 3) is iterator: False 而文件則是iterator >>> file_path = os.path.abspath("test.py") >>> with open(file_path) as ifile: ... isinstance(ifile, Iterator) ... True 結語 了解了iterable和iterator,以後開發時, 若想創造出可以被迭代的對象或是迭代器, 則要知道必須要包含哪些基礎功能 那麼Generator呢?

2020-04-11 · 1 min read · 115 words · KbWen · ZH

python pdb

pdb — The Python Debugger 一段簡單的程式碼 print(f'file = {__file__}') 常見pdb幾種使用方式 1. 直接使用 python -m pdb file.py 執行上面指令會讓整個檔案進入pdb模式操作 > /home/src/test.py(1)<module>() -> file = __file__ (Pdb) 2. 設斷點 把上面程式碼改成 file = __file__ import pdb; pdb.set_trace() print(f'file = {file}') 執行後則會在第二行進入pdb > /home/src/test.py(3)<module>() -> print(f'file = {file}') (Pdb) 結果如同上方,此時進入操作。 在python3.7之後版本,可以使用 breakpoint() 指令 詳見pep553 file = __file__ breakpoint() print(f'file = {file}') 3. python shell 中使用 如果使用中遇到一些function的錯誤,可以這樣使用 創造一個測試function: def test(): a = 1 b = 'b' return a + b 這個function會出現錯誤:數字和字串的操作 再進入python >>> from test import test >>> import pdb >>> test() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/src/test.py", line 4, in test return a + b TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> pdb.pm() > /home/src/test.py(4)test() -> return a + b (Pdb) 一樣也會進入pdb操作 ...

2020-04-10 · 1 min read · 133 words · KbWen · ZH

OPENCV 人臉辨識

人臉檢測 (Face Detection) 通常是人臉辨識流程的前置處理。這裡我們利用 Haar 特徵 來進行實作。 在訓練過程中,該演算法使用 AdaBoost,即利用多個「弱分類器」級聯 (Cascade) 來判別。每一步都會提取一個特徵值來判斷是否為人臉: 如果判斷為「是」,則進入下一個層級的強分類器。 如果判斷為「否」,則直接排除該區域。 廣義來看,這就像是讓所有弱分類器進行投票,並根據各自的準確率加權集成。其組成的分類器架構稱為 Cascade,形式上類似於簡單的多層決策樹。 實際應用與調整 在實際使用中,Haar Cascade 的挑戰主要在於參數的調優,尤其是 scaleFactor 和 minNeighbors: scaleFactor:控制影像縮放的比例。數值調大時,檢測的層數會變少,速度快但容易漏掉較小的目標。 minNeighbors:決定一個目標區域被聲明為「人臉」前,周圍必須也被檢測到的人臉鄰居數量。 由於不同圖片的解析度與場景差異,往往需要手動調整參數才能達到最佳效果,這在自動化處理上較為困難。未來我會嘗試使用深度學習等更強健的方式。 參考來源:Face Recognition with Python 下圖是檢測人臉與眼睛的結果,圖片來源為 USA Volleyball National Team 合照: My Github

2017-07-12 · 1 min read · 37 words · KbWen · ZH

ML KNN

k-th nearest neighbor (k-NN) k-NN 是監督式學習 (Supervised learning) 的一種,名稱非常簡明扼要,就是尋找「K 個最相近的鄰居」。 這個演算法在實作時,會找到附近 K 個最近的點,根據鄰居的類別來判斷自己要歸在哪一類。雖然它是監督式學習,但其實並不需要訓練模型參數,而是將所有訓練資料儲存起來進行即時對比。 我們可以藉由調整 K 的數值來增加演算法的 Noise Margin。然而,此演算法存在著儲存空間需求大(空間複雜度高)的問題,且容易受到數據不平衡的影響。 在實作上,核心在於計算點與點之間的距離。我使用了 Scipy 的函數來實作,為了方便觀察,先取 K=1,並將結果與 sklearn 的 KNN 進行比較。 實作思路是利用 for 迴圈計算每個測試資料與所有訓練資料的距離,並取最近者的類別作為預測結果。 準確率比較: sklearn knn : 0.9733 手刻 knn : 0.9467 My Github

2017-06-30 · 1 min read · 40 words · KbWen · ZH

LSTM

原文網址:Understanding LSTMs 想像人在思考或閱讀文章時,並不是從零開始,而是會保留過去的記憶。RNN 就是為了解決這方面的問題而設計的。 每次訓練時,網路會保留過去的訊息並持續傳遞。而 LSTM 則是一種特殊的 RNN 形式。 The Problem of Long-Term Dependencies 在許多情況下,我們需要更多的上下文訊息,但這些關鍵資訊可能距離當前時間點非常遙遠。一般的 RNN 在處理這種長距離依賴時,容易產生梯度消失或梯度爆炸的問題。 LSTM LSTM 稱為「長短期記憶網絡」(Long Short Term Memory networks),是一種特殊的 RNN 架構。 不同於傳統 RNN 在每個 Cell 裡只包含一個 tanh 層,LSTM 增加了: input gate (輸入門) output gate (輸出門) forget gate (遺忘門) 這些閘門都是用來精準控制資料的操作。使用 sigmoid 激活函數可以看做是控制記憶與讀取資料量的多寡:0 代表不通過,1 代表全部通過。 詳細的數學推導可以參考原文。文中也介紹了 GRU——一種更為簡煉高效的 LSTM 變體。值得注意的是,現今我們從 RNN 領域獲得的優異成果,幾乎指的都是 LSTM 的應用。 在 TensorFlow 中,LSTM 已經封裝完善,呼叫即可使用。 下圖是用 LSTM (紅虛線) 去學習黑線 (x*sin(x)) 的擬合結果:

2017-06-29 · 1 min read · 66 words · KbWen · ZH

Kaggle PM2.5 Prediction

嘗試用 sklearn 進行分析。 使用豐原站的觀測記錄,將資料分為訓練集 (train set) 與測試集 (test set): train.csv:每個月前 20 天的所有觀測資料。 test_X.csv:從每個月剩下的 10 天中取樣。每筆資料包含連續 10 小時,以前九小時的所有觀測數據作為 Feature,預測第十小時的 PM2.5 濃度。一共取出 240 筆不重複的測試資料。 sklearn 在使用上非常直接。目前的策略是採用最基礎的方式:取出所有前九小時的值作為 Feature,不進行額外的特徵工程或化簡,直接觀察結果。 在 Private 排名約在中間,略高於 Baseline。 因為使用的是 Linear Regression,對 Gradient Descent 而言:計算一次斜率,直接就能找到解。 My Github

2017-06-13 · 1 min read · 37 words · KbWen · ZH

Kaggle Titanic

Kaggle The sinking of the RMS Titanic is one of the most infamous shipwrecks in history. On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. This sensational tragedy shocked the international community and led to better safety regulations for ships. One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class. ...

2017-06-09 · 2 min read · 224 words · KbWen · EN

TENSORFLOW 練習4: word2vec

把字詞轉成 word embedding 要在字詞中找到他們之間的某種關聯,而不只是分散無意義的符號代表。 做這個問題的核心概念是: 「假設兩個不同句子中的詞上下文相同,則代表兩個詞的語意相近。」 今天要來使用 skip-gram 模型,一個類似二元分類的方式 (判斷像或是不像)。一開始也同之前的問題,先做數據處理。 計算出現數量:[(most count word1, n1), (second word2, n2)] 文字轉成向量: 例如:The actual code for this tutorial is very short 生成的 skip-gram pairs 示意: ([the, code], actual), ([actual, for], code), … (actual, the), (actual, code), (code, actual), … 在這之間都會給他編號,轉化為 (10, 20), (10, 30), (30, 10), (30, 40) ... 的形式。 用到 nce_loss,目前我還不是非常熟練,概念上是讓目標詞的機率越高越好,並讓其餘 K 個負面樣本 (negative samples) 的機率降低。 經典案例: king - queen = man - woman ==> king - queen + woman = man ...

2017-05-12 · 1 min read · 95 words · KbWen · ZH

Tensorflow 練習3: 'FizzBuzz'

Joel Grus — FizzBuzz in TensorFlow 從網路上看到的幽默問題,算是一個很有趣的使用,適合在做完 Classification 後練習。 輸入資料處理和原版程式碼一樣,因為還蠻直觀的: 1 – 000000001 – [0 0 0 0 0 0 0 0 1] 2 – 000000010 – [0 0 0 0 0 0 0 1 0] ……… 輸出則是用 [1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1] 來代表四個分類。 輸入輸出都是一個矩陣的形式。利用兩層 hidden layer 分別是 512 和 256,激勵函數選擇 relu,剩下的就交給 tensorflow 分類。 結果 一開始一直分不出來,都會卡在把每個資料都判定成同一類 (0.533)。後來減低每次訓練丟進去的量就 OK 了 (忘記一開始做分類時也只丟一點點進去)。 ...

2017-05-08 · 1 min read · 89 words · KbWen · ZH