建立以劇情為基礎的推薦系統

Python 中文本特徵工程

Rounak Banik

Data Scientist

電影推薦器

片名 概要
Shanghai Triad 1930 年代,一名與上海黑幫有親戚關係的鄉下男孩,被叔叔帶到都會上海,成為幫派老大的情婦僕人。
Cry, the Beloved Country 一位南非牧師前往大城市,尋找犯下罪行而走偏的兒子。
Python 中文本特徵工程

電影推薦器

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 中文本特徵工程

步驟

  1. 文字前處理
  2. 產生 tf-idf 向量
  3. 建立 cosine 相似度矩陣
Python 中文本特徵工程

推薦函式

  1. 以電影片名、cosine 相似度矩陣與索引序列為引數。
  2. 取出該電影的成對 cosine 相似度分數。
  3. 將分數由高到低排序。
  4. 輸出分數最高者對應的片名。
  5. 忽略最高的相似度分數(1)。
Python 中文本特徵工程

產生 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 中文本特徵工程

建立 cosine 相似度矩陣

# 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 中文本特徵工程

`linear_kernel` 函式

  • tf-idf 向量的長度為 1
  • 兩個 tf-idf 向量的 cosine 分數等於它們的內積。
  • 可大幅縮短計算時間。
  • 使用 linear_kernel 取代 cosine_similarity
Python 中文本特徵工程

建立 cosine 相似度矩陣

# 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 中文本特徵工程

`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 中文本特徵工程

一起來練習吧!

Python 中文本特徵工程

Preparing Video For Download...