制限付きレーベンシュタイン
stringdist パッケージには、レーベンシュタイン距離の変種である Restricted Damerau-Levenshtein 距離の実装もあり、これを試してみます。レッスンの流れに沿って、これをカスタム関数に包み、学習前に距離行列を前計算してから、局所外れ値因子による異常検知器を学習します。評価には accuracy_score()(accuracy() として利用可能)を使います。利用できるパッケージは stringdist、numpy(別名 np)、scipy.spatial.distance の pdist() と squareform()、そして LocalOutlierFactor(lof として利用)です。データは label と sequence の2列を持つ pandas のデータフレームとして事前に読み込まれており、クラスは IMMUNE SYSTEM と VIRUS の2種類です。
この演習はコースの一部です
Python で設計する Machine Learning ワークフロー
演習の手順
- 入力
uとvを受け取る関数を書きます。どちらも文字列を1つ含む配列であり、2つの文字列に対してrdlevenshtein()を適用します。 proteinsのsequence列を、まずnumpy配列にキャストしてから.reshape()を使って再整形します。my_rdlevenshtein()を用いてsequencesの正方距離行列を計算し、lofに学習させます。predsとproteins['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(____, ____))