https://github.com/nalinzip/ml_study/blob/main/ML_lastweek.ipynb
이러한 데이터를 기반으로 추천 시스템은
최근접 이웃 협업 필터링은 메모리(Memory) 협업 필터링이라고도 하며,
일반적으로 사용자 기반과 아이템 기반으로 다시 나뉠 수 있음
사용자 기반 (User-User):
“당신과 비슷한 고객들이 다음 상품도 구매했습니다.”
(Customers like you also bought these items)
아이템 기반 (Item-Item):
“이 상품을 선택한 다른 고객들은 다음 상품도 구매했습니다.”
(Customers who bought this item also bought these items)
사용자 기반 최근접 이웃 방식은 특정 사용자와 유사한 다른 사용자를 TOP-N으로 선정해,
이 Top-N 사용자가 좋아하는 아이템을 추천하는 방식임
즉, 특정 사용자와 타 사용자 간의 유사도(Similarity)를 측정한 뒤,
가장 유사도가 높은 Top-N 사용자를 추출해 그들이 선호하는 아이템을 추천함
다음 그림은 사용자별 영화 평점 정보를 나타내고 있음

사용자 A는 주요 영화의 평점 정보가 사용자 C보다 사용자 B와 비슷하므로, 사용자 A와 사용자 B는 상호 간 유사도가 매우 높다고 할 수 있음
만약 사용자 A에게 아직 보지 못한 두 개의 영화인 ‘프로메테우스’와 ‘스타워즈 – 라스트 제다이’ 중 하나를 추천한다면, 사용자 C가 재미있게 본 ‘스타워즈 – 라스트 제다이’보다는, 사용자 A와 유사도가 높은 사용자 B가 재미있게 관람한 ‘프로메테우스’를 추천하는 것이 사용자 기반 최근접 이웃 협업 필터링임
아이템 기반 최근접 이웃 방식은 그 명칭이 주는 이미지 때문에 ‘아이템 간의 속성이 얼마나 비슷한지를 기반으로 추천한다’고 착각할 수 있음
하지만 아이템 기반 최근접 이웃 방식은 아이템이 가지는 속성과는 상관없이,
사용자들이 그 아이템을 좋아하는지 / 싫어하는지의 평가 척도가 유사한 아이템을 추천하는 기준이 되는 알고리즘임
위의 사용자 기반 최근접 이웃 데이터셋과 행과 열이 서로 반대입니다.
(행이 개별 아이템이고, 열이 개별 사용자)

아이템(영화) ‘다크 나이트’는 ‘스타워즈 – 라스트 제다이’보다 ‘프로메테우스’와 사용자들의 평점 분포가 훨씬더 비슷하므로, ‘다크 나이트’와 ‘프로메테우스’는 상호 간 아이템 유사도가 상대적으로 매우 높음
따라서 ‘다크 나이트’를 매우 좋아하는 사용자 D에게, 아이템 기반 협업 필터링은 D가 아직 관람하지 못한 ‘프로메테우스’와 ‘스타워즈 – 라스트 제다이’ 중 ‘프로메테우스’를 추천함
일반적으로 사용자 기반보다는 아이템 기반 협업 필터링이 정확도가 더 높음
이유는 비슷한 영화를 좋아하거나 상품을 구입했다고 해서 사람들의 취향이 반드시 비슷하다고 판단하기 어려운 경우가 많기 때문임
매우 유명한 영화는 취향과 관계없이 대부분의 사람이 관람하는 경우가 많고, 사용자들이 평점을 매긴 영화(또는 상품)의 개수가 많지 않은 경우가 일반적이며, 이를 기반으로 다른 사람과의 유사도를 비교하기가 어려운 부분도 있음
따라서 최근접 이웃 협업 필터링은 대부분 아이템 기반 알고리즘을 적용함

예: factor1 = 액션 선호도, factor2 = 로맨스 선호도
예: P(1, 1) = 0.94 (사용자 1의 액션 선호도), P(1, 2) = 0.96 (로맨스 선호도)
예: Q.T(1, 1) = 1.7 (영화 1의 액션 요소), Q.T(2, 1) = 2.49 (영화 2의 액션 요소)

