受限 Levenshtein
你注意到 stringdist 套件也實作了 Levenshtein 距離的一種變形,稱為 Restricted Damerau-Levenshtein 距離,想要試試看。你會依照課程中的邏輯,把它包成自訂函式,並在訓練區域離群因子(Local Outlier Factor)異常偵測器之前,先預先計算距離矩陣。你會用 accuracy_score()(已以 accuracy() 提供)來衡量效能。你也可以使用 stringdist、numpy(以 np 匯入)、scipy.spatial.distance 中的 pdist() 與 squareform(),以及 LocalOutlierFactor(以 lof 匯入)。資料已預先載入為 pandas DataFrame,包含 label 與 sequence 兩個欄位,並有兩個類別:IMMUNE SYSTEM 與 VIRUS。
本練習屬於課程
在 Python 設計機器學習工作流程
練習說明
- 撰寫一個函式,輸入為
u與v,每個都是只含一個字串的陣列,對這兩個字串套用rdlevenshtein()函式。 - 先把
proteins的sequence欄位轉為numpy陣列,接著使用.reshape()重新塑形。 - 使用
my_rdlevenshtein()為sequences計算平方距離矩陣,並在其上訓練lof。 - 將
preds與proteins['label']轉為布林值(表示某蛋白是否為病毒),以此計算 accuracy。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Wrap the RD-Levenshtein metric in a custom function
def my_rdlevenshtein(u, v):
return ____.rdlevenshtein(____, ____)
# Reshape the array into a numpy matrix
sequences = ____(proteins['seq']).____(-1, 1)
# Compute the pairwise distance matrix in square form
M = ____
# Run a LoF algorithm on the precomputed distance matrix
preds = lof(metric=____).____(M)
# Compute the accuracy of the outlier predictions
print(accuracy(____, ____))