Movie-Lens-Dataset-Visualization-and-Prediction

Movie-Lens-Dataset-Visualization-and-Prediction

Hari Haran (AIGAMER)
11 min readMar 1, 2021

This dataset (ml-latest-small) describes 5-star rating and free-text tagging activity from MovieLens, a movie recommendation service. It contains 100836 ratings and 3683 tag applications across 9742 movies. These data were created by 610 users between March 29, 1996 and September 24, 2018. This dataset was generated on September 26, 2018.

Users were selected at random for inclusion. All selected users had rated at least 20 movies. No demographic information is included. Each user is represented by an id, and no other information is provided.

The data are contained in the files links.csv, movies.csv, ratings.csv and tags.csv. More details about the contents and use of all these files follows.

This is a development dataset. As such, it may change over time and is not an appropriate dataset for shared research results. See available benchmark datasets if that is your intent.

This and other GroupLens data sets are publicly available for download at http://grouplens.org/datasets/.

Neither the University of Minnesota nor any of the researchers involved can guarantee the correctness of the data, its suitability for any particular purpose, or the validity of results based on the use of the data set. The data set may be used for any research purposes under the following conditions:

  • The user may not state or imply any endorsement from the University of Minnesota or the GroupLens Research Group.
  • The user must acknowledge the use of the data set in publications resulting from the use of the data set (see below for citation information).
  • The user may redistribute the data set, including transformations, so long as it is distributed under these same license conditions.
  • The user may not use this information for any commercial or revenue-bearing purposes without first obtaining permission from a faculty member of the GroupLens Research Project at the University of Minnesota.
  • The executable software scripts are provided “as is” without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The entire risk as to the quality and performance of them is with you. Should the program prove defective, you assume the cost of all necessary servicing, repair or correction.

In no event shall the University of Minnesota, its affiliates or employees be liable to you for any damages arising out of the use or inability to use these programs (including but not limited to loss of data or data being rendered inaccurate).

If you have any further questions or comments, please email grouplens-info@umn.edu

To acknowledge use of the dataset in publications, please cite the following paper:

F. Maxwell Harper and Joseph A. Konstan. 2015. The MovieLens Datasets: History and Context. ACM Transactions on Interactive Intelligent Systems (TiiS) 5, 4: 19:1–19:19. https://doi.org/10.1145/2827872

GroupLens is a research group in the Department of Computer Science and Engineering at the University of Minnesota. Since its inception in 1992, GroupLens’s research projects have explored a variety of fields including:

  • recommender systems
  • online communities
  • mobile and ubiquitious technologies
  • digital libraries
  • local geographic information systems

GroupLens Research operates a movie recommender based on collaborative filtering, MovieLens, which is the source of these data. We encourage you to visit http://movielens.org to try it out! If you have exciting ideas for experimental work to conduct on MovieLens, send us an email at grouplens-info@cs.umn.edu — we are always interested in working with external collaborators.

Formatting and Encoding