평점은 사용자의 특정 장르 선호도와 영화의 그 장르적 특성을 반영하여 결정됨
예: 사용자가 액션 장르를 매우 좋아하고, 영화가 액션 특성이 크면 높은 평점을 줄 가능성이 높음
평점은 사용자 선호도 벡터(P)와 영화 특성 벡터(Q.T)의 내적 결과로 계산 가능
예: R(1, 1) = 4는 P 매트릭스의 User 1 벡터와 Q.T 매트릭스의 Item 1 벡터의 내적 결과
예: R(1, 2) = 2.56 (User 1의 벡터와 Item 2 벡터의 내적 결과)

여기서 Q는 아이템–잠재 요인 행렬 (N×K 차원), Q.T는 그 전치 행렬임

M: 총 사용자 수
N: 총 아이템 수
K: 잠재 요인의 차원 수
R (M×N): 사용자–아이템 평점 행렬
P (M×K): 사용자와 잠재 요인 간 관계 값을 담은 행렬
Q (N×K): 아이템과 잠재 요인 간 관계 값을 담은 행렬
Q.T (K×N): Q 행렬의 전치 행렬
예시: 많은 널(NaN) 값을 가지는 고차원의 희소 행렬 R은
→ 저차원의 밀집 행렬 P와 Q로 분해될 수 있음



사용자-아이템 평점 행렬의 미정 값을 포함한 모든 평점 값은 행렬 분해를 통해 얻어진 P 행렬과 Q.T 행렬의 내적을 통해 예측 평점으로 다시 계산할 수 있음

확률적 경사 하강법(SGD)은 경사 하강법의 일종으로, 5장 회귀의 3절에서 소개된 개념임
SGD를 활용한 행렬 분해는 예측 행렬(R̂)이 실제 행렬(R)과 최소한의 오류를 갖도록 비용 함수 최적화를 반복
절차:
P와 Q 행렬을 임의의 값으로 초기화
P와 Q.T의 곱으로 예측 R 행렬을 계산하고 오류 측정
이 오류를 최소화하기 위해 P와 Q 값을 반복적으로 업데이트
오류가 충분히 줄어들 때까지 2, 3단계를 반복


