開始使用免費開始

整合所有步驟

除了你在上一個練習建立的以距離為基礎的異常偵測流程外,你也想加入以特徵為基礎、使用 one-class SVM 的做法。你決定萃取兩個特徵:第一是字串長度,第二是字串第一個字母的數值編碼,後者可使用第 1 章介紹的 LabelEncoder() 來取得。為了公平比較,你會把離群分數輸入 AUC 計算。下列物件已匯入:LabelEncoder()、將 roc_auc_score() 命名為 auc(),以及 OneClassSVM。資料已存在名為 proteinspandas 資料框,包含兩個欄位 labelseq,以及兩個類別「IMMUNE SYSTEM」與「VIRUS」。已訓練好的 LoF 偵測器可用 lof_detector 取得。

本練習屬於課程

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

檢視課程

練習說明

  • 對於字串 slen(s) 會回傳其長度。把它套用到 seq 欄位以建立新欄位 len
  • 對於字串 slist(s) 會回傳其字元清單。用這個方法擷取每個序列的第一個字母,並以 LabelEncoder() 進行編碼。
  • LoF 分數位於屬性 negative_outlier_factor_。計算其 AUC。
  • 以只包含 lenfirst 兩欄的資料框來訓練 1-class SVM。取出分數,並用 AUC 評估 LoF 分數與 SVM 分數。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create a feature that contains the length of the string
proteins['len'] = proteins['seq'].apply(____)

# Create a feature encoding the first letter of the string
proteins['first'] =  ____.____(
  proteins['seq'].apply(____))

# Extract scores from the fitted LoF object, compute its AUC
scores_lof = lof_detector.____
print(____(proteins['label']==____, scores_lof))

# Fit a 1-class SVM, extract its scores, and compute its AUC
svm = ____.____(proteins[['len', 'first']])
scores_svm = svm.____(proteins[['len', 'first']])
print(____(proteins['label']==____, scores_svm))
編輯並執行程式碼