-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTF_IDF_movie_rec.py
123 lines (92 loc) · 3.41 KB
/
TF_IDF_movie_rec.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# -*- coding: utf-8 -*-
"""Untitled0.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1yOA0AYjwrRvH37A8YmBkUdw2hQUgUhhg
"""
!pip install konlpy
import pandas as pd
import re
import numpy as np
# 토큰화를 위한 모듈
from konlpy.tag import Okt
# 빈도수 딕셔너리를 만들기 위한 모듈
from collections import Counter
okt=Okt()
data = pd.read_csv('/content/drive/My Drive/자연어처리/movie.csv')
print(data.columns)
print(data.loc[:,['story']])
movies = data.loc[:,['title','story']]
print(pd.DataFrame(movies))
movies['keyword'] = movies['story']
for i in range(len(data.story)-1):
movies['keyword'][i] = re.sub(r'[^가-힣0-9a-zA-Z\s]','', str(movies['story'][i]))
print(pd.DataFrame(movies))
movies
token_ls = []
STOP_WORDS = ['의','가','이','은','들','는','좀','잘','걍','과','도','를','으로','자','에','와','한','하다',',',"'",'\r']
for i in range(len(movies)):
token_ls = []
for j in okt.morphs(movies['keyword'][i], stem=True):
if j not in STOP_WORDS:
token_ls.append(j)
movies['story'][i] = token_ls
print(movies.story)
movies['re_story'] = movies['story']
movies
for i in range(len(movies)):
movies['re_story'][i]
str1 = ''
for ele in movies['re_story'][i]:
str1 += ele+' '
movies['re_story'][i] = str1
# def listToString(s,i):
# # initialize an empty string
# str1 = ""
# # traverse in the string
# for ele in s:
# str1 += ele+' '
# # return string
# return srt1
movies
movie = movies.loc[:,['title','re_story']]
print(movie)
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer()
tfidf_matrix = tfidf.fit_transform(movie.re_story)
# 줄거리에 대해서 tf-idf 수행
print(tfidf_matrix.shape)
# from sklearn.feature_extraction.text import TfidfVectorizer
# tfidf = TfidfVectorizer(stop_words='english')
# movie = movie['re_story'].fillna('')
"""코사인 유사도 구하기"""
from sklearn.metrics.pairwise import linear_kernel
cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)
cosine_sim
indices = pd.Series(movie.index, index=movie.title).drop_duplicates()
print(indices)
indices['그린 북']
def movie_REC(title, cosine_sim=cosine_sim):
#입력한 영화로 부터 인덱스 가져오기
idx = indices[title]
print(idx)
# 모든 영화에 대해서 해당 영화와의 유사도를 구하기
sim_scores = list(enumerate(cosine_sim[idx]))
print(sim_scores)
# 유사도에 따라 영화들을 정렬
sim_scores = sorted(sim_scores, key=lambda x:x[1], reverse = True)
print(sim_scores)
# 가장 유사한 10개의 영화를 받아옴
sim_scores = sim_scores[1:11]
print(sim_scores)
# 가장 유사한 10개 영화의 인덱스 받아옴
movie_indices = [i[0] for i in sim_scores]
print(movie_indices)
#기존에 읽어들인 데이터에서 해당 인덱스의 값들을 가져온다. 그리고 스코어 열을 추가하여 코사인 유사도도 확인할 수 있게 한다.
result_df = movie.iloc[movie_indices].copy()
result_df['score'] = [i[1] for i in sim_scores]
# 읽어들인 데이터에서 줄거리 부분만 제거, 제목과 스코어만 보이게 함
del result_df['re_story']
# 가장 유사한 10개의 영화의 제목을 리턴
return result_df
movie_REC('아이언맨')