원본 행렬 R을 np.NaN 포함하여 생성
분해할 행렬 P, Q는 정규 분포 기반 랜덤 값으로 초기화
잠재 요인 차원 수 K는 3으로 설정
이후 반복 최적화를 통해 P와 Q를 학습하고, P @ Q.T로 예측 행렬 생성
import numpy as np
# 원본 행렬 R 생성, 분해 행렬 P와 Q 초기화, 잠재요인 차원 K는 3 설정.
R = np.array([[4, np.nan, np.nan, 2, np.nan ],
[np.nan, 5, np.nan, 3, 1 ],
[np.nan, np.nan, 3, 4, 4 ],
[5, 2, 1, 2, np.nan ]])
num_users, num_items = R.shape
K=3
# P와 Q 매트릭스의 크기를 지정하고 정규분포를 가진 random한 값으로 입력합니다.
np.random.seed(1)
P = np.random.normal(scale=1./K, size=(num_users, K))
Q = np.random.normal(scale=1./K, size=(num_items, K))
다음으로 실제 R 행렬과 예측 행렬의 오차를 구하는 get_rmse() 함수를 만들어보겠습니다.
from sklearn.metrics import mean_squared_error
def get_rmse(R, P, Q, non_zeros):
error = 0
# 두개의 분해된 행렬 P와 Q.T의 내적으로 예측 R 행렬 생성
full_pred_matrix = np.dot(P, Q.T)
# 실제 R 행렬에서 널이 아닌 값의 위치 인덱스 추출하여 실제 R 행렬과 예측 행렬의 RMSE 추출
x_non_zero_ind = [non_zero[0] for non_zero in non_zeros]
y_non_zero_ind = [non_zero[1] for non_zero in non_zeros]
R_non_zeros = R[x_non_zero_ind, y_non_zero_ind]
full_pred_matrix_non_zeros = full_pred_matrix[x_non_zero_ind, y_non_zero_ind]
mse = mean_squared_error(R_non_zeros, full_pred_matrix_non_zeros)
rmse = np.sqrt(mse)
return rmse
SGD 기반 행렬 분해 과정 요약:
업데이트 식:
사용자 벡터 pu 업데이트:
pu = pu + η (e_ui qi - λ * pu)
아이템 벡터 qi 업데이트:
qi = qi + η (e_ui pu - λ * qi)
오류 출력:
get_rmse() 함수를 사용
50회마다 RMSE(평균 제곱근 오차)를 출력해 학습 성능 확인
# R > 0 인 행 위치, 열 위치, 값을 non_zeros 리스트에 저장.
non_zeros = [ (i, j, R[i,j]) for i in range(num_users) for j in range(num_items) if R[i,j] > 0 ]
steps=1000
learning_rate=0.01
r_lambda=0.01
# SGD 기법으로 P와 Q 매트릭스를 계속 업데이트.
for step in range(steps):
for i, j, r in non_zeros:
# 실제 값과 예측 값의 차이인 오류 값 구함
eij = r - np.dot(P[i, :], Q[j, :].T)
# Regularization을 반영한 SGD 업데이트 공식 적용
P[i,:] = P[i,:] + learning_rate*(eij * Q[j, :] - r_lambda*P[i,:])
Q[j,:] = Q[j,:] + learning_rate*(eij * P[i, :] - r_lambda*Q[j,:])
rmse = get_rmse(R, P, Q, non_zeros)
if (step % 50) == 0 :
print("### iteration step : ", step," rmse : ", rmse)
이제 분해된 P와 Q 행렬을 P * Q.T로 곱하여 예측 행렬을 만들어서 출력
pred_matrix = np.dot(P, Q.T)
print('예측 행렬:\n', np.round(pred_matrix, 3))
SGD로 분해한 예측 행렬 결과:
활용 예고:
import pandas as pd
import numpy as np
import warnings; warnings.filterwarnings('ignore')
movies =pd.read_csv('/content/sample_data/tmdb_5000_movies.csv')
print(movies.shape)
movies.head(1)
주요 칼럼:
id
title (영화 제목)
genres (영화 장르)
vote_average (평균 평점)
vote_count (평점 투표 수)
popularity (인기도)
keywords (주요 키워드 문구)
overview (영화 개요 설명)
movies_df = movies[['id','title', 'genres', 'vote_average', 'vote_count',
'popularity', 'keywords', 'overview']]
pd.set_option('max_colwidth', 100)
movies_df[['genres','keywords']][:1]
from ast import literal_eval
movies_df['genres'] = movies_df['genres'].apply(literal_eval)
movies_df['keywords'] = movies_df['keywords'].apply(literal_eval)
movies_df['genres'] = movies_df['genres'].apply(lambda x : [ y['name'] for y in x])
movies_df['keywords'] = movies_df['keywords'].apply(lambda x : [ y['name'] for y in x])
movies_df[['genres', 'keywords']][:1]
콘텐츠 기반 필터링 구현 단계:
문자열로 변환된 genres 칼럼을 Count 기반으로 피처 벡터화 변환
genres 문자열을 피처 벡터화 행렬로 변환한 데이터셋을 코사인 유사도를 통해 비교
장르 유사도가 높은 영화 중에 평점이 높은 순으로 영화를 추천
리스트 객체 값으로 구성된 genres 칼럼에 apply(lambda x: (' ').join(x))를 적용해 개별 요소를 공백 문자로 구분하는 문자열로 변환해 별도의 칼럼인 genres_literal 칼럼으로 저장
리스트 객체 내의 개별 값을 연속된 문자열로 변환하려면 일반적으로 ('구분문자').join(리스트 객체)를 사용
from sklearn.feature_extraction.text import CountVectorizer
# CountVectorizer를 적용하기 위해 공백문자로 word 단위가 구분되는 문자열로 변환.
movies_df['genres_literal'] = movies_df['genres'].apply(lambda x : (' ').join(x))
count_vect = CountVectorizer(min_df=1, ngram_range=(1,2))
genre_mat = count_vect.fit_transform(movies_df['genres_literal'])
print(genre_mat.shape)
CountVectorizer를 적용하여 4,803개의 레코드와 276개의 개별 단어 피처로 구성된 피처 벡터 행렬을 생성
이 피처 벡터 행렬을 기반으로 사이킷런의 cosine_similarity() 함수를 사용해 코사인 유사도를 계산
cosine_similarity() 함수는 기준 행과 비교 행의 코사인 유사도를 계산하여 행렬 형태로 반환
이 함수는 각 영화 간 장르 기반 유사도를 수치화해 콘텐츠 기반 필터링 추천 시스템에서 핵심 역할 수행

