diff --git "a/Week16_\353\263\265\354\212\265\352\263\274\354\240\234_\352\271\200\354\230\210\353\202\230.ipynb" "b/Week16_\353\263\265\354\212\265\352\263\274\354\240\234_\352\271\200\354\230\210\353\202\230.ipynb" new file mode 100644 index 0000000..2069d7b --- /dev/null +++ "b/Week16_\353\263\265\354\212\265\352\263\274\354\240\234_\352\271\200\354\230\210\353\202\230.ipynb" @@ -0,0 +1,3039 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "97c4ec9e-8f21-4844-b5e6-a36edb2f250c", + "metadata": {}, + "source": [ + "9.5\n" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "366da19e-933e-4d39-8a57-6abc5052b6d0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(4803, 20)\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
budgetgenreshomepageidkeywordsoriginal_languageoriginal_titleoverviewpopularityproduction_companiesproduction_countriesrelease_daterevenueruntimespoken_languagesstatustaglinetitlevote_averagevote_count
0237000000[{\"id\": 28, \"name\": \"Action\"}, {\"id\": 12, \"name\": \"Adventure\"}, {\"id\": 14, \"name\": \"Fantasy\"}, {...http://www.avatarmovie.com/19995[{\"id\": 1463, \"name\": \"culture clash\"}, {\"id\": 2964, \"name\": \"future\"}, {\"id\": 3386, \"name\": \"sp...enAvatarIn the 22nd century, a paraplegic Marine is dispatched to the moon Pandora on a unique mission, ...150.437577[{\"name\": \"Ingenious Film Partners\", \"id\": 289}, {\"name\": \"Twentieth Century Fox Film Corporatio...[{\"iso_3166_1\": \"US\", \"name\": \"United States of America\"}, {\"iso_3166_1\": \"GB\", \"name\": \"United ...2009-12-102787965087162.0[{\"iso_639_1\": \"en\", \"name\": \"English\"}, {\"iso_639_1\": \"es\", \"name\": \"Espa\\u00f1ol\"}]ReleasedEnter the World of Pandora.Avatar7.211800
\n", + "
" + ], + "text/plain": [ + " budget \\\n", + "0 237000000 \n", + "\n", + " genres \\\n", + "0 [{\"id\": 28, \"name\": \"Action\"}, {\"id\": 12, \"name\": \"Adventure\"}, {\"id\": 14, \"name\": \"Fantasy\"}, {... \n", + "\n", + " homepage id \\\n", + "0 http://www.avatarmovie.com/ 19995 \n", + "\n", + " keywords \\\n", + "0 [{\"id\": 1463, \"name\": \"culture clash\"}, {\"id\": 2964, \"name\": \"future\"}, {\"id\": 3386, \"name\": \"sp... \n", + "\n", + " original_language original_title \\\n", + "0 en Avatar \n", + "\n", + " overview \\\n", + "0 In the 22nd century, a paraplegic Marine is dispatched to the moon Pandora on a unique mission, ... \n", + "\n", + " popularity \\\n", + "0 150.437577 \n", + "\n", + " production_companies \\\n", + "0 [{\"name\": \"Ingenious Film Partners\", \"id\": 289}, {\"name\": \"Twentieth Century Fox Film Corporatio... \n", + "\n", + " production_countries \\\n", + "0 [{\"iso_3166_1\": \"US\", \"name\": \"United States of America\"}, {\"iso_3166_1\": \"GB\", \"name\": \"United ... \n", + "\n", + " release_date revenue runtime \\\n", + "0 2009-12-10 2787965087 162.0 \n", + "\n", + " spoken_languages \\\n", + "0 [{\"iso_639_1\": \"en\", \"name\": \"English\"}, {\"iso_639_1\": \"es\", \"name\": \"Espa\\u00f1ol\"}] \n", + "\n", + " status tagline title vote_average vote_count \n", + "0 Released Enter the World of Pandora. Avatar 7.2 11800 " + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import warnings; warnings.filterwarnings('ignore')\n", + "\n", + "movies =pd.read_csv('./tmdb_5000_movies.csv') \n", + "print(movies.shape)\n", + "movies.head(1)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "51e83ac0-159a-46a8-8f98-94b1d5ea84e0", + "metadata": {}, + "outputs": [], + "source": [ + " movies_df = movies[['id', 'title', 'genres', 'vote_average', 'vote_count', 'popularity','keywords', 'overview']]" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "5531d83f-b9de-414a-b266-070cd658a191", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
genreskeywords
0[{\"id\": 28, \"name\": \"Action\"}, {\"id\": 12, \"name\": \"Adventure\"}, {\"id\": 14, \"name\": \"Fantasy\"}, {...[{\"id\": 1463, \"name\": \"culture clash\"}, {\"id\": 2964, \"name\": \"future\"}, {\"id\": 3386, \"name\": \"sp...
\n", + "
" + ], + "text/plain": [ + " genres \\\n", + "0 [{\"id\": 28, \"name\": \"Action\"}, {\"id\": 12, \"name\": \"Adventure\"}, {\"id\": 14, \"name\": \"Fantasy\"}, {... \n", + "\n", + " keywords \n", + "0 [{\"id\": 1463, \"name\": \"culture clash\"}, {\"id\": 2964, \"name\": \"future\"}, {\"id\": 3386, \"name\": \"sp... " + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pd.set_option('max_colwidth', 100)\n", + "movies_df[['genres', 'keywords']][: 1]" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "62da79b5-c842-43ee-9107-2578ea922052", + "metadata": {}, + "outputs": [], + "source": [ + "from ast import literal_eval\n", + "\n", + "movies_df['genres'] = movies_df['genres'].apply(literal_eval)\n", + "movies_df['keywords'] = movies_df['keywords'].apply(literal_eval)" + ] + }, + { + "cell_type": "markdown", + "id": "4f43c54f-aa24-420c-8f5f-f199be5af7a7", + "metadata": {}, + "source": [ + "-> 문자열을 객체로 변환" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "06341d9e-9150-400a-bd0a-472ef875b932", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
genreskeywords
0[Action, Adventure, Fantasy, Science Fiction][culture clash, future, space war, space colony, society, space travel, futuristic, romance, spa...
\n", + "
" + ], + "text/plain": [ + " genres \\\n", + "0 [Action, Adventure, Fantasy, Science Fiction] \n", + "\n", + " keywords \n", + "0 [culture clash, future, space war, space colony, society, space travel, futuristic, romance, spa... " + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "movies_df['genres'] = movies_df['genres'].apply(lambda x : [ y['name'] for y in x])\n", + "movies_df['keywords'] = movies_df['keywords'].apply(lambda x : [ y['name'] for y in x])\n", + "movies_df[['genres', 'keywords']][:1]" + ] + }, + { + "cell_type": "markdown", + "id": "e018166d-6baf-49da-b221-3d0846be89ff", + "metadata": {}, + "source": [ + "장르 콘텐츠 유사도 측정" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "bf36c271-87a6-4d81-8d17-a092e8a26e88", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(4803, 276)\n" + ] + } + ], + "source": [ + "from sklearn.feature_extraction.text import CountVectorizer\n", + "\n", + "movies_df['genres_literal'] = movies_df['genres'].apply(lambda x : (' ').join(x))\n", + "count_vect = CountVectorizer(min_df=1, ngram_range=(1,2))\n", + "genre_mat = count_vect.fit_transform(movies_df['genres_literal'])\n", + "print(genre_mat.shape)" + ] + }, + { + "cell_type": "markdown", + "id": "41e67637-3dac-4163-9fd8-308ee99a1c1e", + "metadata": {}, + "source": [ + "min_df = 0 으로 하면 오류나서 1로 수정" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "7a93dbcc-ed75-46ea-965f-9b2052df58ad", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(4803, 4803)\n", + "[[1. 0.59628479 0.4472136 ... 0. 0. 0. ]\n", + " [0.59628479 1. 0.4 ... 0. 0. 0. ]]\n" + ] + } + ], + "source": [ + "from sklearn.metrics.pairwise import cosine_similarity\n", + "\n", + "genre_sim = cosine_similarity(genre_mat, genre_mat)\n", + "print(genre_sim.shape)\n", + "print(genre_sim[:2])" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "f399c2ea-1c30-4e65-8c89-be51795eb1f5", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 0 3494 813 ... 3038 3037 2401]]\n" + ] + } + ], + "source": [ + "genre_sim_sorted_ind = genre_sim.argsort()[:, ::-1]\n", + "print(genre_sim_sorted_ind[:1])" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "eb7fa1e5-4784-41e0-aaf8-fe30c5c8b15a", + "metadata": {}, + "outputs": [], + "source": [ + "def find_sim_movie(df, sorted_ind, title_name, top_n=10):\n", + " \n", + " title_movie = df[df['title'] == title_name]\n", + " \n", + " title_index = title_movie.index.values\n", + " similar_indexes = sorted_ind[title_index, :(top_n)]\n", + " print(similar_indexes)\n", + " similar_indexes = similar_indexes.reshape(-1)\n", + " \n", + " return df.iloc[similar_indexes]" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "1f6b71a6-5ac8-4e7e-9f5f-d785d683bde3", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[2731 1243 3636 1946 2640 4065 1847 4217 883 3866]]\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
titlevote_average
2731The Godfather: Part II8.3
1243Mean Streets7.2
3636Light Sleeper5.7
1946The Bad Lieutenant: Port of Call - New Orleans6.0
2640Things to Do in Denver When You're Dead6.7
4065Mi America0.0
1847GoodFellas8.2
4217Kids6.8
883Catch Me If You Can7.7
3866City of God8.1
\n", + "
" + ], + "text/plain": [ + " title vote_average\n", + "2731 The Godfather: Part II 8.3\n", + "1243 Mean Streets 7.2\n", + "3636 Light Sleeper 5.7\n", + "1946 The Bad Lieutenant: Port of Call - New Orleans 6.0\n", + "2640 Things to Do in Denver When You're Dead 6.7\n", + "4065 Mi America 0.0\n", + "1847 GoodFellas 8.2\n", + "4217 Kids 6.8\n", + "883 Catch Me If You Can 7.7\n", + "3866 City of God 8.1" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "similar_movies = find_sim_movie(movies_df, genre_sim_sorted_ind, 'The Godfather',10)\n", + "similar_movies[['title', 'vote_average']]" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "e21c2453-53fd-4776-b196-c744db503624", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
titlevote_averagevote_count
3519Stiff Upper Lips10.01
4247Me You and Five Bucks10.02
4045Dancer, Texas Pop. 8110.01
4662Little Big Top10.01
3992Sardaarji9.52
2386One Man's Hero9.32
2970There Goes My Baby8.52
1881The Shawshank Redemption8.58205
2796The Prisoner of Zenda8.411
3337The Godfather8.45893
\n", + "
" + ], + "text/plain": [ + " title vote_average vote_count\n", + "3519 Stiff Upper Lips 10.0 1\n", + "4247 Me You and Five Bucks 10.0 2\n", + "4045 Dancer, Texas Pop. 81 10.0 1\n", + "4662 Little Big Top 10.0 1\n", + "3992 Sardaarji 9.5 2\n", + "2386 One Man's Hero 9.3 2\n", + "2970 There Goes My Baby 8.5 2\n", + "1881 The Shawshank Redemption 8.5 8205\n", + "2796 The Prisoner of Zenda 8.4 11\n", + "3337 The Godfather 8.4 5893" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "movies_df[['title','vote_average','vote_count']].sort_values('vote_average', ascending=False)[:10]" + ] + }, + { + "cell_type": "markdown", + "id": "5cd3ce1a-521b-47de-810c-d3ffed341a20", + "metadata": {}, + "source": [ + "왜곡된 평점 데이터를 회피해야함 : 가중평점 이용" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "98008c97-ea05-46b5-a13a-190ec0ec29a2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "C: 6.092 m: 370.2\n" + ] + } + ], + "source": [ + "C = movies_df['vote_average'].mean()\n", + "m = movies_df['vote_count'].quantile(0.6)\n", + "print('C:',round(C,3), 'm:',round(m,3))" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "fc2d9419-b19a-4b39-8169-9e9a2bb284ba", + "metadata": {}, + "outputs": [], + "source": [ + "percentile = 0.6\n", + "m = movies_df['vote_count'].quantile(percentile)\n", + "C = movies_df['vote_average'].mean()\n", + "\n", + "def weighted_vote_average(record):\n", + " v = record['vote_count']\n", + " R = record['vote_average']\n", + " \n", + " return ( (v/(v+m)) * R ) + ( (m/(m+v)) * C ) \n", + "\n", + "movies_df['weighted_vote'] = movies_df.apply(weighted_vote_average, axis=1) " + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "267895a7-d068-49d7-b678-d73859f47409", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
titlevote_averageweighted_votevote_count
1881The Shawshank Redemption8.58.3960528205
3337The Godfather8.48.2635915893
662Fight Club8.38.2164559413
3232Pulp Fiction8.38.2071028428
65The Dark Knight8.28.13693012002
1818Schindler's List8.38.1260694329
3865Whiplash8.38.1232484254
809Forrest Gump8.28.1059547927
2294Spirited Away8.38.1058673840
2731The Godfather: Part II8.38.0795863338
\n", + "
" + ], + "text/plain": [ + " title vote_average weighted_vote vote_count\n", + "1881 The Shawshank Redemption 8.5 8.396052 8205\n", + "3337 The Godfather 8.4 8.263591 5893\n", + "662 Fight Club 8.3 8.216455 9413\n", + "3232 Pulp Fiction 8.3 8.207102 8428\n", + "65 The Dark Knight 8.2 8.136930 12002\n", + "1818 Schindler's List 8.3 8.126069 4329\n", + "3865 Whiplash 8.3 8.123248 4254\n", + "809 Forrest Gump 8.2 8.105954 7927\n", + "2294 Spirited Away 8.3 8.105867 3840\n", + "2731 The Godfather: Part II 8.3 8.079586 3338" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "movies_df[['title','vote_average','weighted_vote','vote_count']].sort_values('weighted_vote',\n", + " ascending=False)[:10]" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "5834b05b-c9d5-46a6-8e6c-1ed8d1beead9", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
titlevote_averageweighted_vote
2731The Godfather: Part II8.38.079586
1847GoodFellas8.27.976937
3866City of God8.17.759693
1663Once Upon a Time in America8.27.657811
883Catch Me If You Can7.77.557097
281American Gangster7.47.141396
4041This Is England7.46.739664
1149American Hustle6.86.717525
1243Mean Streets7.26.626569
2839Rounders6.96.530427
\n", + "
" + ], + "text/plain": [ + " title vote_average weighted_vote\n", + "2731 The Godfather: Part II 8.3 8.079586\n", + "1847 GoodFellas 8.2 7.976937\n", + "3866 City of God 8.1 7.759693\n", + "1663 Once Upon a Time in America 8.2 7.657811\n", + "883 Catch Me If You Can 7.7 7.557097\n", + "281 American Gangster 7.4 7.141396\n", + "4041 This Is England 7.4 6.739664\n", + "1149 American Hustle 6.8 6.717525\n", + "1243 Mean Streets 7.2 6.626569\n", + "2839 Rounders 6.9 6.530427" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def find_sim_movie(df, sorted_ind, title_name, top_n=10):\n", + " title_movie = df[df['title'] == title_name]\n", + " title_index = title_movie.index.values\n", + " \n", + " # top_n의 2배에 해당하는 쟝르 유사성이 높은 index 추출 \n", + " similar_indexes = sorted_ind[title_index, :(top_n*2)]\n", + " similar_indexes = similar_indexes.reshape(-1)\n", + " similar_indexes = similar_indexes[similar_indexes != title_index]\n", + " return df.iloc[similar_indexes].sort_values('weighted_vote', ascending=False)[:top_n]\n", + "\n", + "similar_movies = find_sim_movie(movies_df, genre_sim_sorted_ind, 'The Godfather',10)\n", + "similar_movies[['title', 'vote_average', 'weighted_vote']]" + ] + }, + { + "cell_type": "markdown", + "id": "84007d7e-b122-4f12-a69e-74d8a9f038a8", + "metadata": {}, + "source": [ + "-> find_sim_movie 함수를 변경해서 다시 '대부'와 유사한 영화를 추천" + ] + }, + { + "cell_type": "markdown", + "id": "9300b792-7809-4bc3-be16-1c1f38e9903a", + "metadata": {}, + "source": [ + "9.6 아이템 기반 최근접 이웃 협업 필터링 실습" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "9896d2f6-8f26-4631-b120-12dc00a79150", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(9742, 3)\n", + "(100836, 4)\n" + ] + } + ], + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "movies = pd.read_csv('./ml-latest-small/movies.csv')\n", + "ratings = pd.read_csv('./ml-latest-small/ratings.csv')\n", + "print(movies.shape)\n", + "print(ratings.shape)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "764696f4-be89-42a8-b474-25bdafd2afd3", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
movieIdtitlegenres
01Toy Story (1995)Adventure|Animation|Children|Comedy|Fantasy
12Jumanji (1995)Adventure|Children|Fantasy
23Grumpier Old Men (1995)Comedy|Romance
34Waiting to Exhale (1995)Comedy|Drama|Romance
45Father of the Bride Part II (1995)Comedy
\n", + "
" + ], + "text/plain": [ + " movieId title \\\n", + "0 1 Toy Story (1995) \n", + "1 2 Jumanji (1995) \n", + "2 3 Grumpier Old Men (1995) \n", + "3 4 Waiting to Exhale (1995) \n", + "4 5 Father of the Bride Part II (1995) \n", + "\n", + " genres \n", + "0 Adventure|Animation|Children|Comedy|Fantasy \n", + "1 Adventure|Children|Fantasy \n", + "2 Comedy|Romance \n", + "3 Comedy|Drama|Romance \n", + "4 Comedy " + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "movies.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "31724371-7456-4955-96e6-4e3b12eeaef4", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
movieId12345678910...193565193567193571193573193579193581193583193585193587193609
userId
14.0NaN4.0NaNNaN4.0NaNNaNNaNNaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
2NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
3NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
\n", + "

3 rows × 9724 columns

\n", + "
" + ], + "text/plain": [ + "movieId 1 2 3 4 5 6 7 8 \\\n", + "userId \n", + "1 4.0 NaN 4.0 NaN NaN 4.0 NaN NaN \n", + "2 NaN NaN NaN NaN NaN NaN NaN NaN \n", + "3 NaN NaN NaN NaN NaN NaN NaN NaN \n", + "\n", + "movieId 9 10 ... 193565 193567 193571 193573 193579 193581 \\\n", + "userId ... \n", + "1 NaN NaN ... NaN NaN NaN NaN NaN NaN \n", + "2 NaN NaN ... NaN NaN NaN NaN NaN NaN \n", + "3 NaN NaN ... NaN NaN NaN NaN NaN NaN \n", + "\n", + "movieId 193583 193585 193587 193609 \n", + "userId \n", + "1 NaN NaN NaN NaN \n", + "2 NaN NaN NaN NaN \n", + "3 NaN NaN NaN NaN \n", + "\n", + "[3 rows x 9724 columns]" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ratings = ratings[['userId', 'movieId', 'rating']]\n", + "ratings_matrix = ratings.pivot_table('rating', index='userId', columns='movieId')\n", + "ratings_matrix.head(3)" + ] + }, + { + "cell_type": "markdown", + "id": "b2ddb347-a788-49da-918e-84f919cbf148", + "metadata": {}, + "source": [ + "-> 모든 사용자를 로우, 모든 영화를 칼럼으로 구성한 데이터 세트로 변경" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "1fd1850d-c42c-4df5-9cd9-ad03e6ae39ae", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
title'71 (2014)'Hellboy': The Seeds of Creation (2004)'Round Midnight (1986)'Salem's Lot (2004)'Til There Was You (1997)'Tis the Season for Love (2015)'burbs, The (1989)'night Mother (1986)(500) Days of Summer (2009)*batteries not included (1987)...Zulu (2013)[REC] (2007)[REC]² (2009)[REC]³ 3 Génesis (2012)anohana: The Flower We Saw That Day - The Movie (2013)eXistenZ (1999)xXx (2002)xXx: State of the Union (2005)¡Three Amigos! (1986)À nous la liberté (Freedom for Us) (1931)
userId
10.00.00.00.00.00.00.00.00.00.0...0.00.00.00.00.00.00.00.04.00.0
20.00.00.00.00.00.00.00.00.00.0...0.00.00.00.00.00.00.00.00.00.0
30.00.00.00.00.00.00.00.00.00.0...0.00.00.00.00.00.00.00.00.00.0
\n", + "

3 rows × 9719 columns

\n", + "
" + ], + "text/plain": [ + "title '71 (2014) 'Hellboy': The Seeds of Creation (2004) \\\n", + "userId \n", + "1 0.0 0.0 \n", + "2 0.0 0.0 \n", + "3 0.0 0.0 \n", + "\n", + "title 'Round Midnight (1986) 'Salem's Lot (2004) \\\n", + "userId \n", + "1 0.0 0.0 \n", + "2 0.0 0.0 \n", + "3 0.0 0.0 \n", + "\n", + "title 'Til There Was You (1997) 'Tis the Season for Love (2015) \\\n", + "userId \n", + "1 0.0 0.0 \n", + "2 0.0 0.0 \n", + "3 0.0 0.0 \n", + "\n", + "title 'burbs, The (1989) 'night Mother (1986) (500) Days of Summer (2009) \\\n", + "userId \n", + "1 0.0 0.0 0.0 \n", + "2 0.0 0.0 0.0 \n", + "3 0.0 0.0 0.0 \n", + "\n", + "title *batteries not included (1987) ... Zulu (2013) [REC] (2007) \\\n", + "userId ... \n", + "1 0.0 ... 0.0 0.0 \n", + "2 0.0 ... 0.0 0.0 \n", + "3 0.0 ... 0.0 0.0 \n", + "\n", + "title [REC]² (2009) [REC]³ 3 Génesis (2012) \\\n", + "userId \n", + "1 0.0 0.0 \n", + "2 0.0 0.0 \n", + "3 0.0 0.0 \n", + "\n", + "title anohana: The Flower We Saw That Day - The Movie (2013) \\\n", + "userId \n", + "1 0.0 \n", + "2 0.0 \n", + "3 0.0 \n", + "\n", + "title eXistenZ (1999) xXx (2002) xXx: State of the Union (2005) \\\n", + "userId \n", + "1 0.0 0.0 0.0 \n", + "2 0.0 0.0 0.0 \n", + "3 0.0 0.0 0.0 \n", + "\n", + "title ¡Three Amigos! (1986) À nous la liberté (Freedom for Us) (1931) \n", + "userId \n", + "1 4.0 0.0 \n", + "2 0.0 0.0 \n", + "3 0.0 0.0 \n", + "\n", + "[3 rows x 9719 columns]" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# title 컬럼을 얻기 이해 movies 와 조인 수행\n", + "rating_movies = pd.merge(ratings, movies, on='movieId')\n", + "\n", + "# columns='title' 로 title 컬럼으로 pivot 수행. \n", + "ratings_matrix = rating_movies.pivot_table('rating', index='userId', columns='title')\n", + "\n", + "# NaN 값을 모두 0 으로 변환\n", + "ratings_matrix = ratings_matrix.fillna(0)\n", + "ratings_matrix.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "8d8adb65-2650-41f3-9497-123a935d0c4d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
userId12345678910...601602603604605606607608609610
title
'71 (2014)0.00.00.00.00.00.00.00.00.00.0...0.00.00.00.00.00.00.00.00.04.0
'Hellboy': The Seeds of Creation (2004)0.00.00.00.00.00.00.00.00.00.0...0.00.00.00.00.00.00.00.00.00.0
'Round Midnight (1986)0.00.00.00.00.00.00.00.00.00.0...0.00.00.00.00.00.00.00.00.00.0
\n", + "

3 rows × 610 columns

\n", + "
" + ], + "text/plain": [ + "userId 1 2 3 4 5 6 7 \\\n", + "title \n", + "'71 (2014) 0.0 0.0 0.0 0.0 0.0 0.0 0.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 0.0 0.0 0.0 0.0 0.0 0.0 \n", + "'Round Midnight (1986) 0.0 0.0 0.0 0.0 0.0 0.0 0.0 \n", + "\n", + "userId 8 9 10 ... 601 602 603 \\\n", + "title ... \n", + "'71 (2014) 0.0 0.0 0.0 ... 0.0 0.0 0.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 0.0 0.0 ... 0.0 0.0 0.0 \n", + "'Round Midnight (1986) 0.0 0.0 0.0 ... 0.0 0.0 0.0 \n", + "\n", + "userId 604 605 606 607 608 609 610 \n", + "title \n", + "'71 (2014) 0.0 0.0 0.0 0.0 0.0 0.0 4.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 0.0 0.0 0.0 0.0 0.0 0.0 \n", + "'Round Midnight (1986) 0.0 0.0 0.0 0.0 0.0 0.0 0.0 \n", + "\n", + "[3 rows x 610 columns]" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ratings_matrix_T = ratings_matrix.transpose()\n", + "ratings_matrix_T.head(3)" + ] + }, + { + "cell_type": "markdown", + "id": "d3178666-07df-4881-bd52-80620bc020c2", + "metadata": {}, + "source": [ + "변경된 데이터 세트 기반 코사인유사도 계산" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "a9e79b14-ee2c-49a0-a7fa-ecc30f1bdaf0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(9719, 9719)\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
title'71 (2014)'Hellboy': The Seeds of Creation (2004)'Round Midnight (1986)'Salem's Lot (2004)'Til There Was You (1997)'Tis the Season for Love (2015)'burbs, The (1989)'night Mother (1986)(500) Days of Summer (2009)*batteries not included (1987)...Zulu (2013)[REC] (2007)[REC]² (2009)[REC]³ 3 Génesis (2012)anohana: The Flower We Saw That Day - The Movie (2013)eXistenZ (1999)xXx (2002)xXx: State of the Union (2005)¡Three Amigos! (1986)À nous la liberté (Freedom for Us) (1931)
title
'71 (2014)1.00.0000000.0000000.00.00.00.0000000.00.1416530.0...0.00.3420550.5433050.7071070.00.00.1394310.3273270.00.0
'Hellboy': The Seeds of Creation (2004)0.01.0000000.7071070.00.00.00.0000000.00.0000000.0...0.00.0000000.0000000.0000000.00.00.0000000.0000000.00.0
'Round Midnight (1986)0.00.7071071.0000000.00.00.00.1767770.00.0000000.0...0.00.0000000.0000000.0000000.00.00.0000000.0000000.00.0
\n", + "

3 rows × 9719 columns

\n", + "
" + ], + "text/plain": [ + "title '71 (2014) \\\n", + "title \n", + "'71 (2014) 1.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 \n", + "'Round Midnight (1986) 0.0 \n", + "\n", + "title 'Hellboy': The Seeds of Creation (2004) \\\n", + "title \n", + "'71 (2014) 0.000000 \n", + "'Hellboy': The Seeds of Creation (2004) 1.000000 \n", + "'Round Midnight (1986) 0.707107 \n", + "\n", + "title 'Round Midnight (1986) \\\n", + "title \n", + "'71 (2014) 0.000000 \n", + "'Hellboy': The Seeds of Creation (2004) 0.707107 \n", + "'Round Midnight (1986) 1.000000 \n", + "\n", + "title 'Salem's Lot (2004) \\\n", + "title \n", + "'71 (2014) 0.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 \n", + "'Round Midnight (1986) 0.0 \n", + "\n", + "title 'Til There Was You (1997) \\\n", + "title \n", + "'71 (2014) 0.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 \n", + "'Round Midnight (1986) 0.0 \n", + "\n", + "title 'Tis the Season for Love (2015) \\\n", + "title \n", + "'71 (2014) 0.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 \n", + "'Round Midnight (1986) 0.0 \n", + "\n", + "title 'burbs, The (1989) \\\n", + "title \n", + "'71 (2014) 0.000000 \n", + "'Hellboy': The Seeds of Creation (2004) 0.000000 \n", + "'Round Midnight (1986) 0.176777 \n", + "\n", + "title 'night Mother (1986) \\\n", + "title \n", + "'71 (2014) 0.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 \n", + "'Round Midnight (1986) 0.0 \n", + "\n", + "title (500) Days of Summer (2009) \\\n", + "title \n", + "'71 (2014) 0.141653 \n", + "'Hellboy': The Seeds of Creation (2004) 0.000000 \n", + "'Round Midnight (1986) 0.000000 \n", + "\n", + "title *batteries not included (1987) ... \\\n", + "title ... \n", + "'71 (2014) 0.0 ... \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 ... \n", + "'Round Midnight (1986) 0.0 ... \n", + "\n", + "title Zulu (2013) [REC] (2007) \\\n", + "title \n", + "'71 (2014) 0.0 0.342055 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 0.000000 \n", + "'Round Midnight (1986) 0.0 0.000000 \n", + "\n", + "title [REC]² (2009) \\\n", + "title \n", + "'71 (2014) 0.543305 \n", + "'Hellboy': The Seeds of Creation (2004) 0.000000 \n", + "'Round Midnight (1986) 0.000000 \n", + "\n", + "title [REC]³ 3 Génesis (2012) \\\n", + "title \n", + "'71 (2014) 0.707107 \n", + "'Hellboy': The Seeds of Creation (2004) 0.000000 \n", + "'Round Midnight (1986) 0.000000 \n", + "\n", + "title anohana: The Flower We Saw That Day - The Movie (2013) \\\n", + "title \n", + "'71 (2014) 0.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 \n", + "'Round Midnight (1986) 0.0 \n", + "\n", + "title eXistenZ (1999) xXx (2002) \\\n", + "title \n", + "'71 (2014) 0.0 0.139431 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 0.000000 \n", + "'Round Midnight (1986) 0.0 0.000000 \n", + "\n", + "title xXx: State of the Union (2005) \\\n", + "title \n", + "'71 (2014) 0.327327 \n", + "'Hellboy': The Seeds of Creation (2004) 0.000000 \n", + "'Round Midnight (1986) 0.000000 \n", + "\n", + "title ¡Three Amigos! (1986) \\\n", + "title \n", + "'71 (2014) 0.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 \n", + "'Round Midnight (1986) 0.0 \n", + "\n", + "title À nous la liberté (Freedom for Us) (1931) \n", + "title \n", + "'71 (2014) 0.0 \n", + "'Hellboy': The Seeds of Creation (2004) 0.0 \n", + "'Round Midnight (1986) 0.0 \n", + "\n", + "[3 rows x 9719 columns]" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from sklearn.metrics.pairwise import cosine_similarity\n", + "\n", + "item_sim = cosine_similarity(ratings_matrix_T, ratings_matrix_T)\n", + "item_sim_df = pd.DataFrame(data=item_sim, index=ratings_matrix.columns,\n", + " columns=ratings_matrix.columns)\n", + "print(item_sim_df.shape)\n", + "item_sim_df.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "29cae598-890f-419f-9535-561707ac53f3", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "title\n", + "Godfather, The (1972) 1.000000\n", + "Godfather: Part II, The (1974) 0.821773\n", + "Goodfellas (1990) 0.664841\n", + "One Flew Over the Cuckoo's Nest (1975) 0.620536\n", + "Star Wars: Episode IV - A New Hope (1977) 0.595317\n", + "Fargo (1996) 0.588614\n", + "Name: Godfather, The (1972), dtype: float64" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "item_sim_df[\"Godfather, The (1972)\"].sort_values(ascending=False)[:6]" + ] + }, + { + "cell_type": "markdown", + "id": "192c4785-816c-4bb9-9ee1-5c0239e76931", + "metadata": {}, + "source": [ + "대부를 제외하면 대부-2편이 가장 유사도가 높음. 이후 좋은 친구들(Goodfellas)\n", + "장르가 완전히 다른 영화도 유사도가 매우 높게 나타남 : 스타워즈 1편, 뻐꾸기 둥지 위로 날아간 새 등" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "id": "8fc9ac82-6553-48f9-b47b-6cc54196e55e", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "title\n", + "Dark Knight, The (2008) 0.727263\n", + "Inglourious Basterds (2009) 0.646103\n", + "Shutter Island (2010) 0.617736\n", + "Dark Knight Rises, The (2012) 0.617504\n", + "Fight Club (1999) 0.615417\n", + "Name: Inception (2010), dtype: float64" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "item_sim_df[\"Inception (2010)\"].sort_values(ascending=False)[1:6]" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "id": "2868db94-9ffe-4d2f-ad5a-717d98349d6d", + "metadata": {}, + "outputs": [], + "source": [ + "def predict_rating(ratings_arr, item_sim_arr ):\n", + " ratings_pred = ratings_arr.dot(item_sim_arr)/ np.array([np.abs(item_sim_arr).sum(axis=1)])\n", + " return ratings_pred" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "id": "324ba7c0-4786-4efd-a1fe-b28ac2cab02a", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
title'71 (2014)'Hellboy': The Seeds of Creation (2004)'Round Midnight (1986)'Salem's Lot (2004)'Til There Was You (1997)'Tis the Season for Love (2015)'burbs, The (1989)'night Mother (1986)(500) Days of Summer (2009)*batteries not included (1987)...Zulu (2013)[REC] (2007)[REC]² (2009)[REC]³ 3 Génesis (2012)anohana: The Flower We Saw That Day - The Movie (2013)eXistenZ (1999)xXx (2002)xXx: State of the Union (2005)¡Three Amigos! (1986)À nous la liberté (Freedom for Us) (1931)
userId
10.0703450.5778550.3216960.2270550.2069580.1946150.2498830.1025420.1570840.178197...0.1136080.1817380.1339620.1285740.0061790.2120700.1929210.1360240.2929550.720347
20.0182600.0427440.0188610.0000000.0000000.0359950.0134130.0023140.0322130.014863...0.0156400.0208550.0201190.0157450.0499830.0148760.0216160.0245280.0175630.000000
30.0118840.0302790.0644370.0037620.0037490.0027220.0146250.0020850.0056660.006272...0.0069230.0116650.0118000.0122250.0000000.0081940.0070170.0092290.0104200.084501
\n", + "

3 rows × 9719 columns

\n", + "
" + ], + "text/plain": [ + "title '71 (2014) 'Hellboy': The Seeds of Creation (2004) \\\n", + "userId \n", + "1 0.070345 0.577855 \n", + "2 0.018260 0.042744 \n", + "3 0.011884 0.030279 \n", + "\n", + "title 'Round Midnight (1986) 'Salem's Lot (2004) \\\n", + "userId \n", + "1 0.321696 0.227055 \n", + "2 0.018861 0.000000 \n", + "3 0.064437 0.003762 \n", + "\n", + "title 'Til There Was You (1997) 'Tis the Season for Love (2015) \\\n", + "userId \n", + "1 0.206958 0.194615 \n", + "2 0.000000 0.035995 \n", + "3 0.003749 0.002722 \n", + "\n", + "title 'burbs, The (1989) 'night Mother (1986) (500) Days of Summer (2009) \\\n", + "userId \n", + "1 0.249883 0.102542 0.157084 \n", + "2 0.013413 0.002314 0.032213 \n", + "3 0.014625 0.002085 0.005666 \n", + "\n", + "title *batteries not included (1987) ... Zulu (2013) [REC] (2007) \\\n", + "userId ... \n", + "1 0.178197 ... 0.113608 0.181738 \n", + "2 0.014863 ... 0.015640 0.020855 \n", + "3 0.006272 ... 0.006923 0.011665 \n", + "\n", + "title [REC]² (2009) [REC]³ 3 Génesis (2012) \\\n", + "userId \n", + "1 0.133962 0.128574 \n", + "2 0.020119 0.015745 \n", + "3 0.011800 0.012225 \n", + "\n", + "title anohana: The Flower We Saw That Day - The Movie (2013) \\\n", + "userId \n", + "1 0.006179 \n", + "2 0.049983 \n", + "3 0.000000 \n", + "\n", + "title eXistenZ (1999) xXx (2002) xXx: State of the Union (2005) \\\n", + "userId \n", + "1 0.212070 0.192921 0.136024 \n", + "2 0.014876 0.021616 0.024528 \n", + "3 0.008194 0.007017 0.009229 \n", + "\n", + "title ¡Three Amigos! (1986) À nous la liberté (Freedom for Us) (1931) \n", + "userId \n", + "1 0.292955 0.720347 \n", + "2 0.017563 0.000000 \n", + "3 0.010420 0.084501 \n", + "\n", + "[3 rows x 9719 columns]" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#개인화된 예측 평점 구하기\n", + "ratings_pred = predict_rating(ratings_matrix.values , item_sim_df.values)\n", + "ratings_pred_matrix = pd.DataFrame(data=ratings_pred, index= ratings_matrix.index,\n", + " columns = ratings_matrix.columns)\n", + "ratings_pred_matrix.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "0989084d-0248-415f-a8eb-c87c907a270c", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "아이템 기반 모든 인접 이웃 MSE: 9.895354759094706\n" + ] + } + ], + "source": [ + "from sklearn.metrics import mean_squared_error\n", + "\n", + "# 사용자가 평점을 부여한 영화에 대해서만 예측 성능 평가 MSE 구함\n", + "def get_mse(pred, actual):\n", + " # Ignore nonzero terms.\n", + " pred = pred[actual.nonzero()].flatten()\n", + " actual = actual[actual.nonzero()].flatten()\n", + " return mean_squared_error(pred, actual)\n", + "\n", + "print('아이템 기반 모든 인접 이웃 MSE: ', get_mse(ratings_pred, ratings_matrix.values ))" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "id": "c7b6768d-1b9a-4853-ac54-609901d2cd2f", + "metadata": {}, + "outputs": [], + "source": [ + "def predict_rating_topsim(ratings_arr, item_sim_arr, n=20):\n", + " # 사용자-아이템 평점 행렬 크기만큼 0으로 채운 예측 행렬 초기화\n", + " pred = np.zeros(ratings_arr.shape)\n", + "\n", + " # 사용자-아이템 평점 행렬의 열 크기만큼 Loop 수행. \n", + " for col in range(ratings_arr.shape[1]):\n", + " # 유사도 행렬에서 유사도가 큰 순으로 n개 데이터 행렬의 index 반환\n", + " top_n_items = [np.argsort(item_sim_arr[:, col])[:-n-1:-1]]\n", + " # 개인화된 예측 평점을 계산\n", + " for row in range(ratings_arr.shape[0]):\n", + " pred[row, col] = item_sim_arr[col, :][top_n_items].dot(ratings_arr[row, :][top_n_items].T) \n", + " pred[row, col] /= np.sum(np.abs(item_sim_arr[col, :][top_n_items])) \n", + " return pred" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "id": "d132680f-e1e6-4b8a-9de7-0fff0fe73c79", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "아이템 기반 인접 TOP-20 이웃 MSE: 3.694999233129397\n" + ] + } + ], + "source": [ + "ratings_pred = predict_rating_topsim(ratings_matrix.values , item_sim_df.values, n=20)\n", + "print('아이템 기반 인접 TOP-20 이웃 MSE: ', get_mse(ratings_pred, ratings_matrix.values ))\n", + "\n", + "ratings_pred_matrix = pd.DataFrame(data=ratings_pred, index= ratings_matrix.index,\n", + " columns = ratings_matrix.columns)" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "id": "6488cf5a-27aa-43a0-b28b-72b4b3b0a26c", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "title\n", + "Adaptation (2002) 5.0\n", + "Citizen Kane (1941) 5.0\n", + "Raiders of the Lost Ark (Indiana Jones and the Raiders of the Lost Ark) (1981) 5.0\n", + "Producers, The (1968) 5.0\n", + "Lord of the Rings: The Two Towers, The (2002) 5.0\n", + "Lord of the Rings: The Fellowship of the Ring, The (2001) 5.0\n", + "Back to the Future (1985) 5.0\n", + "Austin Powers in Goldmember (2002) 5.0\n", + "Minority Report (2002) 4.0\n", + "Witness (1985) 4.0\n", + "Name: 9, dtype: float64" + ] + }, + "execution_count": 47, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "user_rating_id = ratings_matrix.loc[9, :]\n", + "user_rating_id[ user_rating_id > 0].sort_values(ascending=False)[:10]" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "id": "0eb2ebc2-1f30-4b19-830a-767178d4c8b8", + "metadata": {}, + "outputs": [], + "source": [ + "def get_unseen_movies(ratings_matrix, userId):\n", + " user_rating = ratings_matrix.loc[userId,:]\n", + " \n", + " # user_rating이 0보다 크면 기존에 관람한 영화임. 대상 index를 추출하여 list 객체로 만듬\n", + " already_seen = user_rating[ user_rating > 0].index.tolist()\n", + " \n", + " # 모든 영화명을 list 객체로 만듬. \n", + " movies_list = ratings_matrix.columns.tolist()\n", + " \n", + " # list comprehension으로 already_seen에 해당하는 movie는 movies_list에서 제외함. \n", + " unseen_list = [ movie for movie in movies_list if movie not in already_seen]\n", + " \n", + " return unseen_list" + ] + }, + { + "cell_type": "markdown", + "id": "18276e66-65e9-4dfa-abfa-9a2598f9f281", + "metadata": {}, + "source": [ + "-> 사용자가 이미 평점을 준 영화를 제외하고 추천할 수 있도록 평점을 주지 않은 영화를 리스트 객체로 반환하는 함수" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "id": "08d63e35-8a85-4e37-9913-c97510529bd0", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
pred_score
title
Shrek (2001)0.866202
Spider-Man (2002)0.857854
Last Samurai, The (2003)0.817473
Indiana Jones and the Temple of Doom (1984)0.816626
Matrix Reloaded, The (2003)0.800990
Harry Potter and the Sorcerer's Stone (a.k.a. Harry Potter and the Philosopher's Stone) (2001)0.765159
Gladiator (2000)0.740956
Matrix, The (1999)0.732693
Pirates of the Caribbean: The Curse of the Black Pearl (2003)0.689591
Lord of the Rings: The Return of the King, The (2003)0.676711
\n", + "
" + ], + "text/plain": [ + " pred_score\n", + "title \n", + "Shrek (2001) 0.866202\n", + "Spider-Man (2002) 0.857854\n", + "Last Samurai, The (2003) 0.817473\n", + "Indiana Jones and the Temple of Doom (1984) 0.816626\n", + "Matrix Reloaded, The (2003) 0.800990\n", + "Harry Potter and the Sorcerer's Stone (a.k.a. Harry Potter and the Philosopher's Stone) (2001) 0.765159\n", + "Gladiator (2000) 0.740956\n", + "Matrix, The (1999) 0.732693\n", + "Pirates of the Caribbean: The Curse of the Black Pearl (2003) 0.689591\n", + "Lord of the Rings: The Return of the King, The (2003) 0.676711" + ] + }, + "execution_count": 50, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def recomm_movie_by_userid(pred_df, userId, unseen_list, top_n=10):\n", + " # 예측 평점 DataFrame에서 사용자id index와 unseen_list로 들어온 영화명 컬럼을 추출하여\n", + " # 가장 예측 평점이 높은 순으로 정렬함. \n", + " recomm_movies = pred_df.loc[userId, unseen_list].sort_values(ascending=False)[:top_n]\n", + " return recomm_movies\n", + " \n", + "# 사용자가 관람하지 않는 영화명 추출 \n", + "unseen_list = get_unseen_movies(ratings_matrix, 9)\n", + "\n", + "# 아이템 기반의 인접 이웃 협업 필터링으로 영화 추천 \n", + "recomm_movies = recomm_movie_by_userid(ratings_pred_matrix, 9, unseen_list, top_n=10)\n", + "\n", + "# 평점 데이타를 DataFrame으로 생성. \n", + "recomm_movies = pd.DataFrame(data=recomm_movies.values,index=recomm_movies.index,columns=['pred_score'])\n", + "recomm_movies" + ] + }, + { + "cell_type": "markdown", + "id": "aec98111-4284-4720-89ef-7cee3ac0cb57", + "metadata": {}, + "source": [ + "-> ‘슈렉’, ‘스파이더 맨’, ‘인디아나 존스-2편’, ‘매트릭스’ 등 다양하지만 높은 흥행성을 가진 작품이 추천" + ] + }, + { + "cell_type": "markdown", + "id": "480ed080-e62b-43b3-955c-f46ed8179f19", + "metadata": {}, + "source": [ + "9.7 행렬 분해를 이용한 잠재 요인 협업 필터링 실습" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "id": "8d37584b-22e1-4c74-b1e4-bf216cfabf33", + "metadata": {}, + "outputs": [], + "source": [ + "def matrix_factorization(R, K, steps=200, learning_rate=0.01, r_lambda = 0.01):\n", + " num_users, num_items = R.shape\n", + " # P와 Q 매트릭스의 크기를 지정하고 정규분포를 가진 랜덤한 값으로 입력합니다. \n", + " np.random.seed(1)\n", + " P = np.random.normal(scale=1./K, size=(num_users, K))\n", + " Q = np.random.normal(scale=1./K, size=(num_items, K))\n", + " \n", + " # R > 0 인 행 위치, 열 위치, 값을 non_zeros 리스트 객체에 저장. \n", + " non_zeros = [ (i, j, R[i,j]) for i in range(num_users) for j in range(num_items) if R[i,j] > 0 ]\n", + " \n", + " # SGD기법으로 P와 Q 매트릭스를 계속 업데이트. \n", + " for step in range(steps):\n", + " for i, j, r in non_zeros:\n", + " # 실제 값과 예측 값의 차이인 오류 값 구함\n", + " eij = r - np.dot(P[i, :], Q[j, :].T)\n", + " # Regularization을 반영한 SGD 업데이트 공식 적용\n", + " P[i,:] = P[i,:] + learning_rate*(eij * Q[j, :] - r_lambda*P[i,:])\n", + " Q[j,:] = Q[j,:] + learning_rate*(eij * P[i, :] - r_lambda*Q[j,:])\n", + " \n", + " rmse = get_rmse(R, P, Q, non_zeros)\n", + " if (step % 10) == 0 :\n", + " print(\"### iteration step : \", step,\" rmse : \", rmse)\n", + " \n", + " return P, Q" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "id": "20482bbe-1bf4-40ec-bde9-bcd8ccc98c87", + "metadata": {}, + "outputs": [], + "source": [ + "#앞에서 쓴 get_rmse 정의\n", + "import numpy as np\n", + "from sklearn.metrics import mean_squared_error\n", + "\n", + "def get_rmse(R, P, Q, non_zeros):\n", + " error = 0\n", + " # 두개의 분해된 행렬 P와 Q.T의 내적 곱으로 예측 R 행렬 생성\n", + " full_pred_matrix = np.dot(P, Q.T)\n", + " \n", + " # 실제 R 행렬에서 널이 아닌 값의 위치 인덱스 추출하여 실제 R 행렬과 예측 행렬의 RMSE 추출\n", + " x_non_zero_ind = [non_zero[0] for non_zero in non_zeros]\n", + " y_non_zero_ind = [non_zero[1] for non_zero in non_zeros]\n", + " R_non_zeros = R[x_non_zero_ind, y_non_zero_ind]\n", + " \n", + " full_pred_matrix_non_zeros = full_pred_matrix[x_non_zero_ind, y_non_zero_ind]\n", + " \n", + " mse = mean_squared_error(R_non_zeros, full_pred_matrix_non_zeros)\n", + " rmse = np.sqrt(mse)\n", + " \n", + " return rmse" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "id": "9f76758b-cac5-4635-af21-f5b0d8b19827", + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "movies = pd.read_csv('./ml-latest-small/movies.csv')\n", + "ratings = pd.read_csv('./ml-latest-small/ratings.csv')\n", + "ratings = ratings[['userId', 'movieId', 'rating']]\n", + "ratings_matrix = ratings.pivot_table('rating', index='userId', columns='movieId')\n", + "\n", + "# title 컬럼을 얻기 이해 movies 와 조인 수행\n", + "rating_movies = pd.merge(ratings, movies, on='movieId')\n", + "\n", + "# columns='title' 로 title 컬럼으로 pivot 수행. \n", + "ratings_matrix = rating_movies.pivot_table('rating', index='userId', columns='title')" + ] + }, + { + "cell_type": "markdown", + "id": "5f1c5b50-0dbe-439a-97b7-11711f12d41d", + "metadata": {}, + "source": [ + "사용자-아이템 평점 행렬을 행렬 분해\n", + "SGD 반복 횟수는 200회만 지정, 잠재요인 차원 K는 50, 학습률과 L2 Regularization 계수는 모두 0.01 로 설정하고 수행" + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "id": "0468802b-84eb-4e8e-bd29-276995e524fb", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "### iteration step : 0 rmse : 2.9023619751336867\n", + "### iteration step : 10 rmse : 0.7335768591017927\n", + "### iteration step : 20 rmse : 0.5115539026853442\n", + "### iteration step : 30 rmse : 0.37261628282537446\n", + "### iteration step : 40 rmse : 0.29608182991810134\n", + "### iteration step : 50 rmse : 0.2520353192341642\n", + "### iteration step : 60 rmse : 0.22487503275269854\n", + "### iteration step : 70 rmse : 0.20685455302331537\n", + "### iteration step : 80 rmse : 0.19413418783028683\n", + "### iteration step : 90 rmse : 0.18470082002720403\n", + "### iteration step : 100 rmse : 0.17742927527209104\n", + "### iteration step : 110 rmse : 0.1716522696470749\n", + "### iteration step : 120 rmse : 0.1669518194687172\n", + "### iteration step : 130 rmse : 0.16305292191997542\n", + "### iteration step : 140 rmse : 0.15976691929679643\n", + "### iteration step : 150 rmse : 0.1569598699945732\n", + "### iteration step : 160 rmse : 0.15453398186715428\n", + "### iteration step : 170 rmse : 0.15241618551077643\n", + "### iteration step : 180 rmse : 0.1505508073962831\n", + "### iteration step : 190 rmse : 0.1488947091323209\n" + ] + } + ], + "source": [ + "P, Q = matrix_factorization(ratings_matrix.values, K=50, steps=200, learning_rate=0.01, r_lambda = 0.01)\n", + "pred_matrix = np.dot(P, Q.T)" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "id": "bb4776dc-422a-4df6-9ac8-ecfa07dad17c", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
title'71 (2014)'Hellboy': The Seeds of Creation (2004)'Round Midnight (1986)'Salem's Lot (2004)'Til There Was You (1997)'Tis the Season for Love (2015)'burbs, The (1989)'night Mother (1986)(500) Days of Summer (2009)*batteries not included (1987)...Zulu (2013)[REC] (2007)[REC]² (2009)[REC]³ 3 Génesis (2012)anohana: The Flower We Saw That Day - The Movie (2013)eXistenZ (1999)xXx (2002)xXx: State of the Union (2005)¡Three Amigos! (1986)À nous la liberté (Freedom for Us) (1931)
userId
13.0550844.0920183.5641304.5021673.9812151.2716943.6032742.3332665.0917493.972454...1.4026084.2083823.7059572.7205142.7873313.4750763.2534582.1610874.0104950.859474
23.1701193.6579923.3087074.1665214.3118901.2754694.2379721.9003663.3928593.647421...0.9738113.5282643.3615322.6725352.4044564.2327892.9116021.6345764.1357350.725684
32.3070731.6588531.4435382.2088592.2294860.7807601.9970430.9249082.9707002.551446...0.5203541.7094942.2815961.7828331.6351731.3232762.8875801.0426182.2938900.396941
\n", + "

3 rows × 9719 columns

\n", + "
" + ], + "text/plain": [ + "title '71 (2014) 'Hellboy': The Seeds of Creation (2004) \\\n", + "userId \n", + "1 3.055084 4.092018 \n", + "2 3.170119 3.657992 \n", + "3 2.307073 1.658853 \n", + "\n", + "title 'Round Midnight (1986) 'Salem's Lot (2004) \\\n", + "userId \n", + "1 3.564130 4.502167 \n", + "2 3.308707 4.166521 \n", + "3 1.443538 2.208859 \n", + "\n", + "title 'Til There Was You (1997) 'Tis the Season for Love (2015) \\\n", + "userId \n", + "1 3.981215 1.271694 \n", + "2 4.311890 1.275469 \n", + "3 2.229486 0.780760 \n", + "\n", + "title 'burbs, The (1989) 'night Mother (1986) (500) Days of Summer (2009) \\\n", + "userId \n", + "1 3.603274 2.333266 5.091749 \n", + "2 4.237972 1.900366 3.392859 \n", + "3 1.997043 0.924908 2.970700 \n", + "\n", + "title *batteries not included (1987) ... Zulu (2013) [REC] (2007) \\\n", + "userId ... \n", + "1 3.972454 ... 1.402608 4.208382 \n", + "2 3.647421 ... 0.973811 3.528264 \n", + "3 2.551446 ... 0.520354 1.709494 \n", + "\n", + "title [REC]² (2009) [REC]³ 3 Génesis (2012) \\\n", + "userId \n", + "1 3.705957 2.720514 \n", + "2 3.361532 2.672535 \n", + "3 2.281596 1.782833 \n", + "\n", + "title anohana: The Flower We Saw That Day - The Movie (2013) \\\n", + "userId \n", + "1 2.787331 \n", + "2 2.404456 \n", + "3 1.635173 \n", + "\n", + "title eXistenZ (1999) xXx (2002) xXx: State of the Union (2005) \\\n", + "userId \n", + "1 3.475076 3.253458 2.161087 \n", + "2 4.232789 2.911602 1.634576 \n", + "3 1.323276 2.887580 1.042618 \n", + "\n", + "title ¡Three Amigos! (1986) À nous la liberté (Freedom for Us) (1931) \n", + "userId \n", + "1 4.010495 0.859474 \n", + "2 4.135735 0.725684 \n", + "3 2.293890 0.396941 \n", + "\n", + "[3 rows x 9719 columns]" + ] + }, + "execution_count": 57, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ratings_pred_matrix = pd.DataFrame(data=pred_matrix, index= ratings_matrix.index,\n", + " columns = ratings_matrix.columns)\n", + "\n", + "ratings_pred_matrix.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "id": "a5f155dc-5e5a-4de3-9068-a104355bcfd7", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
pred_score
title
Rear Window (1954)5.704612
South Park: Bigger, Longer and Uncut (1999)5.451100
Rounders (1998)5.298393
Blade Runner (1982)5.244951
Roger & Me (1989)5.191962
Gattaca (1997)5.183179
Ben-Hur (1959)5.130463
Rosencrantz and Guildenstern Are Dead (1990)5.087375
Big Lebowski, The (1998)5.038690
Star Wars: Episode V - The Empire Strikes Back (1980)4.989601
\n", + "
" + ], + "text/plain": [ + " pred_score\n", + "title \n", + "Rear Window (1954) 5.704612\n", + "South Park: Bigger, Longer and Uncut (1999) 5.451100\n", + "Rounders (1998) 5.298393\n", + "Blade Runner (1982) 5.244951\n", + "Roger & Me (1989) 5.191962\n", + "Gattaca (1997) 5.183179\n", + "Ben-Hur (1959) 5.130463\n", + "Rosencrantz and Guildenstern Are Dead (1990) 5.087375\n", + "Big Lebowski, The (1998) 5.038690\n", + "Star Wars: Episode V - The Empire Strikes Back (1980) 4.989601" + ] + }, + "execution_count": 58, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 사용자가 관람하지 않는 영화명 추출 \n", + "unseen_list = get_unseen_movies(ratings_matrix, 9)\n", + "\n", + "# 아이템 기반의 인접 이웃 협업 필터링으로 영화 추천 \n", + "recomm_movies = recomm_movie_by_userid(ratings_pred_matrix, 9, unseen_list, top_n=10)\n", + "\n", + "# 평점 데이타를 DataFrame으로 생성. \n", + "recomm_movies = pd.DataFrame(data=recomm_movies.values,index=recomm_movies.index,columns=['pred_score'])\n", + "recomm_movies" + ] + }, + { + "cell_type": "markdown", + "id": "049d7d63-c0c9-428d-b9c4-2078dd7d87da", + "metadata": {}, + "source": [ + "앞의 결과와 다른 것을 확인할 수 있음!\n", + "이창(Rear Window, 1954), 사우스파크 등이 추천됨" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python (myenv)", + "language": "python", + "name": "myenv" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.8" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git "a/Week16_\354\230\210\354\212\265\352\263\274\354\240\234_\352\271\200\354\230\210\353\202\230.ipynb" "b/Week16_\354\230\210\354\212\265\352\263\274\354\240\234_\352\271\200\354\230\210\353\202\230.ipynb" new file mode 100644 index 0000000..4678a93 --- /dev/null +++ "b/Week16_\354\230\210\354\212\265\352\263\274\354\240\234_\352\271\200\354\230\210\353\202\230.ipynb" @@ -0,0 +1,924 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "language_info": { + "name": "python" + } + }, + "cells": [ + { + "cell_type": "markdown", + "source": [ + "SGD를 이용한 행렬 분해" + ], + "metadata": { + "id": "SPi_quxPrkoc" + } + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "id": "2WavR1FYcf6h" + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "# 원본 행렬 R 생성, 분해 행렬 P와 Q 초기화, 잠재요인 차원 K는 3 설정.\n", + "R = np.array([[4, np.nan, np.nan, 2, np.nan ],\n", + " [np.nan, 5, np.nan, 3, 1 ],\n", + " [np.nan, np.nan, 3, 4, 4 ],\n", + " [5, 2, 1, 2, np.nan]])\n", + "num_users, num_items = R.shape\n", + "K=3\n", + "\n", + "# P와 Q 매트릭스의 크기를 지정하고 정규분포를 가진 random한 값으로 입력합니다.\n", + "np.random.seed(1)\n", + "P = np.random.normal(scale=1./K, size=(num_users, K))\n", + "Q = np.random.normal(scale=1./K, size=(num_items, K))" + ] + }, + { + "cell_type": "code", + "source": [ + "from sklearn.metrics import mean_squared_error\n", + "\n", + "def get_rmse(R, P, Q, non_zeros):\n", + " error = 0\n", + " # 두개의 분해된 행렬 P와 Q.T의 내적으로 예측 R 행렬 생성\n", + " full_pred_matrix = np.dot(P, Q.T)\n", + "\n", + " # 실제 R 행렬에서 널이 아닌 값의 위치 인덱스 추출하여 실제 R 행렬과 예측 행렬의 RMSE 추출\n", + " x_non_zero_ind = [non_zero[0] for non_zero in non_zeros]\n", + " y_non_zero_ind = [non_zero[1] for non_zero in non_zeros]\n", + " R_non_zeros = R[x_non_zero_ind, y_non_zero_ind]\n", + " full_pred_matrix_non_zeros = full_pred_matrix[x_non_zero_ind, y_non_zero_ind]\n", + "\n", + " mse = mean_squared_error(R_non_zeros, full_pred_matrix_non_zeros)\n", + " rmse = np.sqrt(mse)\n", + "\n", + " return rmse" + ], + "metadata": { + "id": "LokzAl1lrvn2" + }, + "execution_count": 3, + "outputs": [] + }, + { + "cell_type": "code", + "source": [ + "non_zeros = [ (i, j, R[i,j]) for i in range(num_users) for j in range(num_items) if R[i,j] > 0 ]\n", + "\n", + "steps=1000\n", + "learning_rate=0.01\n", + "r_lambda=0.01\n", + "\n", + "# SGD 기법으로 P와 Q 매트릭스를 계속 업데이트.\n", + "for step in range(steps):\n", + " for i, j, r in non_zeros:\n", + " # 실제 값과 예측 값의 차이인 오류 값 구함\n", + " eij = r - np.dot(P[i, :], Q[j, :].T)\n", + " # Regularization을 반영한 SGD 업데이트 공식 적용\n", + " P[i,:] = P[i,:] + learning_rate*(eij * Q[j, :] - r_lambda*P[i,:])\n", + " Q[j,:] = Q[j,:] + learning_rate*(eij * P[i, :] - r_lambda*Q[j,:])\n", + "\n", + " rmse = get_rmse(R, P, Q, non_zeros)\n", + " if (step % 50) == 0 :\n", + " print(\"### iteration step : \", step,\" rmse : \", rmse)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "8iCO-XmDr_HF", + "outputId": "90a2fa39-263a-4b27-d51d-9554ef4d684a" + }, + "execution_count": 4, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "### iteration step : 0 rmse : 3.2388050277987723\n", + "### iteration step : 50 rmse : 0.4876723101369648\n", + "### iteration step : 100 rmse : 0.1564340384819247\n", + "### iteration step : 150 rmse : 0.07455141311978046\n", + "### iteration step : 200 rmse : 0.04325226798579314\n", + "### iteration step : 250 rmse : 0.029248328780878973\n", + "### iteration step : 300 rmse : 0.022621116143829466\n", + "### iteration step : 350 rmse : 0.019493636196525135\n", + "### iteration step : 400 rmse : 0.018022719092132704\n", + "### iteration step : 450 rmse : 0.01731968595344266\n", + "### iteration step : 500 rmse : 0.016973657887570753\n", + "### iteration step : 550 rmse : 0.016796804595895633\n", + "### iteration step : 600 rmse : 0.01670132290188466\n", + "### iteration step : 650 rmse : 0.01664473691247669\n", + "### iteration step : 700 rmse : 0.016605910068210026\n", + "### iteration step : 750 rmse : 0.016574200475705\n", + "### iteration step : 800 rmse : 0.01654431582921597\n", + "### iteration step : 850 rmse : 0.01651375177473524\n", + "### iteration step : 900 rmse : 0.01648146573819501\n", + "### iteration step : 950 rmse : 0.016447171683479155\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "pred_matrix = np.dot(P, Q.T)\n", + "print('예측 행렬:\\n', np.round(pred_matrix, 3))" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "8xXR7q0rsFpm", + "outputId": "4b29bfb1-8296-4007-bbc5-052a52174963" + }, + "execution_count": 5, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "예측 행렬:\n", + " [[3.991 0.897 1.306 2.002 1.663]\n", + " [6.696 4.978 0.979 2.981 1.003]\n", + " [6.677 0.391 2.987 3.977 3.986]\n", + " [4.968 2.005 1.006 2.017 1.14 ]]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Suprise" + ], + "metadata": { + "id": "u3K3-xLOsNMR" + } + }, + { + "cell_type": "code", + "source": [ + "!pip install scikit-surprise" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "vKXA15wzsI2m", + "outputId": "8306644f-f174-463f-bacf-20403b87e31a" + }, + "execution_count": 7, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Collecting scikit-surprise\n", + " Downloading scikit_surprise-1.1.4.tar.gz (154 kB)\n", + "\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/154.4 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m \u001b[32m153.6/154.4 kB\u001b[0m \u001b[31m5.1 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m154.4/154.4 kB\u001b[0m \u001b[31m3.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[?25h Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n", + " Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n", + " Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n", + "Requirement already satisfied: joblib>=1.2.0 in /usr/local/lib/python3.11/dist-packages (from scikit-surprise) (1.5.1)\n", + "Requirement already satisfied: numpy>=1.19.5 in /usr/local/lib/python3.11/dist-packages (from scikit-surprise) (2.0.2)\n", + "Requirement already satisfied: scipy>=1.6.0 in /usr/local/lib/python3.11/dist-packages (from scikit-surprise) (1.15.3)\n", + "Building wheels for collected packages: scikit-surprise\n", + " Building wheel for scikit-surprise (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n", + " Created wheel for scikit-surprise: filename=scikit_surprise-1.1.4-cp311-cp311-linux_x86_64.whl size=2469537 sha256=6a0efb56cfcb081fa3b74ab3b3f08877fcfea4ee7b8286790b258676bb9944f3\n", + " Stored in directory: /root/.cache/pip/wheels/2a/8f/6e/7e2899163e2d85d8266daab4aa1cdabec7a6c56f83c015b5af\n", + "Successfully built scikit-surprise\n", + "Installing collected packages: scikit-surprise\n", + "Successfully installed scikit-surprise-1.1.4\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "!pip install numpy==1.26.4" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "UYNwl9Pos96G", + "outputId": "a03d07ed-a50f-457d-cd3f-0f4d360627bf" + }, + "execution_count": 1, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Requirement already satisfied: numpy==1.26.4 in /usr/local/lib/python3.11/dist-packages (1.26.4)\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "import numpy as np\n", + "print(np.__version__)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "UtazJapQtIeY", + "outputId": "4b341785-f018-4e25-b945-4b8b71bf4efc" + }, + "execution_count": 2, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "1.26.4\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "from surprise import SVD\n", + "from surprise import Dataset\n", + "from surprise import accuracy\n", + "from surprise.model_selection import train_test_split" + ], + "metadata": { + "id": "SBzHvV2-sWKz" + }, + "execution_count": 3, + "outputs": [] + }, + { + "cell_type": "code", + "source": [ + "data = Dataset.load_builtin('ml-100k')\n", + "trainset, testset = train_test_split(data, test_size=.25, random_state=0)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "JW07MAodtUec", + "outputId": "718db389-6f12-462a-d688-e7b482d451b2" + }, + "execution_count": 4, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Dataset ml-100k could not be found. Do you want to download it? [Y/n] Y\n", + "Trying to download dataset from https://files.grouplens.org/datasets/movielens/ml-100k.zip...\n", + "Done! Dataset ml-100k has been saved to /root/.surprise_data/ml-100k\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "algo = SVD(random_state=0)\n", + "algo.fit(trainset)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "ynjwiHpQswpJ", + "outputId": "ee390185-8dff-4ec6-dce8-070cbb8f4a64" + }, + "execution_count": 6, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "" + ] + }, + "metadata": {}, + "execution_count": 6 + } + ] + }, + { + "cell_type": "code", + "source": [ + "predictions = algo.test( testset )\n", + "print('prediction type :',type(predictions), ' size:',len(predictions))\n", + "print('prediction 결과의 최초 5개 추출')\n", + "predictions[:5]" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "BPSO_A-AtbNf", + "outputId": "beb81ed1-e8b8-4914-d75c-1a921178a8bc" + }, + "execution_count": 7, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "prediction type : size: 25000\n", + "prediction 결과의 최초 5개 추출\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "[Prediction(uid='120', iid='282', r_ui=4.0, est=3.5114147666251547, details={'was_impossible': False}),\n", + " Prediction(uid='882', iid='291', r_ui=4.0, est=3.573872419581491, details={'was_impossible': False}),\n", + " Prediction(uid='535', iid='507', r_ui=5.0, est=4.033583485472447, details={'was_impossible': False}),\n", + " Prediction(uid='697', iid='244', r_ui=5.0, est=3.8463639495936905, details={'was_impossible': False}),\n", + " Prediction(uid='751', iid='385', r_ui=4.0, est=3.1807542478219157, details={'was_impossible': False})]" + ] + }, + "metadata": {}, + "execution_count": 7 + } + ] + }, + { + "cell_type": "code", + "source": [ + "[ (pred.uid, pred.iid, pred.est) for pred in predictions[:3] ]" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "Nhz3FxIxtgAq", + "outputId": "88e7d4cc-6219-488f-e41c-7670a1848b1f" + }, + "execution_count": 8, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "[('120', '282', 3.5114147666251547),\n", + " ('882', '291', 3.573872419581491),\n", + " ('535', '507', 4.033583485472447)]" + ] + }, + "metadata": {}, + "execution_count": 8 + } + ] + }, + { + "cell_type": "code", + "source": [ + "uid = str(196)\n", + "iid = str(302)\n", + "pred = algo.predict(uid, iid)\n", + "print(pred)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "nnC5j2sWt36B", + "outputId": "6c044afa-782c-4051-b9ef-b3ec8d172795" + }, + "execution_count": 9, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "user: 196 item: 302 r_ui = None est = 4.49 {'was_impossible': False}\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "accuracy.rmse(predictions)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "n3SbyYmat7ey", + "outputId": "a2331d51-b250-406d-ed3a-8c20d2794300" + }, + "execution_count": 11, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "RMSE: 0.9467\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "0.9466860806937948" + ] + }, + "metadata": {}, + "execution_count": 11 + } + ] + }, + { + "cell_type": "code", + "source": [ + "from google.colab import drive\n", + "drive.mount('/content/drive')" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "mvkpNKpywYd8", + "outputId": "e45eec06-2912-4a0e-e98c-03a85f1212c9" + }, + "execution_count": 20, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "import pandas as pd\n", + "\n", + "ratings = pd.read_csv('/content/drive/My Drive/ratings.csv')\n", + "ratings.to_csv('/content/drive/My Drive/ratings_noh.csv', index=False, header=False)" + ], + "metadata": { + "id": "XQRyNJ-0wd2I" + }, + "execution_count": 22, + "outputs": [] + }, + { + "cell_type": "code", + "source": [ + "from surprise import Reader\n", + "\n", + "reader = Reader(line_format='user item rating timestamp', sep=',', rating_scale=(0.5, 5))\n", + "data=Dataset.load_from_file('/content/drive/My Drive/ratings_noh.csv',reader=reader)" + ], + "metadata": { + "id": "Ssh2hdFEvRIl" + }, + "execution_count": 24, + "outputs": [] + }, + { + "cell_type": "code", + "source": [ + "trainset, testset = train_test_split(data, test_size=.25, random_state=0)\n", + "\n", + "# 수행시마다 동일한 결과 도출을 위해 random_state 설정\n", + "algo = SVD(n_factors=50, random_state=0)\n", + "\n", + "# 학습 데이터 세트로 학습 후 테스트 데이터 세트로 평점 예측 후 RMSE 평가\n", + "algo.fit(trainset)\n", + "predictions = algo.test( testset )\n", + "accuracy.rmse(predictions)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "ojkXcOXXyY-k", + "outputId": "1453f28b-bcce-41bf-ed05-6420d67e19dc" + }, + "execution_count": 25, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "RMSE: 0.8682\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "0.8681952927143516" + ] + }, + "metadata": {}, + "execution_count": 25 + } + ] + }, + { + "cell_type": "code", + "source": [ + "import pandas as pd\n", + "from surprise import Reader, Dataset\n", + "\n", + "ratings = pd.read_csv('/content/drive/My Drive/ratings.csv')\n", + "read = Reader(rating_scale = (0.5, 5.0))\n", + "\n", + "#ratings DataFrame에서 칼럼은 사용자 아이디, 아이템 아이디, 평점 순서를 지켜야함\n", + "data = Dataset.load_from_df(ratings[['userId', 'movieId', 'rating']], reader)\n", + "trainset, testset = train_test_split(data, test_size = 0.25, random_state = 0)\n", + "algo = SVD(n_factors = 50, random_state = 0)\n", + "algo.fit(trainset)\n", + "predictions = algo.test(testset)\n", + "accuracy.rmse(predictions)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "m_XXAH2KyhIv", + "outputId": "68957415-e480-44f1-c27f-2fd710af0779" + }, + "execution_count": 27, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "RMSE: 0.8682\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "0.8681952927143516" + ] + }, + "metadata": {}, + "execution_count": 27 + } + ] + }, + { + "cell_type": "code", + "source": [ + "from surprise.model_selection import cross_validate\n", + "\n", + "# 판다스 DataFrame에서 Surprise 데이터 세트로 데이터 로딩\n", + "ratings = pd.read_csv('/content/drive/My Drive/ratings.csv')\n", + "reader = Reader(rating_scale=(0.5, 5.0))\n", + "data = Dataset.load_from_df(ratings[['userId', 'movieId', 'rating']], reader)\n", + "\n", + "algo = SVD(random_state=0)\n", + "cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=5, verbose=True)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "TaIFUvl9z0fk", + "outputId": "3c11838f-ae36-452b-dd3b-e50ff1280958" + }, + "execution_count": 28, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Evaluating RMSE, MAE of algorithm SVD on 5 split(s).\n", + "\n", + " Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean Std \n", + "RMSE (testset) 0.8732 0.8845 0.8723 0.8759 0.8671 0.8746 0.0057 \n", + "MAE (testset) 0.6688 0.6811 0.6714 0.6733 0.6623 0.6714 0.0061 \n", + "Fit time 1.81 1.86 1.86 1.40 1.52 1.69 0.19 \n", + "Test time 0.10 0.42 0.10 0.12 0.29 0.21 0.13 \n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "{'test_rmse': array([0.87320257, 0.88448915, 0.87230917, 0.87587848, 0.86713577]),\n", + " 'test_mae': array([0.66875498, 0.68113196, 0.67138592, 0.67334625, 0.66228778]),\n", + " 'fit_time': (1.8056704998016357,\n", + " 1.8638763427734375,\n", + " 1.8628664016723633,\n", + " 1.4039747714996338,\n", + " 1.521538257598877),\n", + " 'test_time': (0.0969231128692627,\n", + " 0.4235539436340332,\n", + " 0.10028314590454102,\n", + " 0.11871576309204102,\n", + " 0.2872450351715088)}" + ] + }, + "metadata": {}, + "execution_count": 28 + } + ] + }, + { + "cell_type": "code", + "source": [ + "from surprise.model_selection import GridSearchCV\n", + "\n", + "# 최적화할 파라미터를 딕셔너리 형태로 지정\n", + "param_grid = {'n_epochs': [20, 40, 60], 'n_factors': [50, 100, 200] }\n", + "\n", + "# CV를 3개 폴드 세트로 지정, 성능 평가는 rmse, mse로 수행하도록 GridSearchCV 구성\n", + "gs = GridSearchCV(SVD, param_grid, measures=['rmse', 'mae'], cv=3)\n", + "gs.fit(data)\n", + "\n", + "# 최고 RMSE Evaluation 점수와 그때의 하이퍼 파라미터\n", + "print(gs.best_score['rmse'])\n", + "print(gs.best_params['rmse'])" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "nENGA5rw1CAF", + "outputId": "c50fbf95-3c2f-4346-f1ea-1ef88183d0e4" + }, + "execution_count": 29, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "0.8772574994261989\n", + "{'n_epochs': 20, 'n_factors': 50}\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "#데이터세트를 trainset 클래스 객체로 변환하지 않으면 fit()을 통해 학습 불가\n", + "#데이터를 그대로 fit()에 적용해서 오류남\n", + "data = Dataset.load_from_df(ratings[['userId', 'movieId', 'rating']], reader)\n", + "algo = SVD(n_factors=50, random_state=0)\n", + "algo.fit(data)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 279 + }, + "id": "ptutR2mQ1dIg", + "outputId": "fa17656d-fba2-496e-be55-7e54133fd108" + }, + "execution_count": 30, + "outputs": [ + { + "output_type": "error", + "ename": "AttributeError", + "evalue": "'DatasetAutoFolds' object has no attribute 'n_users'", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m/tmp/ipython-input-30-2037329450.py\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mdata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mDataset\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mload_from_df\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mratings\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'userId'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'movieId'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'rating'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mreader\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0malgo\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mSVD\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mn_factors\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m50\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrandom_state\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0malgo\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfit\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m/usr/local/lib/python3.11/dist-packages/surprise/prediction_algorithms/matrix_factorization.pyx\u001b[0m in \u001b[0;36msurprise.prediction_algorithms.matrix_factorization.SVD.fit\u001b[0;34m()\u001b[0m\n", + "\u001b[0;32m/usr/local/lib/python3.11/dist-packages/surprise/prediction_algorithms/matrix_factorization.pyx\u001b[0m in \u001b[0;36msurprise.prediction_algorithms.matrix_factorization.SVD.sgd\u001b[0;34m()\u001b[0m\n", + "\u001b[0;31mAttributeError\u001b[0m: 'DatasetAutoFolds' object has no attribute 'n_users'" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "from surprise.dataset import DatasetAutoFolds\n", + "\n", + "reader = Reader(line_format='user item rating timestamp', sep=',', rating_scale=(0.5, 5))\n", + "data_folds = DatasetAutoFolds(ratings_file='/content/drive/My Drive/ratings_noh.csv', reader=reader)\n", + "\n", + "#전체 데이터를 학습데이터로 생성함.\n", + "trainset = data_folds.build_full_trainset()" + ], + "metadata": { + "id": "7oswkKxa1t9c" + }, + "execution_count": 31, + "outputs": [] + }, + { + "cell_type": "code", + "source": [ + "algo = SVD(n_epochs=20, n_factors=50, random_state=0)\n", + "algo.fit(trainset)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "7N4wE5CA15K7", + "outputId": "c52e6a19-cd79-44a8-b25e-29cff5c5bb78" + }, + "execution_count": 32, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "" + ] + }, + "metadata": {}, + "execution_count": 32 + } + ] + }, + { + "cell_type": "code", + "source": [ + "# 영화에 대한 상세 속성 정보 DataFrame로딩\n", + "movies = pd.read_csv('/content/drive/My Drive/movies.csv')\n", + "\n", + "# userId=9 의 movieId 데이터 추출하여 movieId=42 데이터가 있는지 확인\n", + "movieIds = ratings[ratings['userId']==9]['movieId']\n", + "if movieIds[movieIds==42].count() == 0:\n", + " print('사용자 아이디 9는 영화 아이디 42의 평점 없음')\n", + "\n", + "print(movies[movies['movieId']==42])" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "4XE2hRGP1766", + "outputId": "8141ecd3-19bf-4d95-f9e7-ebb49de74ef8" + }, + "execution_count": 34, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "사용자 아이디 9는 영화 아이디 42의 평점 없음\n", + " movieId title genres\n", + "38 42 Dead Presidents (1995) Action|Crime|Drama\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "uid = str(9)\n", + "iid = str(42)\n", + "\n", + "pred = algo.predict(uid, iid, verbose=True)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "QOT2fZfy2A68", + "outputId": "28f780ac-3914-49e0-b38f-7874471cf725" + }, + "execution_count": 35, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "user: 9 item: 42 r_ui = None est = 3.13 {'was_impossible': False}\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "-> 추천 예측 평점은 3.13" + ], + "metadata": { + "id": "rzVcdNeU2TDG" + } + }, + { + "cell_type": "code", + "source": [ + "def get_unseen_surprise(ratings, movies, userId):\n", + " #입력값으로 들어온 userId에 해당하는 사용자가 평점을 매긴 모든 영화를 리스트로 생성\n", + " seen_movies = ratings[ratings['userId']== userId]['movieId'].tolist()\n", + " total_movies = movies['movieId'].tolist()\n", + "\n", + " # 모든 영화들의 movieId중 이미 평점을 매긴 영화의 movieId를 제외하여 리스트로 생성\n", + " unseen_movies= [movie for movie in total_movies if movie not in seen_movies]\n", + " print('평점 매긴 영화수:',len(seen_movies), '추천대상 영화수:',len(unseen_movies), \\\n", + " '전체 영화수:',len(total_movies))\n", + "\n", + " return unseen_movies\n", + "\n", + "unseen_movies = get_unseen_surprise(ratings, movies, 9)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "0rWLfO5R2Rdt", + "outputId": "c52adfb6-50ed-4f83-b8d2-8b5d1fde7d47" + }, + "execution_count": 37, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "평점 매긴 영화수: 46 추천대상 영화수: 9696 전체 영화수: 9742\n" + ] + } + ] + }, + { + "cell_type": "code", + "source": [ + "def recomm_movie_by_surprise(algo, userId, unseen_movies, top_n=10):\n", + " # 알고리즘 객체의 predict() 메서드를 평점이 없는 영화에 반복 수행한 후 결과를 list 객체로 저장\n", + " predictions = [algo.predict(str(userId), str(movieId)) for movieId in unseen_movies]\n", + "\n", + " def sortkey_est(pred):\n", + " return pred.est\n", + "\n", + " # sortkey_est( ) 반환값의 내림 차순으로 정렬 수행하고 top_n개의 최상위 값 추출.\n", + " predictions.sort(key=sortkey_est, reverse=True)\n", + " top_predictions= predictions[:top_n]\n", + "\n", + " # top_n으로 추출된 영화의 정보 추출. 영화 아이디, 추천 예상 평점, 제목 추출\n", + " top_movie_ids = [ int(pred.iid) for pred in top_predictions]\n", + " top_movie_rating = [ pred.est for pred in top_predictions]\n", + " top_movie_titles = movies[movies.movieId.isin(top_movie_ids)]['title']\n", + " top_movie_preds = [ (id, title, rating) for id, title, rating in zip(top_movie_ids, top_movie_titles, top_movie_rating)]\n", + "\n", + " return top_movie_preds\n", + "\n", + "unseen_movies = get_unseen_surprise(ratings, movies, 9)\n", + "top_movie_preds = recomm_movie_by_surprise(algo, 9, unseen_movies, top_n=10)\n", + "print('##### Top-10 추천 영화 리스트 #####')\n", + "\n", + "for top_movie in top_movie_preds:\n", + " print(top_movie[1], \":\", top_movie[2])" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "nSB_Nhkk2XzM", + "outputId": "ccfb1f9c-37e7-40d5-e029-63bd692c474b" + }, + "execution_count": 38, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "평점 매긴 영화수: 46 추천대상 영화수: 9696 전체 영화수: 9742\n", + "##### Top-10 추천 영화 리스트 #####\n", + "Usual Suspects, The (1995) : 4.306302135700814\n", + "Star Wars: Episode IV - A New Hope (1977) : 4.281663842987387\n", + "Pulp Fiction (1994) : 4.278152632122759\n", + "Silence of the Lambs, The (1991) : 4.226073566460876\n", + "Godfather, The (1972) : 4.1918097904381995\n", + "Streetcar Named Desire, A (1951) : 4.154746591122657\n", + "Star Wars: Episode V - The Empire Strikes Back (1980) : 4.122016128534504\n", + "Star Wars: Episode VI - Return of the Jedi (1983) : 4.108009609093436\n", + "Goodfellas (1990) : 4.083464936588478\n", + "Glory (1989) : 4.07887165526957\n" + ] + } + ] + } + ] +} \ No newline at end of file diff --git "a/Week16_\354\230\210\354\212\265\352\263\274\354\240\234_\352\271\200\354\230\210\353\202\230.pdf" "b/Week16_\354\230\210\354\212\265\352\263\274\354\240\234_\352\271\200\354\230\210\353\202\230.pdf" new file mode 100644 index 0000000..872e0eb Binary files /dev/null and "b/Week16_\354\230\210\354\212\265\352\263\274\354\240\234_\352\271\200\354\230\210\353\202\230.pdf" differ