The dataset files are written as comma-separated values files with a single header row. Columns that contain commas (,) are escaped using double-quotes ("). These files are encoded as UTF-8. If accented characters in movie titles or tag values (e.g. Misérables, Les (1995)) display incorrectly, make sure that any program reading the data, such as a text editor, terminal, or script, is configured for UTF-8.

User Ids

MovieLens users were selected at random for inclusion. Their ids have been anonymized. User ids are consistent between ratings.csv and tags.csv (i.e., the same id refers to the same user across the two files).

Movie Ids

Only movies with at least one rating or tag are included in the dataset. These movie ids are consistent with those used on the MovieLens web site (e.g., id 1 corresponds to the URL https://movielens.org/movies/1). Movie ids are consistent between ratings.csv, tags.csv, movies.csv, and links.csv (i.e., the same id refers to the same movie across these four data files).

Ratings Data File Structure (ratings.csv)

All ratings are contained in the file ratings.csv. Each line of this file after the header row represents one rating of one movie by one user, and has the following format:

The lines within this file are ordered first by userId, then, within user, by movieId.

Ratings are made on a 5-star scale, with half-star increments (0.5 stars — 5.0 stars).

Timestamps represent seconds since midnight Coordinated Universal Time (UTC) of January 1, 1970.

All tags are contained in the file tags.csv. Each line of this file after the header row represents one tag applied to one movie by one user, and has the following format:

The lines within this file are ordered first by userId, then, within user, by movieId.

Tags are user-generated metadata about movies. Each tag is typically a single word or short phrase. The meaning, value, and purpose of a particular tag is determined by each user.

Timestamps represent seconds since midnight Coordinated Universal Time (UTC) of January 1, 1970.

Movies Data File Structure (movies.csv)

Movie information is contained in the file movies.csv. Each line of this file after the header row represents one movie, and has the following format:

Movie titles are entered manually or imported from https://www.themoviedb.org/, and include the year of release in parentheses. Errors and inconsistencies may exist in these titles.

Genres are a pipe-separated list, and are selected from the following:

Identifiers that can be used to link to other sources of movie data are contained in the file links.csv. Each line of this file after the header row represents one movie, and has the following format:

movieId is an identifier for movies used by https://movielens.org. E.g., the movie Toy Story has the link https://movielens.org/movies/1.

imdbId is an identifier for movies used by http://www.imdb.com. E.g., the movie Toy Story has the link http://www.imdb.com/title/tt0114709/.

tmdbId is an identifier for movies used by https://www.themoviedb.org. E.g., the movie Toy Story has the link https://www.themoviedb.org/movie/862.

Use of the resources listed above is subject to the terms of each provider.

Cross-Validation

Prior versions of the MovieLens dataset included either pre-computed cross-folds or scripts to perform this computation. We no longer bundle either of these features with the dataset, since most modern toolkits provide this as a built-in feature. If you wish to learn about standard approaches to cross-fold computation in the context of recommender systems evaluation, see LensKit for tools, documentation, and open-source code examples.

This dataset (ml-latest-small) describes 5-star rating and free-text tagging activity from , a movie recommendation service. It contains 100836 ratings and 3683 tag applications across 9742 movies. These data were created by 610 users between March 29, 1996 and September 24, 2018. This dataset was generated on September 26, 2018.

1. Formulate questions for Analysis

The main analysis will focus on answering the below questions. It’s important to note that the findings in this analysis are based on a sample and are not definitive.

  1. Find the Year with most Movies released
  2. What is the most common Genre ?
  3. Find the Avg. Ratings given for each Movie by different Users
  4. Movie with most No Users ratings.
  5. Which User has Rated more no.of Movies and what is that Users Avg. Rating ?
  6. Predict what would be the Rating a movie with specific Genres will get ?

2. Import Necessary Libraries

#data analysis libraries 
import numpy as np
import pandas as pd

#visualization libraries
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
#ignore warnings
import warnings
warnings.filterwarnings('ignore')

3. Read in and Explore/Analyze the Data

It’s time to read in our data’s using , and take a first look at the dimensions and data using the and functions.

#import train and test CSV files
movie = pd.read_csv("movies.csv")
ratings = pd.read_csv("ratings.csv")
links = pd.read_csv("links.csv")
tags = pd.read_csv("tags.csv")
#take a look at the training data
print(movie.shape)
print(ratings.shape)
print(links.shape)
print(tags.shape,end="\n\n")
m=pd.read_csv("movies.csv")
movie.head(3)
links.head(3)
ratings.head(3)
tags.head(3)

#get a list of the features within the dataset
print("Movie : ", movie.columns,end="\n\n")
print("Rating : ", ratings.columns,end="\n\n")
print("Links : ", links.columns,end="\n\n")
print("Tags : ", tags.columns,end="\n\n")

movie.info()
ratings.info()
tags.info()
(9742, 3)
(100836, 4)
(9742, 3)
(3683, 4)

Movie : Index(['movieId', 'title', 'genres'], dtype='object')

Rating : Index(['userId', 'movieId', 'rating', 'timestamp'], dtype='object')

Links : Index(['movieId', 'imdbId', 'tmdbId'], dtype='object')

Tags : Index(['userId', 'movieId', 'tag', 'timestamp'], dtype='object')

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9742 entries, 0 to 9741
Data columns (total 3 columns):
movieId 9742 non-null int64
title 9742 non-null object
genres 9742 non-null object
dtypes: int64(1), object(2)
memory usage: 228.5+ KB
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 100836 entries, 0 to 100835
Data columns (total 4 columns):
userId 100836 non-null int64
movieId 100836 non-null int64
rating 100836 non-null float64
timestamp 100836 non-null int64
dtypes: float64(1), int64(3)
memory usage: 3.1 MB
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3683 entries, 0 to 3682
Data columns (total 4 columns):
userId 3683 non-null int64
movieId 3683 non-null int64
tag 3683 non-null object
timestamp 3683 non-null int64
dtypes: int64(3), object(1)
memory usage: 115.2+ KB
  • Numerical Features: movieId , userId , rating
  • Categorical Features: tags , genres
  • Alphanumeric Features: None

The data types for each feature

Now that we have an idea of what kinds of features we’re working with, we can see how much information we have about each of them.

# Droping the timestamp column from ratings and tags file
ratings.drop(columns='timestamp',inplace=True)
tags.drop(columns='timestamp',inplace=True)

Some Observations:

  • userId: Unique Id provided for each User
  • userId were selected at random for inclusion. Their ids have been anonymized. User ids are consistent between ratings.csv and tags.csv (i.e., the same id refers to the same user across the two files).
  • movieId: Unique Id provided for each Movie
  • Only movies with at least one rating or tag are included in the dataset. These movie ids are consistent with those used on the MovieLens web site (e.g., id 1 corresponds to the URL . Movie ids are consistent between ratings.csv, tags.csv, movies.csv, and links.csv (i.e., the same id refers to the same movie across these four data files).
  • rating (rating.csv): Ratings are made on a 5-star scale, with half-star increments (0.5 stars - 5.0 stars).
  • All Ratings are contained in the file ratings.csv. Each line of this file after the header row represents one rating of one movie by one user
  • Mean show the average rating is 3.2-Star
  • genres: Genres are a pipe-separated list, and are selected from the following:
  • Children’s
  • Documentary
  • (no genres listed)

Suggestions:

  • The Timestamp column from both tags.csv and ratings.csv does not contribute much. So lets drop them
  • links.csv has no usefull information hence lets drop the table.
  • In movie.csv from the Title column we can extrct the year in which the movie was released.
  • For further prediction the genres column has to extracted and all Individual Genres has to br Encoded into Numerical Values ( eg. One-Hot-Encoding method )

4. Descriptive Analytics and Visualization

#Extracting the year from the Title
movie['Year'] = movie['title'].str.extract('.*\((.*)\).*',expand = False)

Now that we have extracted the from the lets find out which Year has the highest number of Movie releases

Max No.of Movies Relesed = 311
Year = 2002





count 107.000000
mean 90.934579
std 102.122223
min 1.000000
25% 16.000000
50% 39.000000
75% 150.000000
max 311.000000
Name: title, dtype: float64

1.

As per the above result we got to know that in has the highest number of movie releases with .

On an Avg. there are around releasing per Year.

Now Lets extract the individual from the Genres column. And lets create columns with the each Genres as the name and allot “1” if the movie has the Genre else “0”

# Seperate the Geners Column and Encoding them with One-Hot-Encoding Method.
genres=[]
for i in range(len(movie.genres)):
for x in movie.genres[i].split('|'):
if x not in genres:
genres.append(x)

len(genres)
for x in genres:
movie[x] = 0
for i in range(len(movie.genres)):
for x in movie.genres[i].split('|'):
movie[x][i]=1
movie

9742 rows × 24 columns

Now that we have the data in the Genres Column converted in to Numerical values in different columns, Lets Drop the Genres Column

movie.drop(columns='genres',inplace=True)
movie.sort_index(inplace=True)
x={}
for i in movie.columns[4:23]:
x[i]=movie[i].value_counts()[1]
print("{} \t\t\t\t{}".format(i,x[i]))

plt.bar(height=x.values(),x=x.keys())
plt.show()
Animation 611
Children 664
Comedy 3756
Fantasy 779
Romance 1596
Drama 4361
Action 1828
Crime 1199
Thriller 1894
Horror 978
Mystery 573
Sci-Fi 980
War 382
Musical 334
Documentary 440
IMAX 158
Western 167
Film-Noir 87
(no genres listed) 34

2.

From the above we can say that is the most Comman Genre released in the Movie Field with 4361 Movies followed by Comedy with 3756 Movies and so on ...........

3.

As we can see that each movies is being rated by many Users, lets Group them by "movieId" and rate each movie with the mean of the Rating given by different Users.

9742 rows × 4 columns

4.

From the above table we can say that Forest Gump (1994) has the no.of. Ratings with as average.

Followed by Shawshank Redemption, The (1994) with 317 User Ratings and as average and so on.

5.

Final Summary and Results

6. Model, Predict and Solve

We will use Model to Predict the Rating of a movie with it's Genres given.

As we know that the Genres are Enocded (with method) which is from the 3'rd column to the 23rd column are set as features and the Ratings (last column) is the expected result.

Using sklearn.model_selection.train_test_split function we will split the whole data into train data and test data

For the same Data that we trained with,gives a error of

I have set the n_estimators to as it is results in less error than others after manually testing with multiple values.

Now let’s try predicting the Ratings with the Test data and see the output and how well the model predicted.

From the above results we can say that the model perdicts the Ratings for a movie with ± 0.70 deviated from the actual value.

Results

As the analysis are based on a sample and are not definitive the model is quite reliable and for Predicting the Rating of a Movie with it's Genres given

Originally published at https://aigamer28100.github.io.

--

--

Hari Haran (AIGAMER)
Hari Haran (AIGAMER)

Written by Hari Haran (AIGAMER)

DevOps Engineer at Zoho since 2022, specializing in innovative solutions, fostering teamwork, and driving progress.

No responses yet