피처 벡터화된 행렬에 cosine_similarity() 함수를 적용하여 모든 영화 간의 장르 유사도를 계산
이 함수는 4,803 x 4,803 크기의 코사인 유사도 행렬을 반환
반환된 행렬에서 앞 2개 데이터(예: 상위 2개 영화 간 유사도)만 추출하여 확인함
from sklearn.metrics.pairwise import cosine_similarity
genre_sim = cosine_similarity(genre_mat, genre_mat)
print(genre_sim.shape)
print(genre_sim[:2])
genre_sim_sorted_ind = genre_sim.argsort()[:, ::-1]
print(genre_sim_sorted_ind[:1])
def find_sim_movie(df, sorted_ind, title_name, top_n=10):
# 인자로 입력된 movies_df DataFrame에서 'title' 컬럼이 입력된 title_name 값인 DataFrame추출
title_movie = df[df['title'] == title_name]
# title_named을 가진 DataFrame의 index 객체를 ndarray로 반환하고
# sorted_ind 인자로 입력된 genre_sim_sorted_ind 객체에서 유사도 순으로 top_n 개의 index 추출
title_index = title_movie.index.values
similar_indexes = sorted_ind[title_index, :(top_n)]
# 추출된 top_n index들 출력. top_n index는 2차원 데이터 임.
#dataframe에서 index로 사용하기 위해서 1차원 array로 변경
print(similar_indexes)
similar_indexes = similar_indexes.reshape(-1)
return df.iloc[similar_indexes]
find_sim_movie() 함수를 이용해 영화 대부'와 장르 별로 유사한 영화 10개를 추천해 보겠습니다.
similar_movies = find_sim_movie(movies_df, genre_sim_sorted_ind, 'The Godfather',10)
similar_movies[['title', 'vote_average']]
movies_df[['title','vote_average','vote_count']].sort_values('vote_average', ascending=False)[:10]
'쇼생크 탈출(The Shawshank Redemption)', '대부(The Godfather)' 같은 명작보다 생소한 영화들이 더 높은 평점으로 나타남
예: 'Stiff Upper Lips', 'Me You and Five Bucks' 등 → 이유: 평가 횟수가 매우 적음
평점 왜곡 회피 필요 → 평가 횟수를 반영한 새로운 평가 방식 필요
IMDb에서는 평가 횟수 기반 가중 평점(Weighted Rating) 방식을 사용
이 방식을 이용해 새롭게 평점을 부여
• v : 개별 영화에 평점을 투표한 횟수
• m : 평점을 부여하기 위한 최소 투표 횟수
• R : 개별 영화에 대한 평균 평점
• C : 전체 영화에 대한 평균 평점
C = movies_df['vote_average'].mean()
m = movies_df['vote_count'].quantile(0.6)
print('C:',round(C,3), 'm:',round(m,3))
percentile = 0.6
m = movies_df['vote_count'].quantile(percentile)
C = movies_df['vote_average'].mean()
def weighted_vote_average(record):
v = record['vote_count']
R = record['vote_average']
return ( (v/(v+m)) * R ) + ( (m/(m+v)) * C )
movies_df['weighted_vote'] = movies_df.apply(weighted_vote_average, axis=1)
새롭게 부여된 weighted_vote 평점이 높은 순으로 상위 10개의 영화를 추출해 보겠습니다.
movies_df[['title','vote_average','weighted_vote','vote_count']].sort_values('weighted_vote',
ascending=False)[:10]
def find_sim_movie(df, sorted_ind, title_name, top_n=10):
title_movie = df[df['title'] == title_name]
title_index = title_movie.index.values
# top_n의 2배에 해당하는 쟝르 유사성이 높은 index 추출
similar_indexes = sorted_ind[title_index, :(top_n*2)]
similar_indexes = similar_indexes.reshape(-1)
# 기준 영화 index는 제외
similar_indexes = similar_indexes[similar_indexes != title_index]
# top_n의 2배에 해당하는 후보군에서 weighted_vote 높은 순으로 top_n 만큼 추출
return df.iloc[similar_indexes].sort_values('weighted_vote', ascending=False)[:top_n]
similar_movies = find_sim_movie(movies_df, genre_sim_sorted_ind, 'The Godfather',10)
similar_movies[['title', 'vote_average', 'weighted_vote']]
데이터 가공 및 변환
import pandas as pd
import numpy as np
movies = pd.read_csv('/content/sample_data/movies.csv')
ratings = pd.read_csv('/content/sample_data/ratings.csv')
print(movies.shape)
print(ratings.shape)

