开始使用免费开始使用

探索文本向量,第 1 部分

让我们在刚学到的文本向量探索方法上继续深入,使用 volunteer 数据集的 title tf/idf 向量。在这一部分中,我们将基于幻灯片里的那个函数进行扩展。我们会让该函数返回一个数字列表。在下一个练习中,您将编写另一个函数,用于汇总所有文档中的高频词,提取出来,然后用这份列表来筛选 text_tfidf 向量。

本练习是课程的一部分

Python 中的机器学习预处理

查看课程

练习说明

  • 添加名为 original_vocabtop_n 的参数,其中 original_vocab 对应 tfidf_vec.vocabulary_
  • 对打包后的字典调用 pd.Series(),这样更便于后续操作。
  • 使用 .sort_values() 对 Series 排序,并将索引切片到前 top_n 个词。
  • 调用该函数,设置 original_vocab=tfidf_vec.vocabulary_,设置 vector_index=8(获取第 9 行),并设置 top_n=3(获取权重最高的 3 个词)。

交互式实操练习

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

# Add in the rest of the arguments
def return_weights(vocab, ____, vector, vector_index, ____):
    zipped = dict(zip(vector[vector_index].indices, vector[vector_index].data))
    
    # Transform that zipped dict into a series
    zipped_series = ____({vocab[i]:zipped[i] for i in vector[vector_index].indices})
    
    # Sort the series to pull out the top n weighted words
    zipped_index = zipped_series.____(ascending=False)[:____].index
    return [original_vocab[i] for i in zipped_index]

# Print out the weighted words
print(return_weights(vocab, ____, text_tfidf, ____, ____))
编辑并运行代码