开始使用免费开始使用

受限 Levenshtein

您注意到 stringdist 包还实现了 Levenshtein 距离的一种变体,称为受限 Damerau-Levenshtein 距离,想要试一试。您将沿用课程中的思路,把它封装进一个自定义函数,并在拟合局部异常因子检测器之前预计算距离矩阵。您将使用 accuracy_score() 来评估性能,它已以 accuracy() 提供。您还可以使用以下包与对象:stringdistnumpy(简称 np)、scipy.spatial.distance 中的 pdist()squareform(),以及 LocalOutlierFactor(简称 lof)。数据已作为 pandas 的 dataframe 预加载,包含两列 labelsequence,且有两个类别:IMMUNE SYSTEMVIRUS

本练习是课程的一部分

用 Python 设计机器学习工作流

查看课程

练习说明

  • 编写一个以 uv 为输入的函数,它们各自是包含一个字符串的数组,对这两个字符串应用 rdlevenshtein()
  • proteins 中的 sequence 列先转换为 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(____, ____))
编辑并运行代码