开始使用免费开始使用

整合应用

除了上一个练习中构建的基于距离学习的异常检测流程,您还希望加入基于特征学习的单类 SVM 方法。您决定提取两个特征:其一是字符串长度,其二是字符串首字母的数值编码,该编码通过第 1 章介绍的 LabelEncoder() 获得。为确保公平对比,您将把离群分数用于计算 AUC。以下对象已导入:LabelEncoder()roc_auc_score() 并重命名为 auc(),以及 OneClassSVM。数据以 pandas 的数据框 proteins 提供,包含两列 labelseq,有两个类别:IMMUNE SYSTEMVIRUS。一个已训练好的 LoF 检测器以 lof_detector 提供。

本练习是课程的一部分

用 Python 设计机器学习工作流

查看课程

练习说明

  • 对于字符串 slen(s) 返回其长度。将其应用到 seq 列以生成新列 len
  • 对于字符串 slist(s) 返回其字符列表。用它提取每个序列的首字母,并使用 LabelEncoder() 进行编码。
  • LoF 分数位于属性 negative_outlier_factor_ 中。计算其 AUC。
  • 在仅包含 lenfirst 两列的数据框上拟合 1-类 SVM。提取分数,并使用 AUC 评估 LoF 分数和 SVM 分数。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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))
编辑并运行代码