<jupyter_start><jupyter_text>29. 사이킷런을 활용한 추천 시스템 입문**추천 시스템의 기본 개념과 종류에 대해 알아보고, 사이킷런을 활용하여 연습해 봅니다. 기초적인 추천 시스템을 기반으로 실제 사용되는 추천 시스템이 어떻게 동작하는지 생각해 봅니다.**  29-1. 들어가며 ```bash$ mkdir -p ~/aiffel/movie_recommendation```  29-2. 추천 시스템이란?  29-3. 코사인 유사도<jupyter_code>import numpy as np

t1 = np.array([1, 1, 1])
t2 = np.array([2, 0, 1])
from numpy import dot
from numpy.linalg import norm
def cos_sim(A, B):
	return dot(A, B)/(norm(A)*norm(B))
cos_sim(t1, t2)
from sklearn.metrics.pairwise import cosine_similarity
t1 = np.array([[1, 1, 1]])
t2 = np.array([[2, 0, 1]])
cosine_similarity(t1,t2)<jupyter_output><empty_output><jupyter_text>29-4. 추천시스템의 종류  29-5. 콘텐츠 기반 필터링<jupyter_code>import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity

print('⏩⏩')
import os
csv_path = os.getenv('HOME')+'/aiffel/movie_recommendation/movie_dataset.csv'
df = pd.read_csv(csv_path)
df.head()
df.columns
features = ['keywords','cast','genres','director']
features
def combine_features(row):
    return row['keywords']+" "+row['cast']+" "+row['genres']+" "+row['director']

combine_features(df[:5])
for feature in features:
    df[feature] = df[feature].fillna('')

df["combined_features"] = df.apply(combine_features,axis=1)
df["combined_features"]
cv = CountVectorizer()
count_matrix = cv.fit_transform(df["combined_features"])
print(type(count_matrix))
print(count_matrix.shape)
print(count_matrix)
cosine_sim = cosine_similarity(count_matrix)
print(cosine_sim)
print(cosine_sim.shape)
def get_title_from_index(index):
    return df[df.index == index]["title"].values[0]
def get_index_from_title(title):
    return df[df.title == title]["index"].values[0]

movie_user_likes = "Avatar"
movie_index = get_index_from_title(movie_user_likes)
similar_movies = list(enumerate(cosine_sim[movie_index]))

sorted_similar_movies = sorted(similar_movies,key=lambda x:x[1],reverse=True)[1:]

i=0
print(movie_user_likes+"와 비슷한 영화 3편은 "+"\n")
for item in sorted_similar_movies:
    print(get_title_from_index(item[0]))
    i=i+1
    if i==3:
        break<jupyter_output><empty_output><jupyter_text>29-6. 협업 필터링 (1) 협업 필터링의 종류  29-7. 협업 필터링 (2) 행렬 인수분해<jupyter_code>import numpy as np
from numpy.linalg import svd
np.random.seed(30)
A = np.random.randint(0, 100, size=(4, 4))
A
svd(A)
U, Sigma, VT = svd(A)

print('U matrix: {}\n'.format(U.shape),U)
print('Sigma: {}\n'.format(Sigma.shape),Sigma)
print('V Transpose matrix: {}\n'.format(VT.shape),VT)
Sigma_mat = np.diag(Sigma)

A_ = np.dot(np.dot(U, Sigma_mat), VT)
A_<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15699006875477464, 'fraction_numerical': 0.024446142093200916, 'mean_word_length': 6.234806629834254, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '574762', 'license': 'MIT', 'n_tokens_mistral': 1248, 'n_tokens_neox': 1316, 'n_words': 222, 'path': 'FUNDAMENTALS/Node_29/[F-29] Only_LMS_Code_Blocks.ipynb', 'repo_name': 'HRPzz/AIFFEL', 'size': '2618'}