始める無料で始める

制限付きレーベンシュタイン

stringdist パッケージには、レーベンシュタイン距離の変種である Restricted Damerau-Levenshtein 距離の実装もあり、これを試してみます。レッスンの流れに沿って、これをカスタム関数に包み、学習前に距離行列を前計算してから、局所外れ値因子による異常検知器を学習します。評価には accuracy_score()accuracy() として利用可能)を使います。利用できるパッケージは stringdistnumpy(別名 np)、scipy.spatial.distancepdist()squareform()、そして LocalOutlierFactorlof として利用)です。データは labelsequence の2列を持つ pandas のデータフレームとして事前に読み込まれており、クラスは IMMUNE SYSTEMVIRUS の2種類です。

この演習はコースの一部です

Python で設計する Machine Learning ワークフロー

コースを見る

演習の手順

  • 入力 uv を受け取る関数を書きます。どちらも文字列を1つ含む配列であり、2つの文字列に対して rdlevenshtein() を適用します。
  • proteinssequence 列を、まず numpy 配列にキャストしてから .reshape() を使って再整形します。
  • my_rdlevenshtein() を用いて sequences の正方距離行列を計算し、lof に学習させます。
  • predsproteins['label'] を、それぞれタンパク質がウイルスかどうかを示す真偽値に変換してから精度を計算します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# 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(____, ____))
コードを編集して実行