総仕上げ
前の演習で作成した距離ベース学習の異常検知パイプラインに加えて、1-class SVM を用いた特徴ベース学習もサポートしたいと考えています。ここでは 2 つの特徴量を抽出します。1 つ目は文字列の長さ、2 つ目は Chapter 1 で紹介した LabelEncoder() 関数を使って得る、文字列の先頭文字の数値エンコードです。公正に比較するため、外れ値スコアは AUC で評価します。すでに LabelEncoder()、roc_auc_score() を auc() として、そして OneClassSVM がインポートされています。データは proteins という pandas のデータフレームとして利用でき、label と seq の 2 列を持ち、クラスは IMMUNE SYSTEM と VIRUS の 2 種です。学習済みの LoF 検出器は lof_detector として利用可能です。
この演習はコースの一部です
Python で設計する Machine Learning ワークフロー
演習の手順
- 文字列
sに対してlen(s)はその長さを返します。これをseq列に適用して、新しい列lenを作成してください。 - 文字列
sに対してlist(s)は各文字のリストを返します。これを使って各配列の先頭文字を取り出し、LabelEncoder()を用いてエンコードしてください。 - LoF のスコアは
negative_outlier_factor_属性にあります。これらの AUC を計算してください。 - 列が
lenとfirstのみのデータフレームに対して 1-class SVM を学習し、スコアを抽出してください。LoF のスコアと SVM のスコアをいずれも AUC で評価します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# 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))