余弦相似度

R 自然语言处理入门

Kasey Jones

Research Data Scientist

TF-IDF 输出

# A tibble: 1,498 x 6
       X word         n     tf   idf tf_idf
   <int> <chr>    <int>  <dbl> <dbl>  <dbl>
 1    20 january      4 0.0930  2.30  0.214
 2    15 power        4 0.0690  3.00  0.207
 3    19 futures      9 0.0643  3.00  0.193
 4     8 8            6 0.0619  3.00  0.185
 5     3 canada       2 0.0526  3.00  0.158
 6     3 canadian     2 0.0526  3.00  0.158
R 自然语言处理入门

余弦相似度

  • 衡量两个向量的相似度
  • 通过两向量夹角度量

余弦相似度衡量两个向量的夹角。可将其想象为两条线形成的角。

1 https://en.wikipedia.org/wiki/Cosine_similarity
R 自然语言处理入门

余弦相似度公式

  • 相似度通过两向量的点积计算

计算两向量的点积可衡量它们的相似性。

R 自然语言处理入门

查找相似性(一)

crude_weights <- crude_tibble %>%
  unnest_tokens(output = "word", token = "words", input = text) %>%
  anti_join(stop_words) %>%
  count(word, X) %>%
  bind_tf_idf(word, X, n)
# A tibble: 1,498 x 6
       X word          n    tf   idf tf_idf
   <int> <chr>     <int> <dbl> <dbl>  <dbl>
 1     1 1.50          1 0.25   3.25  0.812
 2     1 16.00         1 1      3.25  3.25 
 3     1 barrel        2 0.133  3.25  0.433
 ...
R 自然语言处理入门

两两相似度

pairwise_similarity(tbl, item, feature, value, ...)
  • tbl:表或 tibble
  • item:要比较的项(文章、推文等)
  • feature:描述项之间关联的列(如词)
  • value:取值列(如 n 或 tf_idf)
R 自然语言处理入门

查找相似性(二)

crude_weights %>%
  pairwise_similarity(X, word, tf_idf) %>%
  arrange(desc(similarity))
# A tibble: 380 x 3
   item1 item2 similarity
   <int> <int>      <dbl>
 1    17    16      0.663
 2    16    17      0.663
 3    13    10      0.311
 4    10    13      0.311
 ...
R 自然语言处理入门

余弦相似度的用例

  • 查找重复/相似文本
  • 用于聚类与分类分析
R 自然语言处理入门

Passons à la pratique !

R 自然语言处理入门

Preparing Video For Download...