×

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

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

Python Array

Python Array In the programming language or computer science, an array is defined as the form of a data structure which consists of or store collection of various types of elements...

10 minutes read.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

3 minutes read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

How to learn python Online

Need to Learn a Programming Language 1. To get a high Paying job We know that Software Engineering is one of the top-paying professions in the world. The top criteria to be...

3 minutes read.

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

How to Download Python

How to Download Python Python is the most renowned programming language and developers across the globe are working on projects that are made using Python and its libraries. Here we will...

4 minutes read.

Exrex Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster...

4 minutes read.

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.

Python Dictionary Methods

Python Dictionary Methods Python has a set of built-in methods that dictionary objects can call. All the python dictionary methods are as follow: Methods Description clear() The dictionary.clear() method removes all the elements...

3 minutes read.

Python Set intersection_update() method

Python Set intersection_update() method The set.intersection_update() method in Python removes the items that is not present in both sets. It is different from the set.intersection() method, because the intersection()method returns a new set, with only  the common elements...

2 minutes read.

Python Key Error

What is an Error? Errors are nothing but problems in the program which occur in a program code, and this will stop the execution of the program. It is also called...

6 minutes read.

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value....

4 minutes read.

Python program to find whether a given number is even or odd

Python program to find whether a given number is even or odd A number is said to be even if any number is completely divisible by 2, which means there is...

1 minute read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

Performing Transaction Using Python MySQL

Transaction A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed....

3 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.