受限 Levenshtein
您注意到 stringdist 包还实现了 Levenshtein 距离的一种变体,称为受限 Damerau-Levenshtein 距离,想要试一试。您将沿用课程中的思路,把它封装进一个自定义函数,并在拟合局部异常因子检测器之前预计算距离矩阵。您将使用 accuracy_score() 来评估性能,它已以 accuracy() 提供。您还可以使用以下包与对象:stringdist、numpy(简称 np)、scipy.spatial.distance 中的 pdist() 与 squareform(),以及 LocalOutlierFactor(简称 lof)。数据已作为 pandas 的 dataframe 预加载,包含两列 label 和 sequence,且有两个类别:IMMUNE SYSTEM 与 VIRUS。
本练习是课程的一部分
用 Python 设计机器学习工作流
练习说明
- 编写一个以
u和v为输入的函数,它们各自是包含一个字符串的数组,对这两个字符串应用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(____, ____))