基于剧情构建推荐器

Python 中的 NLP 特征工程

Rounak Banik

Data Scientist

电影推荐器

标题 概要
上海叛徒 1930 年代,一名与上海黑帮有关的乡下男孩被叔叔带到大城市,做帮主情妇的仆人。
呼喊吧,挚爱的祖国 一位南非牧师前往大城市寻找误入歧途并犯罪的儿子。
Python 中的 NLP 特征工程

电影推荐器

get_recommendations("The Godfather")
1178               The Godfather: Part II
44030    The Godfather Trilogy: 1972-1990
1914              The Godfather: Part III
23126                          Blood Ties
11297                    Household Saints
34717                   Start Liquidation
10821                            Election
38030                          Goodfellas
17729                   Short Sharp Shock
26293                  Beck 28 - Familjen
Name: title, dtype: object
Python 中的 NLP 特征工程

步骤

  1. 文本预处理
  2. 生成 tf-idf 向量
  3. 生成余弦相似度矩阵
Python 中的 NLP 特征工程

推荐函数

  1. 接收电影标题、余弦相似度矩阵和索引序列作为参数。
  2. 提取该电影的成对余弦相似度分数。
  3. 按分数降序排序。
  4. 输出最高分对应的标题。
  5. 忽略最高分(为 1)。
Python 中的 NLP 特征工程

生成 tf-idf 向量

# Import TfidfVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer

# Create TfidfVectorizer object
vectorizer = TfidfVectorizer()

# Generate matrix of tf-idf vectors
tfidf_matrix = vectorizer.fit_transform(movie_plots)
Python 中的 NLP 特征工程

生成余弦相似度矩阵

# Import cosine_similarity
from sklearn.metrics.pairwise import cosine_similarity

# Generate cosine similarity matrix
cosine_sim = cosine_similarity(tfidf_matrix, tfidf_matrix)
array([[1.        , 0.27435345, 0.23092036, ..., 0.        , 0.        ,
        0.00758112],
       [0.27435345, 1.        , 0.1246955 , ..., 0.        , 0.        ,
        0.00740494],
       ...,
       [0.00758112, 0.00740494, 0.        , ..., 0.        , 0.        ,
        1.        ]])
Python 中的 NLP 特征工程

linear_kernel 函数

  • tf-idf 向量的模为 1。
  • 两个 tf-idf 向量的余弦分数即它们的点积。
  • 可显著加快计算。
  • 使用 linear_kernel 替代 cosine_similarity
Python 中的 NLP 特征工程

生成余弦相似度矩阵

# Import cosine_similarity
from sklearn.metrics.pairwise import linear_kernel

# Generate cosine similarity matrix
cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)
array([[1.        , 0.27435345, 0.23092036, ..., 0.        , 0.        ,
        0.00758112],
       [0.27435345, 1.        , 0.1246955 , ..., 0.        , 0.        ,
        0.00740494],
       ...,
       [0.00758112, 0.00740494, 0.        , ..., 0.        , 0.        ,
        1.        ]])
Python 中的 NLP 特征工程

get_recommendations 函数

get_recommendations('The Lion King', cosine_sim, indices)
7782                      African Cats
5877    The Lion King 2: Simba's Pride
4524                         Born Free
2719                          The Bear
4770     Once Upon a Time in China III
7070                        Crows Zero
739                   The Wizard of Oz
8926                   The Jungle Book
1749                 Shadow of a Doubt
7993                      October Baby
Name: title, dtype: object
Python 中的 NLP 特征工程

Passons à la pratique !

Python 中的 NLP 特征工程

Preparing Video For Download...