<jupyter_start><jupyter_text>Finding Similar Movies We'll start by loading up the MovieLens dataset. Using Pandas, we can very quickly load the rows of the u.data and u.item files that we care about, and merge them together so we can work with movie names instead of ID's. (In a real production job, you'd stick with ID's and worry about the names at the display layer to make things more efficient. But this lets us understand what's going on better for now.)<jupyter_code>import pandas as pd

r_cols = ['user_id', 'movie_id', 'rating']
ratings = pd.read_csv('u.data', sep='\t', names=r_cols, usecols=range(3), encoding="ISO-8859-1")
#teen columns lie unko r_cols name dedia
m_cols = ['movie_id', 'title']
movies = pd.read_csv('u.item', sep='|', names=m_cols, usecols=range(2), encoding="ISO-8859-1")
#do columns lie unko m_cols name dedia
ratings = pd.merge(movies, ratings)

ratings.head()<jupyter_output><empty_output><jupyter_text>Now the amazing pivot_table function on a DataFrame will construct a user / movie rating matrix. Note how NaN indicates missing data - movies that specific users didn't rate.<jupyter_code>movieRatings = ratings.pivot_table(index=['user_id'],columns=['title'],values='rating')
movieRatings.head()<jupyter_output><empty_output><jupyter_text>Let's extract a Series of users who rated Star Wars:<jupyter_code>starWarsRatings = movieRatings['Star Wars (1977)']
starWarsRatings.head()<jupyter_output><empty_output><jupyter_text>Pandas' corrwith function makes it really easy to compute the pairwise correlation of Star Wars' vector of user rating with every other movie! After that, we'll drop any results that have no data, and construct a new DataFrame of movies and their correlation score (similarity) to Star Wars:<jupyter_code>similarMovies = movieRatings.corrwith(starWarsRatings)
similarMovies = similarMovies.dropna()
df = pd.DataFrame(similarMovies)
df.head(10)<jupyter_output>C:\Users\<NAME>\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\numpy\lib\function_base.py:2487: RuntimeWarning: Degrees of freedom <= 0 for slice
  warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning)
C:\Users\<NAME>\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\numpy\lib\function_base.py:2496: RuntimeWarning: divide by zero encountered in double_scalars
  c *= 1. / np.float64(fact)<jupyter_text>(That warning is safe to ignore.) Let's sort the results by similarity score, and we should have the movies most similar to Star Wars! Except... we don't. These results make no sense at all! This is why it's important to know your data - clearly we missed something important.<jupyter_code>similarMovies.sort_values(ascending=False)<jupyter_output><empty_output><jupyter_text>Our results are probably getting messed up by movies that have only been viewed by a handful of people who also happened to like Star Wars. So we need to get rid of movies that were only watched by a few people that are producing spurious results. Let's construct a new DataFrame that counts up how many ratings exist for each movie, and also the average rating while we're at it - that could also come in handy later.<jupyter_code>import numpy as np
movieStats = ratings.groupby('title').agg({'rating': [np.size, np.mean]})
movieStats.head()<jupyter_output><empty_output><jupyter_text>Let's get rid of any movies rated by fewer than 100 people, and check the top-rated ones that are left:<jupyter_code>popularMovies = movieStats['rating']['size'] >= 100
movieStats[popularMovies].sort_values([('rating', 'mean')], ascending=False)[:15]<jupyter_output><empty_output><jupyter_text>100 might still be too low, but these results look pretty good as far as "well rated movies that people have heard of." Let's join this data with our original set of similar movies to Star Wars:<jupyter_code>df = movieStats[popularMovies].join(pd.DataFrame(similarMovies, columns=['similarity']))
df.head()<jupyter_output><empty_output><jupyter_text>And, sort these new results by similarity score. That's more like it!<jupyter_code>df.sort_values(['similarity'], ascending=False)[:15]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09941944847605225, 'fraction_numerical': 0.010643444605708756, 'mean_word_length': 6.3707664884135475, 'pattern_counts': {'":': 0, '<': 40, '<?xml version=': 0, '>': 39, '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': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '17742', 'license': 'MIT', 'n_tokens_mistral': 1325, 'n_tokens_neox': 1229, 'n_words': 444, 'path': 'day18/ml23/.ipynb_checkpoints/similarmovies-checkpoint.ipynb', 'repo_name': 'AkshayManchanda/Machine_Learning_with_Python_Training', 'size': '4154'}