×

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system

A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the advice of friends. However, based on your search history, viewing history, or purchase history, Google now knows what news you'll read, and YouTube knows what kinds of videos you'll watch.

A recommendation system aids a firm in gaining loyal clients and establishing confidence by providing them with the items and services for which they come to your website. Today's recommendation systems are so sophisticated that they can manage even new customers who are visiting the site for the first time. They can also recommend things that are currently trending or highly rated. For this project, you can use content-based filtering.

Content-based filtering

The algorithm suggests a product that is like those that were previously viewed. To put it another way, we're trying to locate items that seem alike in this algorithm. If a person enjoys watching Sachine Tendulkar's shots, he might also enjoy watching Ricky Ponting's shots because the two videos have comparable tags and categories. Only the material appears to be identical, and it does not place a greater emphasis on the viewer. Only the product with the greatest score based on previous preferences is recommended.

Dataset

Link: - https://www.kaggle.com/datasets/tmdb/tmdb-movie-metadata?select=tmdb_5000_movies.csv .

Tech stack

  • Python
  • Pandas
  • Streamlit
  • NLTK
  • Pickle
  • Requests

Data processing

We need to select the features which play key role in recommendation. The data selected must be analyzed and preprocessed. We are not going to use all the feature columns. We will only select those that will play a major part in recommendations.

Stemming

  • Porter Stemming is used to perform stemming operations on a tag's column. Python's nltk package is used for this.
  • Stemming is the process of stripping a word down to its root, or lemma, which attaches to suffixes, prefixes, or the roots of other words. For instance, a stemming algorithm changes the phrases "To the root word "chocolate," "chocolates," "chocolatey," and "Choco," and to the stem "retrieve," "retrieval," "retrieved," and "retrieves," respectively. "COSINE

Cosine similarity

  • Cosine Similarity is a machine learning technique which measures the similarity between two vectors. By applying the cosine operation to the angles between the vectors, we can perform this cosine similarity.
  • It is majorly used to find out similarity and classify text information

Creating vectors

Based on the tag’s column, create vectors for corresponding movies, and then use cosine-similarity to compute the distance. Regardless of size, cosine similarity is a statistic for assessing how similar papers are. It determines the cosine of the three-dimensional angle created by two vectors projected side by side. Two comparable texts that are separated by the Euclidean distance because of the size of the document are likely to be oriented closer to one another because of the cosine similarity. Smaller the angle higher will be the similarity.

Source code of the program

import numpy as np
import pandas as pd
import ast
movies = pd.read_csv('tmdb_5000_movies.csv')
credits = pd.read_csv('tmdb_5000_credits.csv')
movies = movies.merge(credits,on='title')
movies = movies[['movie_id','title','genres','overview','keywords','cast','crew']]
movies.head()
movies.isnull().sum()
movies = movies.dropna()
movies.duplicated().sum()
def convert(obj):
L= []
for i in ast.literal_eval(obj):
L.append(i['name'])
return L
movies['genres'] = movies['genres']. apply(convert)
movies['keywords'] = movies['keywords']. apply(convert)
def convert3(obj):
iteration = 0
L= []
for i in ast.literal_eval(obj):
if (iteration! =3):
L.append(i['name'])
iteration = iteration+1
else:
break
return L
movies['cast'] = movies['cast']. apply(convert3)
movies.head()
def extract_director(obj):
L= []
for i in ast.literal_eval(obj):
if(i['job’] = ='Director'):
L.append(i['name'])
break
return L
movies['crew'] = movies['crew']. apply(extract_director)
movies.head()
movies['overview'] = movies['overview'].apply(lambda x:x.split())
movies.head()
movies['genres'] = movies['genres'].apply(lambda x:[i.replace(" ","")for i in x])
movies['keywords'] = movies['keywords'].apply(lambda x:[i.replace(" ","")for i in x])
movies['crew'] = movies['crew'].apply(lambda x:[i.replace(" ","")for i in x])
movies['cast'] = movies['cast'].apply(lambda x:[i.replace(" ","")for i in x])


movies.head()
movies['tags'] = movies['overview'] + movies['genres'] + movies['keywords'] + movies['cast'] + movies['crew']
movies.head()
New_Data = movies[['movie_id','title','tags']]
New_Data.head()
New_Data['tags'] = New_Data['tags'].apply(lambda x:" ".join(x))
New_Data.head()
New_Data['tags'] = New_Data['tags'].apply(lambda x:x.lower())
from sklearn.feature_extraction.text import CountVectorizer                                                                                                         
cv = CountVectorizer(max_features=5000,stop_words='english')
cv.fit_transform(New_Data['tags']).toarray().shape
vectors = cv.fit_transform(New_Data['tags']).toarray()
vectors
cv.get_feature_names()




import nltk
from nltk.stem.porter import PorterStemmer
ps = PorterStemmer()
def stem(text):
y = []


for i in text.split():
y.append(ps.stem(i))
return " ".join(y)
New_Data['tags'][0]
New_Data['tags'] = New_Data['tags'].apply(stem)
from sklearn.metrics.pairwise import cosine_similarity
similarity = cosine_similarity(vectors)
similarity[1]
sorted(list(enumerate(similarity[0])),reverse=True,key=lambda x:x[1])[1:10]
def recommend(movie):
movie_index = New_Data[New_Data['title'] == movie].index[0]
distances = similarity[movie_index]
movies_list = sorted(list(enumerate(distances)),reverse=True,key=lambda x:x[1])[1:6]


for i in movies_list:
print(New_Data.iloc[i[0]].title)
recommend('Avatar')

Output

Artificial intelligence mini projects with source code

Related Topics

Python divmod() function

Python divmod() function The divmod() function in Python returns a tuple containing the quotient  and the remainder when parameter ‘a’ (divident) is divided by parameter ‘b’ (divisor). Syntax: divmod(a, b) Parameter a: This parameter represents a number you...

1 minute read.

Tuple in Python

Tuples Tuples are the same as the list but as we know that lists are mutable means we can change the data from it. In the tuple we cannot change the...

6 minutes read.

Python Recursion

Recursion is one of the most interesting yet important concepts of any programming language. If you want to be a good programmer or data scientist, then you should better have...

4 minutes read.

Python Set difference() Method

Python Set difference() Method The set.difference() method in Python returns the set difference of two sets(A-B). Syntax set.difference(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return This method returns the difference of the two specified...

2 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Rank Based Percentile GUI Calculator using Tkinter in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

3 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.

Python bool()

Python bool() class The bool() class in Python returns the boolean value for the specified object. Syntax class bool([x]) Parameter object: This parameter represents the object, like String, List, Number etc. Return It will always return True, except...

1 minute read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how...

6 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

Python RegEx

Python RegEx (python regular expressions) is a concept of writing and finding expressions in a pool of characters easily. A Regular expression (RegEx) is a set of characters that defines search...

10 minutes read.

Creating new Database using Python MySQL

In this article, we are going to discuss how to create a new database by connecting Python and MySQL. What is a Database? The places or memory used to secure highly and...

6 minutes read.