pivot_table() 함수는 row 형태의 데이터를 column 형태로 쉽게 변환 가능
columns='movieId'를 지정하면 movieId 값이 새로운 열 이름이 됨
ratings.pivot_table('rating', index='userId', columns='movieId') 호출 시
행: userId
열: movieId
값: rating
즉, 사용자-아이템 평점 행렬로 변환됨
ratings = ratings[['userId', 'movieId', 'rating']]
ratings_matrix = ratings.pivot_table('rating', index='userId', columns='movieId')
ratings_matrix.head(3)
# title 컬럼을 얻기 이해 movies 와 조인 수행
rating_movies = pd.merge(ratings, movies, on='movieId')
# columns='title' 로 title 컬럼으로 pivot 수행.
ratings_matrix = rating_movies.pivot_table('rating', index='userId', columns='title')
# NaN 값을 모두 0 으로 변환
ratings_matrix = ratings_matrix.fillna(0)
ratings_matrix.head(3)

ratings_matrix_T = ratings_matrix.transpose()
ratings_matrix_T.head(3)
ratings_matrix 를 전치 행렬 형식으로 변경한 데이터셋을 기반으로 영화의 코사인 유사도를 구해보겠습니다.
그리고 좀 더 직관적인 영화의 유사도 값을 표현하기 위해 cosine_similarity() 로 반환된 넘파이 행렬에 영화명을 매핑해 DataFrame 으로 변환하겠습니다.
from sklearn.metrics.pairwise import cosine_similarity
item_sim = cosine_similarity(ratings_matrix_T, ratings_matrix_T)
# cosine_similarity() 로 반환된 넘파이 행렬을 영화명을 매핑하여 DataFrame으로 변환
item_sim_df = pd.DataFrame(data=item_sim, index=ratings_matrix.columns,
columns=ratings_matrix.columns)
print(item_sim_df.shape)
item_sim_df.head(3)
확률적 경사 하강법(SGD)을 이용해 사용자–아이템 평점 행렬을 행렬 분해(Matrix Factorization) 하여, 추천 시스템을 구현
R: 원본 평점 행렬 (사용자 × 아이템)
K: 잠재 요인 수
steps: 반복 횟수
learning_rate: 학습률
r_lambda: L2 정규화 계수
구현:
get_rmse(): 예측 평점과 실제 평점의 RMSE 계산 함수
matrix_factorization(): 위 파라미터로 행렬 분해를 수행하는 함수로 정의하여 재사용 가능하게 구성
# Uninstall existing scikit-surprise and numpy to ensure a clean installation
!pip uninstall scikit-surprise numpy -y
# Install a compatible version of numpy first
!pip install numpy==1.24.4 # You can try a different version if this doesn't work
# Reinstall scikit-surprise
!pip install scikit-surprise
# Import surprise again to check if the error is resolved
import surprise
print(surprise.__version__)
# Also check the numpy version
import numpy
print(numpy.__version__)
import surprise
print(surprise.__version__)
!pip uninstall scikit-surprise numpy -y
# Install a compatible version of numpy first. Use a version known to work well with surprise.
# numpy==1.24.4 is a good starting point.
!pip install numpy==1.24.4
# Reinstall scikit-surprise
!pip install scikit-surprise
# Import surprise again to check if the error is resolved
import surprise
print(surprise.__version__)
# Also check the numpy version
import numpy
print(numpy.__version__)
# Import the required modules from surprise
from surprise import SVD
from surprise import Dataset
from surprise import accuracy
from surprise.model_selection import train_test_split
!pip uninstall numpy -y
!pip install numpy
# Import the required modules from surprise
from surprise import SVD
from surprise import Dataset
from surprise import accuracy
from surprise.model_selection import train_test_split
# Load the built-in dataset
data = Dataset.load_builtin('ml-100k')
# Split the data into training and testing sets for reproducibility
trainset, testset = train_test_split(data, test_size=.25, random_state=0)
algo = SVD(random_state=0)
algo.fit(trainset)
predictions = algo.test( testset )
print('prediction type :',type(predictions), ' size:',len(predictions))
print('prediction 결과의 최초 5개 추출')
predictions[:5]
[ (pred.uid, pred.iid, pred.est) for pred in predictions[:3] ]
# 사용자 아이디, 아이템 아이디는 문자열로 입력해야 함.
uid = str(196)
iid = str(302)
pred = algo.predict(uid, iid)
print(pred)
accuracy.rmse(predictions)
import pandas as pd
ratings = pd.read_csv('/content/sample_data/ratings.csv')
# ratings_noh.csv 파일로 unload 시 index 와 header를 모두 제거한 새로운 파일 생성.
ratings.to_csv('/content/sample_data/ratings_noh.csv', index=False, header=False)
from surprise import Reader
reader = Reader(line_format='user item rating timestamp', sep=',', rating_scale=(0.5, 5))
data=Dataset.load_from_file('/content/sample_data/ratings_noh.csv',reader=reader)
trainset, testset = train_test_split(data, test_size=.25, random_state=0)
# 수행시마다 동일한 결과 도출을 위해 random_state 설정
algo = SVD(n_factors=50, random_state=0)
# 학습 데이터 세트로 학습 후 테스트 데이터 세트로 평점 예측 후 RMSE 평가
algo.fit(trainset)
predictions = algo.test( testset )
accuracy.rmse(predictions)
import pandas as pd
from surprise import Reader, Dataset
ratings = pd.read_csv('/content/sample_data/ratings.csv')
reader = Reader(rating_scale=(0.5, 5.0))
# ratings DataFrame 에서 컬럼은 사용자 아이디, 아이템 아이디, 평점 순서를 지켜야 합니다.
data = Dataset.load_from_df(ratings[['userId', 'movieId', 'rating']], reader)
trainset, testset = train_test_split(data, test_size=.25, random_state=0)
algo = SVD(n_factors=50, random_state=0)
algo.fit(trainset)
predictions = algo.test( testset )
accuracy.rmse(predictions)
from surprise.model_selection import cross_validate
# 판다스 DataFrame에서 Surprise 데이터 세트로 데이터 로딩
ratings = pd.read_csv('/content/sample_data/ratings.csv') # reading data in pandas df
reader = Reader(rating_scale=(0.5, 5.0))
data = Dataset.load_from_df(ratings[['userId', 'movieId', 'rating']], reader)
algo = SVD(random_state=0)
cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=5, verbose=True)
from surprise.model_selection import GridSearchCV
# 최적화할 파라미터를 딕셔너리 형태로 지정.
param_grid = {'n_epochs': [20, 40, 60], 'n_factors': [50, 100, 200] }
# CV를 3개 폴드 세트로 지정, 성능 평가는 rmse, mse로 수행하도록 GridSearchCV 구성
gs = GridSearchCV(SVD, param_grid, measures=['rmse', 'mae'], cv=3)
gs.fit(data)
# 최고 RMSE Evaluation 점수와 그때의 하이퍼 파라미터
print(gs.best_score['rmse'])
print(gs.best_params['rmse'])
from surprise.dataset import DatasetAutoFolds
reader = Reader(line_format='user item rating timestamp', sep=',', rating_scale=(0.5, 5))
# DatasetAutoFolds 클래스를 ratings_noh.csv 파일 기반으로 생성.
data_folds = DatasetAutoFolds(ratings_file='/content/sample_data/ratings_noh.csv', reader=reader)
#전체 데이터를 학습데이터로 생성함.
trainset = data_folds.build_full_trainset()
algo = SVD(n_epochs=20, n_factors=50, random_state=0)
algo.fit(trainset)
# 영화에 대한 상세 속성 정보 DataFrame로딩
movies = pd.read_csv('/content/sample_data/movies.csv')
# userId=9 의 movieId 데이터 추출하여 movieId=42 데이터가 있는지 확인.
movieIds = ratings[ratings['userId']==9]['movieId']
if movieIds[movieIds==42].count() == 0:
print('사용자 아이디 9는 영화 아이디 42의 평점 없음')
print(movies[movies['movieId']==42])
uid = str(9)
iid = str(42)
pred = algo.predict(uid, iid, verbose=True)
def get_unseen_surprise(ratings, movies, userId):
#입력값으로 들어온 userId에 해당하는 사용자가 평점을 매긴 모든 영화를 리스트로 생성
seen_movies = ratings[ratings['userId']== userId]['movieId'].tolist()
# 모든 영화들의 movieId를 리스트로 생성.
total_movies = movies['movieId'].tolist()
# 모든 영화들의 movieId중 이미 평점을 매긴 영화의 movieId를 제외하여 리스트로 생성
unseen_movies= [movie for movie in total_movies if movie not in seen_movies]
print('평점 매긴 영화수:',len(seen_movies), '추천대상 영화수:',len(unseen_movies), \
'전체 영화수:',len(total_movies))
return unseen_movies
unseen_movies = get_unseen_surprise(ratings, movies, 9)
def recomm_movie_by_surprise(algo, userId, unseen_movies, top_n=10):
# 알고리즘 객체의 predict() 메서드를 평점이 없는 영화에 반복 수행한 후 결과를 list 객체로 저장
predictions = [algo.predict(str(userId), str(movieId)) for movieId in unseen_movies]
# predictions list 객체는 surprise의 Predictions 객체를 원소로 가지고 있음.
# [Prediction(uid='9', iid='1', est=3.69), Prediction(uid='9', iid='2', est=2.98),,,,]
# 이를 est 값으로 정렬하기 위해서 아래의 sortkey_est 함수를 정의함.
# sortkey_est 함수는 list 객체의 sort() 함수의 키 값으로 사용되어 정렬 수행.
def sortkey_est(pred):
return pred.est
# sortkey_est( ) 반환값의 내림 차순으로 정렬 수행하고 top_n개의 최상위 값 추출.
predictions.sort(key=sortkey_est, reverse=True)
top_predictions= predictions[:top_n]
# top_n으로 추출된 영화의 정보 추출. 영화 아이디, 추천 예상 평점, 제목 추출
top_movie_ids = [ int(pred.iid) for pred in top_predictions]
top_movie_rating = [ pred.est for pred in top_predictions]
top_movie_titles = movies[movies.movieId.isin(top_movie_ids)]['title']
top_movie_preds = [ (id, title, rating) for id, title, rating in zip(top_movie_ids, top_movie_titles, top_movie_rating)]
return top_movie_preds
unseen_movies = get_unseen_surprise(ratings, movies, 9)
top_movie_preds = recomm_movie_by_surprise(algo, 9, unseen_movies, top_n=10)
print('##### Top-10 추천 영화 리스트 #####')
for top_movie in top_movie_preds:
print(top_movie[1], ":", top_movie[2])