開始使用免費開始

受限 Levenshtein

你注意到 stringdist 套件也實作了 Levenshtein 距離的一種變形,稱為 Restricted Damerau-Levenshtein 距離,想要試試看。你會依照課程中的邏輯,把它包成自訂函式,並在訓練區域離群因子(Local Outlier Factor)異常偵測器之前,先預先計算距離矩陣。你會用 accuracy_score()(已以 accuracy() 提供)來衡量效能。你也可以使用 stringdistnumpy(以 np 匯入)、scipy.spatial.distance 中的 pdist()squareform(),以及 LocalOutlierFactor(以 lof 匯入)。資料已預先載入為 pandas DataFrame,包含 labelsequence 兩個欄位,並有兩個類別:IMMUNE SYSTEMVIRUS

本練習屬於課程

在 Python 設計機器學習工作流程

檢視課程

練習說明

  • 撰寫一個函式,輸入為 uv,每個都是只含一個字串的陣列,對這兩個字串套用 rdlevenshtein() 函式。
  • 先把 proteinssequence 欄位轉為 numpy 陣列,接著使用 .reshape() 重新塑形。
  • 使用 my_rdlevenshtein()sequences 計算平方距離矩陣,並在其上訓練 lof
  • predsproteins['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(____, ____))
編輯並執行程式碼