Machine Learning Report
Machine Learning Report
Submittedby
SONY(RA2211026020156)
SIVA SRAVANI(RA2211026020158)
MUKTHANANDA(RA2211026020138)
Undertheguidanceof
ABHIRAMI
(Designation, Department of Computer Science and Engineering)
degreeof
BACHELOROFTECHNOLOGY
in
COMPUTERSCIENCEANDENGINEERING
of
FACULTYOFENGINEERINGANDTECHNOLOGY
SRMINSTITUTEOFSCIENCEANDTECHNOLOGYRAM
APURAM,CHENNAI-600089
NOV 2024
SRMINSTITUTEOFSCIENCEANDTECHNOLOGY
(Deemed tobeUniversityU/S3ofUGCAct,1956)
BONAFIDECERTIFICATE
Certifiedthatthisprojectreporttitled“MOVIERECOMMENDATION
SYSTEM”isthebonafideworkRAVURI SONY[REG NO:RA2211026020156], SIVA
SRAVANI[REGNO:RA2211026020158],MUKTHANANDHA[REGNO:RA2211026
020138]whocarried out the project work undermysupervision. Certified further, that to
the bestof my knowledge, the work reported herein does not form any other project report
ordissertation on the basis of which a degree or award was conferred on an occasion
onthis or anyothercandidate.
SIGNATURE SIGNATURE
Dr.K.RAJA,M.E.,Ph.D.,
Name of the Supervisor
ProfessorandHead
Designation
ComputerScienceandEngineering,
ComputerScienceandEngineering, SRMInstituteofScienceandTechnology,
SRMInstituteofScience andTechnology,
Ramapuram,Chennai.
Ramapuram,Chennai.
INTERNALEXAMINER EXTERNALEXAMINER
SRMINSTITUTEOFSCIENCE
ANDTECHNOLOGYRAMAPURAM,CHENNAI-89
DECLARATION
Weherebydeclarethattheentireworkcontainedinthisprojectreporttitled“MOVIE
RECOMMENDATION SYSTEM” has been carriedoutby RAVURI
SONY[REGNO:RA22110260156],SIVA SRAVANI[REG NO: RA2211026020158],
MUKTHANANDA[REG NO: RA2211026020138] at SRMI nstitute of Science and Technology,
Ramapuram Campus, Chennai- 600089, under theguidance ofABHIRAMI, Department of
ComputerScienceandEngineering.
Place:Chennai
Date: RAVURI SONY
SIVA SRAVANI
MUKTHANANDA
ABSTRACT
iv
TABLEOFCONTENTS
Page.No
ABSTRACT iv
1.INTRODUCTION 1
1.1 Introduction 2
1.2 Problem statement 2
1.3 ProjectDomain 2
1.4 ScopeoftheProject 2
1.5 Methodology 3
2 LITERATURE REVIEW 4
3 PROJECTDESCRIPTION 7
3.1 ExistingSystem 7
3.2 ProposedSystem 7
3.3 FeasibilityStudy 8
3.3.1 EconomicFeasibility 8
3.3.2 TechnicalFeasibility . 9
3.3.3 SocialFeasibility 9
3.4 SystemSpecification
HardwareSpecificationSoftwareSpecificattion
10
4 PROPOSED WORK
4.1 GeneralArchitecture11
4.2Block Diagram12
4.3UMLDiagram13
4.4 UseCaseDiagram14
4.1 ModuleDescription
4.1.1 MODULE1: DATA COLLECTION AND TRAIN-
INGDATA....................................................................16
4.1.2 Step:1Datacollecting16
4.1.3 Step:2Processingofdata16
4.1.4 Step:3SplittheData18
4.1.5 DATASETSSAMPLE18
4.1.6 Step:4BuildingtheModel19
4.1.7 Step:5TestingtheModel19
4.1.8 Step:6Implementingthemodel20
IMPLEMENTATIONANDTESTING 21
5.1 InputandOutput21
5.1.1 Viewofapersonwithoutmask21
5.1.2 Viewofapersonwithmask22
5.2 Testing 22
5.2.1 TypesofTesting 22
5.2.2 Unit testing 22
5.2.3 Integrationtesting 23
5.2.4 Functionaltesting 24
5.2.5 TestResult 25
5.3 Testing Strategy 26
RESULTSANDDISCUSSIONS 27
6.1 EfficiencyoftheProposedSystem27
6.2 Comparisonof ExistingandProposedSystem27
CONCLUSIONANDFUTUREENHANCEMENTS 32
7.1 Conclusion32
7.2 Future Enhancements32
SOURCECODE&POSTERPRESENTATION 35
8.1 SampleCode35
8.2 PosterPresentation39
References 39
A. Sample screenshots
4.1 ArchitectureDiagram11
4.2 Block Diagram 12
4.3 UML Diagram13
4.4 UseCaseDiagram14
CHAPTER 1
INTRODUCTION
1.1Introduction
A Movie Recommendation System is a specialized software application
that assists users in discovering films tailored to their personal tastes and
preferences. By analyzing a variety of factors, such as viewing history, user
ratings, and movie characteristics (e.g., genre, cast, director), these systems use
machine learning algorithms to generate personalized movie suggestions. Two
primary techniques employed in recommendation systems are content-based
filtering, which recommends films similar to those the user has liked in the past,
and collaborative filtering, which makes suggestions based on patterns found in
the preferences of other users with similar tastes. Many modern systems adopt a
hybrid approach, combining both methods to deliver more accurate and diverse
recommendations. Widely used by platforms like Netflix and Amazon Prime,
movie recommendation systems enhance user experience by simplifying content
discovery and keeping viewers engaged with relevant.
1.2Problem statement
The primary problem that a Movie Recommendation System aims to
solve is the challenge of content overload in the digital entertainment space. With
the vast number of movies available across streaming platforms, users often
struggle to find content that aligns with their preferences. This leads to decision
fatigue, where users spend excessive time searching for movies they may enjoy,
potentially resulting in user disengagement or dissatisfaction.
9
The domain of the project is Machine Learning. The progress of machine
learning techniques have been challenging when it comes computer vision and
Image processing. Machine learning uses various algorithms based on the
requirement of the project.
1.5 ScopeoftheProject
The scope of a Movie Recommendation System encompasses the development and deployment of a
solution that can efficiently predict and suggest movies to users based on their preferences and
behavior patterns. This system will utilize various techniques such as content-based filtering,
collaborative filtering, and hybrid methods to deliver accurate recommendations. The system is
expected to handle large datasets, including user profiles, viewing histories, and movie metadata
(e.g., genres, actors, directors), to generate real-time suggestions. Additionally, it will incorporate
mechanisms to adapt to evolving user preferences by continuously learning from user interactions.
The recommendation system can be implemented across various platforms, including streaming
services, online movie rental sites, and personalized content platforms. Furthermore, the scope
extends to optimizing the system for scalability, allowing it to cater to a growing user base while
maintaining performance. Integration with user feedback loops, such as ratings and reviews, will also
be a key component in refining recommendations and improving the system’s accuracy over time.
1.6 METHODOLOGY
The methodology for developing a Movie Recommendation System involves several systematic
steps aimed at delivering personalized movie suggestions to users. Initially, data collection is
conducted to gather user-specific information, such as viewing history and ratings, alongside movie
metadata like genres, cast, and release year. This data undergoes preprocessing, including cleaning
and normalization, to ensure consistency. Exploratory Data Analysis (EDA) is performed to identify
patterns in user preferences and movie characteristics. Next, various recommendation techniques are
employed, including content-based filtering, which focuses on the similarities between movies, and
collaborative filtering, which leverages user interactions and preferences to find patterns among
users. A hybrid approach that combines these methods is often utilized to enhance recommendation
accuracy. The models are then trained and evaluated using metrics like Precision and Recall to
ensure effectiveness. Following model validation, the system is deployed to provide real-time
recommendations, continuously adapting based on user interactions and feedback. Finally, an
intuitive user interface is integrated, enabling users to easily interact with the system and refine their
10
movie suggestions, ultimately enhancing user engagement and satisfaction The methodology for
developing a Movie Recommendation System involves several key steps, leveraging data collection,
machine learning techniques, and recommendation algorithms to build an efficient, scalable system.
Below is a step-by-step outline of the methodology
CHAPTER 2
LITERATURE REVIEW
Authors; Narendra kumar rao; Nagendra Panini Challa; S Sreenivasa Chakravarthi; R Ranjana
The recommendation engine filters information using specific algorithms and recommends
high quality content to customers. It starts capturing more consumer behavior and based on that,
recommends products that consumers can purchase. Three key strategies are used in our
recommendation structures. One Demographic Filtering i.e. They offer general suggestions for each
individual, based entirely on the film's image and genre. The system recommends similar films to all
the users. if you consider that each person is of the same type, this method is considered very simple
In this proposed approach we had used contents like director, actors and genres in content
based filtering but in future we can also consider age of the user as the preferences changes with age
of the user. In future we can implement hybrid filtering which is a combination of content -based
filtering and collaborative-based filtering in which it consider contents and similarities between user
and item. Hybrid recommender will also reduce the value of Root mean square error which inturn
increase the performance of recommeder system and which increases precision and accuracy. We
can also explore this recommendations to various domains like videos, songs, news, tourisms etc.
Authors; Sambandam Jayalakshmi, Narayanan Ganesh,1 Robert cep, and Janakiraman Senthil
Murugan
Movie recommender systems are meant to give suggestions to the users based on the features
they love the most. A highly performing movie recommendation will suggest movies that match the
similarities with the highest degree of performance. This study conducts a systematic literature
11
review on movie recommender systems. It highlights the filtering criteria in the recommender
systems, algorithms implemented in movie recommender systems, the performance measurement
criteria, the challenges in implementation, and recommendations for future research. Some of the
most popular machine learning algorithms .
In this article, movie recommender systems have been described and classified. The
various types of recommender systems are introduced and discussed. Special emphasis is
given to explain in detail the various machine learning and metaheuristic algorithms
commonly deployed in movie recommendation research. The various model metrics that
summarize the quality of the model are discussed at length. The problems associated with
movie recommender systems are also summarized in a structured way and discussed.
Authors; Manoj kumar; Dharmendra kumar yadav; Anukur singh; Vijay Kr. Gupta
The most popular areas where recommender system is applied are books, news, articles,
music, videos, movies etc. In this paper we have proposed a movie recommendation system
named MOVREC. It is based on collaborative filtering approach that makes use of the
information provided by users, analyzes them and then recommends the movies that is best suited to
the user at that time. The recommended movie list is sorted according to the ratings given to
these movies by previous users and it uses K-means algorithm for this purpose.
In this paper we have introduced MovieREC, a recommender system for movie recommendation. It
allows a user to select his choices from a given set of attributes and then recommend him a movie
list based on the cumulative weight of different attributes and using K-means algorithm. By the
nature of our system, it is not an easy task to evaluate the performance since there is no right or
wrong recommendation; it is just a matter of opinions. Based on informal evaluations that we carried
out over a small set of users we got a positive response from them.
12
The present work improves these approaches by taking the movies’ content information into account
during the item similarity calculations. The proposed approach recommends the top n
recommendation list of movies to users on user’s interest preferences that were not already rated.
Graphically shows the percentage of already viewed movies by user and movies.
There are several datasets available to build a movie recommendation system. But for this
project, we are going to use a dataset that contains the metadata (cast, crew, budget, etc...) of the
movie. This project an algorithm for collaborative filtering recommendation system and applied it in
the movie recommendation system. This personalized recommendation system uses the singular
value decomposition algorithm and User-based co-coin similarity algorithm; these recommend the
top n movies to the active User.
Authors: Prof. Snehal Thorave, Abhay Sharma, Sahil Nair, Tanmay Shinde,Mayur Tipras
The purpose of recommendation systems, which are software tools and techniques, is to
provide a group of users with practical and informed recommendations for goods or services that
might be of interest to them. In other words, recommendation systems are a subset of information
filtering systems that aim to predict the "preference" or "rating" that will be given to an item.
13
The proliferation of streaming platforms has led to a vast array of movie options, making it
increasingly difficult for users to discover relevant Content. To address this challenge,
recommendation systems have emerged as valuable tools for suggesting movies based on user
preferences. We discuss the impact of temporal dynamics and social influence in improving
recommendation accuracy and effectiveness. Moreover, we emphasize the importance of
incorporating explanations to enhance user understanding and satisfaction.
Movie Recommendation Systems have become indispensable tools for users to navigate the
vast amount of available Content. This review paper has provided an overview of various techniques
and approaches employed in Movie Recommendation Systems. It is clear that combining various
techniques can produce recommendations that are more precise and tailored, such as collaborative
filtering, contentbased filtering, and deep learning algorithms.
14
15
16
17
CHAPTER 3
PROJECT
DESCRIPTION
18
interactive and adaptive recommendation process, delivering highly relevant and
diverse movie suggestions to users.
3.3 FeasibilityStudy
A feasibility study for a movie recommendation system evaluates its
viability across different dimensions, such as technical, economic, and
operational factors.
1. Technical feasibility
2. Economic feasibility
3. Operational feasibility
4. Legal and ethical feasibility
1. Technical Feasibility
The technical feasibility of a movie recommendation system depends on
the availability of advanced technologies and infrastructure. The system would
require access to large datasets containing user preferences, movie metadata, and
historical viewing patterns. Implementing machine learning algorithms such as
collaborative filtering, content-based filtering, and deep learning techniques will
also require robust computational resources, including cloud computing or high-
performance servers. Modern technologies like Apache Spark, TensorFlow, or
PyTorch can support scalable and efficient data processing.
2. Economic Feasibility
From an economic standpoint, the development and deployment of a
movie recommendation system entail costs related to infrastructure, personnel,
and maintenance. Initial costs include the procurement of servers, cloud storage,
and machine learning tools, while ongoing costs involve software maintenance,
data storage, and algorithm updates. However, the benefits, such as increased
user engagement, customer retention, and potentially higher subscription
revenue, make the investment economically viable. Subscription models,
advertising, or partnerships with studios can further offset the costs, leading to
long-term profitability.
19
3. Operational Feasibility
The operational feasibility hinges on the organization’s ability to
integrate the system into its current platform and maintain it efficiently. The
system will require continuous monitoring and optimization to ensure it delivers
accurate recommendations based on real-time user data. Training staff in
machine learning, data science, and system maintenance is essential for smooth
operations. Additionally, the system should be user-friendly and seamlessly
integrated into the platform’s UI/UX to ensure ease of use.
3.4 SystemSpecification
3.4.1 HardwareSpecification
1. Server Infrastructure:
3. Storage:
20
Minimum: 1 TB for storing movie metadata, user interaction data, model
artifacts
1.Operating System:
2.Programming Languages:
21
TensorFlow, PyTorch, Scikit-learn (for developing the recommendation
algorithms)
22
CHAPTER 4
PROPOSED WORK
The proposed work for the movie recommendation system aims to develop a personalized
platform that suggests films to users based on their preferences, viewing history, and trends within
the broader user base. The system will leverage collaborative filtering, content-based filtering, and
hybrid approaches to deliver recommendations tailored to individual tastes. Collaborative filtering
will identify patterns in user behavior, while content-based filtering will analyze movie attributes
such as genre, cast, and director to match user interests. Additionally, the hybrid model will combine
the strengths of both techniques, overcoming limitations like cold start issues and sparse data.
Advanced machine learning algorithms, such as matrix factorization or deep learning techniques,
will be used to optimize predictions and ensure scalability. The system will also incorporate user
feedback to refine suggestions continuously, providing a dynamic and engaging experience for users
across various demographics. Furthermore, attention will be given to the system's performance,
scalability, and security, ensuring it can handle a large dataset and protect user privacy.
Fig 4.1
23
The architecture diagram for the movie recommendation system outlines the key components
and data flow necessary for personalized recommendations. At the core, the system consists of a
User Interface Layer, where users interact with the platform via web or mobile applications,
providing inputs such as preferences and ratings. This layer connects to the Application Layer, which
processes these inputs and communicates with the Recommendation Engine. The recommendation
engine is powered by two main modules: Collaborative Filtering and Content-Based Filtering. The
Data Processing Layer handles large datasets, including user behavior, movie metadata, and
interaction logs. It processes and stores this data in a Data Storage Layer, which includes both
structured (relational databases) and unstructured data (NoSQL, cloud storage) for scalability.
Fig 4.2
24
The block diagram for the movie recommendation system visually represents the flow of data
and the interaction between different modules to deliver personalized movie recommendations. It
begins with the User Interaction Block, where users provide inputs such as movie ratings,
preferences, and feedback through a user-friendly interface. This data is passed to the Preprocessing
Block, which cleanses, normalizes, and transforms the input for further analysis. The core of the
system lies in the Recommendation Engine Block, consisting of two key components: Collaborative
Filtering and Content-Based Filtering modules. These modules analyze both user behavior and
movie features to generate relevant suggestions.
4.3 UMLDiagram
25
Fig 4.3
The UML diagram for the movie recommendation system captures the structural and behavioral
aspects of the system, detailing how different components interact to deliver personalized
recommendations. The Class Diagram represents the key entities such as User, Movie,
Recommendation Engine, and Rating. Each class has its attributes and methods; for example, the
User class contains attributes like user ID, preferences, and viewing history, while the Movie class
includes movie ID, genre, director, and cast details. The Recommendation Engine class is
responsible for generating recommendations, and the Rating class links users and movies through
ratings or reviews.
26
Fig 4.4
The use case diagram for the movie recommendation system highlights the interaction
between users and the system, demonstrating the key functionalities that the system offers. The
primary actors in the diagram are Users and Admin. The User actor interacts with the system to
perform several use cases such as Search Movies, View Recommendations, Rate Movies, and
Update Profile. When a user searches for a movie or provides ratings, the system collects this
information to refine and deliver personalized recommendations through the Receive
Recommendations use case.
MODULEDESCRIPTION
27
4.5 ModuleDescription
Ourentireprojectisdividedintotwomodules.
28
4.5.1 MODULE1:DATACOLLECTIONANDTRAININGDATA
DataCollectionandtrainingusingMachineLearningAlgorithms
4.5.2 Step:1Datacollecting
4.5.2.2Thedatasettraindataonpeoplewhousemasksandwhodonot.
Figure4.6:TestImage
4.5.3 Step:2Processingofdata
29
4.5.3.2 Theresizing imagecould be a vital Pre-processingstepin
pcvision because of the effectiveness of training model. The
nextstep is to method all the images within the data set into an
array.The im- age is born-again into the array for line them by
the loopperform. After that, the image are going to be
accustomed Pre-process in- put victimization MobileNetV2.
and therefore the
laststepduringthissectionisplayactinghotsecretwritingonlabelsa
s a result of several machine learning algorithms cannot
operateknowledge labeling directly. They need all input
variables andoutput variables to be numeric, as well as this
algorithm.Thelabeled knowledge are going to be remodeled
into a numericallabel,that thealgorithm willperceiveit.
Figure4.7:PreprocessingofData
30
4.5.4 Step:3SplittheData
4.5.4.1 Afterthepre-
processingpart,theinformationissplitinto2batches,that are
training data specifically seventy five percent, and the restis
testing knowledge. every batch is containing each of with-
maskand without-maskpictures.
4.5.5 DATASETSSAMPLE
Figure4.8:Withoutmask
31
Figure4.9:WithMask
4.5.6 Step:4BuildingtheModel
4.5.6.1 The next part is building the model. There are six steps in
buildingthe model that are constructing the training image
generator foraugmentation, the base model with MobileNetV2,
adding modelparameters, collecting the model, coaching the
model, and there-
forethelastissavingthemodelforthelongrunpredictionmethod.
4.5.7 Step:5TestingtheModel
4.5.7.1 To make sure the model can predict well, there are steps in
testingmodel.Thefirststepismakingpredictionsonthetestingset.
32
4.5.8 Step:6Implementingthemodel.
4.5.8.1 The model enforced within the video. The video scan from
frametoborder,thentheface
detectionformulaworks.Ifafaceisdetected,ittakingstofuturemeth
od.Fromdetectedframescontaining faces, reprocessing are
going to be disbursed togetherwithresizing the image size,
changing to the array, preprocessingin-
putvictimizationMobileNetV2.futurestep ispredictinginput file
from the saved model. Predict the input image that
hasbeenprocessedemployingaantecedentlydesignedmodel.Besi
des, the video frame also will be labelled that the person
issportingamaskor not alongsidethepredictiveproportion.
33
Chapter
5IMPLEMENTATIONANDTESTING
5.1 InputandOutput
5.1.1 Viewofapersonwithoutmask
Figure5.1:Personwithoutmask
34
5.1.2 Viewofapersonwithmask
Figure5.2:Personwithmask
5.2 Testing
Testingistheprocessofevaluatingasystemoritscomponent(s)withtheintenttofindwheth
eritsatisfiesthespecifiedrequirementsornot.
5.2.1 TypesofTesting
5.2.2 Unittesting
Unittestingisabenificiablesoftwaretestingmethodwheretheunitsofsourcecodeistestedto
checktheefficiencyandcorrectnessoftheprogram.
35
Input
1 forcategoryinCATEGORIES:
2 path=os.path.join(DIRECTORY,
3
4 category)forimginos.listdir(path):
5 imgpath=os.path.join(path,img)
6 image=loadimg(imgpath,targetsize=(224,224))image=imgtoarray(imag
7 e)
8 image=preprocessinput(image)
9
10 data.append(image)
Testresult
• Datasetsimagesareaccessed.
• Imagesofsize224*224pixelsareconsidered
• Theconsideredimagesareloadedintoanarrayforpreprocessing.
5.2.3 Integrationtesting
Input
frame=vs.read()
1
frame=imutil s.resize(frame,width=400)
2 (locs,preds)=detectandpredictmask(frame,faceNet,maskNet)for(box,pred)inzip(locs,preds):
(startX, startY,endX,endY)=box(mask,withoutMask)=pred
3
label=”Mask”ifmask>withoutMaskel se”NoMask”
4
36
8
color=(0,255,0)iflabel==”Mask”else(0,0,255)
Testresult
• Aframeofsize400pixelsiscreatedtotaketheinputanddisplaytheoutput.
• Alabelisdefinedasasquarebox.Itattainsgreencolourwhenamaskispresentontheface
andredcolourwhenthereisnomask.
5.2.4 Functionaltesting
Input
1 print(”[INFO]traininghead...”)H=model.fit(
2 aug.flow(trainX,trainY, batchsize
3 =BS),stepsperepoch=len(trainX)//BS,
4 v a l i d a t i o nd a t a =( t e s t X,t e s t
5 Y ),validationsteps=len(testX
6 )//BS,epochs=EPOCHS)
7 pri nt(”[INFO]evaluatingnetwork...”)
8 predIdxs=model.predict(testX,batchsize=BS)print(”[INFO]saving
9 maskdetectormodel...”)
10 model.save(”maskdetector.model ”,saveformat=” h5”)
11
TestResult
37
• Alltheimagesfromdatasetsareloadedintothemodelandcarriedoutfortraining.
• AftercompletingthetrainingtheMobilenetV2savesthedetectormodelandcancompe
te withthe inputgiven.
5.2.5 TestResult
Figure5.3:TestImage
38
5.3 TestingStrategy
• Unittesting:Unittestingverifiesthebitsofcodetochecktheviabilityofthecode.
• Functionaltesting:Thefunctionaltestingisdonetoverifytheoutputwiththeprovid
ed inputagainst thefunctionalrequirements.
39
Chapter6
RESULTSANDDISCUSSIONS
Results
Result of the Work Done
Measuring the Result via Accuracy, Precision, Recall, F measure
Preferred to be in Table Format with Numerical Values
Graph for the Table Generated
6.1 EfficiencyoftheProposedSystem
40
addition to the presence of face-masks alsodetermine
whetherthemasksarewearingproperlyornotwithininsingleshotcapturingusi
ng SSD-single shot detection and mobile net-v2 technology where
wecansee highperformance andaccuracyofresults.
6.2 ComparisonofExistingandProposedSystem
The existing system has no key factor like mask detection and there is
no specificsoftware to deploy in surveillance cameras and detection with
less efficient camerasare highly impossible and performance rate and
accuracy is very low. only
singledirectioncapturing.NoobjectdetectionTechnique.InourproposedSyst
emthetechnology was used is highly accurate and processing is very high.
when there is ahigh processing rate. we can say our system is efficient.
latest technology SSD–
singleshotdetectionusingobjectdetectionmodel.deployableinlessefficientw
ebcam
41
technologySSD-
singleshotdetectionusingobjectdetectionmodel.Highperformancerateandhighaccuracy
ofresults.Processingspeedishigh.Easilydetects the
logofobjects.Applicableforlessefficientcamera’slikewebcams.
16
42
Output
Figure6.1:Modeldetectedpersoniswithoutmask
43
Figure6.2:Modeldetectedpersoniswithoutmask
44
Chapter7
CONCLUSIONANDFUTUREENHANCEM
ENTS
7.1 Conclusion
7.2 FutureEnhancements
• Thisprojectisnotonlylimitedtothiscurrentpandemicbutcanbeusedasa protective
technology to prevent from the micro organisms and pollution bywearing
amask.
45
• With the data gathered through this work we can use this for creating a
survey,byanalyzinghowmuchpercentageofpeoplearewearingmasksandnot.
• If the person is not wearing mask, then we can create a software that sends
thewarningmessagestowearamaskanditcanusedtocreateawarenessamongthe
people.
46
Chapter8
SOURCECODE&POSTERPRESENTATI
ON
9.1 SampleCode
1 from tensorflow.keras.preprocessing.imageimportImageDataGenerator
2 from tensorflow.keras.applications importMobileNetV2
3 from tensorflow.keras.layers importAveragePooling2D
4 from tensorflow.keras.layersimportDropout
5 fromtensorflow.keras.layersimportFlatten
6 from tensorflow.keras.layersimportDense
7 fromtensorflow.keras.layersimportInput
8 from tensorflow.keras.models importModel
9 fromtensorflow.keras.optimizersimportAdam
fromtensorflow.keras.applications.mobilenetv2importpreprocessinput
10
fromtensorflow.keras.preprocessing.imageimportimgtoarray
11
fromtensorflow.keras.preprocessing.imageimportloadimg
12
fromtensorflow.keras.utils
13 importtocateg orical
14 from sklearn.preprocessingimportLabelBinarizer
fromsklearn.modelselectionimport
15 train test split
fromsklearn.metricsimport
16 classificationreport
17 from imutilsimportpaths
importmatplotlib.pyplotas
18 plt
importnumpyasnp
19
importos
20
21
47
#andbatchsize
23
INITLR=1e−4
24
25 EPOCHS=20
26 BS=32
27
28 DIRECTORY=r”C:\MaskDetection\CODE\Face−Mask−Detection−master\dataset”
CATEGORIES=[” withmask”,”withoutmask”]
29
30
#grabthe
31 list ofimagesinour datasetdirectory,then initialize
#the
32 list ofdata(i.e.,images)andclassimages
33 print(”[INFO]loadingimages...”)
34
data=[]
35
36 labels=[]
37
forcategoryinCATEGORIES:
38
39 path=os.path.join(DIRECTORY, category)
40 forimginos.listdir(path):
41 imgpath=os.path.join(path,img)
42 image=loadimg(imgpath, targets ize=(224,224))
43 image=imgtoarray(image)
44 image=preprocessinput(image)
45
46 data.append(image)
47 la be ls.append(category)
48
#performone−hotencodingonthe
49 labels
lb=LabelBinarizer()
50
51 labels=lb.fittransform(labels)
52 labels=tocateg o rical(labels)
53
data=np.array( data,dtype=”float32”)
54
55 labels=np.array(labels)
56
#constructthe
60 trainingimagegeneratorfordataaugmentation
aug=ImageDataGenerator(
61
48
62 rotationrange=20,
63 zoomrange=0.15,
64 widthshiftrange=0.2,
65 heightshiftrange=0.2,
66 shearrange=0.15,
67 horizontalflip=True,
68 fillmode =”nearest”)
69
#loadtheMobileNetV2network,
70 ensuringtheheadFClayer sets are
71 # left off
baseModel=MobileNetV2(weights=”imagenet”,
72 includetop=False,
73 inputtensor=Input(shape=(224,224,3)))
74
#constructtheheadofthemodelthat
75 willbeplacedontopofthe
#thebasemodel
76
headModel=baseModel.output
77
78 headModel=AveragePooling2D(poolsize=(7,7))(headModel)
headModel=F latten( name=”flatten”)(headModel)
79
headModel=Dense(128,
80 acti vation=”relu”)(headModel)
81 headModel=Dropout(0.5)(headModel)
82 headModel=Dense(2,activation=”softmax”)(headModel)
83
#placetheheadFCmodelontopofthebasemodel(this
84 wi l lbecome
#theactualmodelwewill
85 train)
model=Model(inputs=baseModel.input,
86 outputs=headModel)
87
#loopoverall
88 layersinthebasemodelandfreezethemsotheywill
#notbeupdatedduringthe
89 first training process
forlayerinbaseModel.layers:
90
91 layer.trainable=False
92
97 metrics=[”accuracy”])
98
99 #train theheadofthenetwork
100 print(”[INFO]traininghead...”)
49
101 H=model.fit(
102 aug.flow(trainX,trainY, batchsize=BS),
103 stepsperepoch=len(trainX) //BS,
104 validationdata=(testX,testY),
105 validationsteps=len(testX) //BS,
106 epochs=EPOCHS)
107
#makepredictionsonthe
108 testing set
109 print(”[INFO]evaluatingnetwork...”)
predIdxs=model.predict(testX,
110 batchsize =BS)
111
112 #foreachimageinthetestingsetweneedtofindtheindexofthe
#labelwithcorresponding
113 largest predicted probability
predIdxs=np.argmax(predIdxs,
114 axis=1)
115
#showanicelyformatted
116 classification report
117 print(classificationreport(testY.argmax(axis=1),predIdxs,
118 targetnames=lb.c lasses))
119
123
#plotthetraining
124 lossandaccuracy
125 N=EPOCHS
126 plt.style.use(”ggplot”)
127 plt.figure()
128 plt.plot( np.arange(0,N),H.history[”loss”], label=”trainloss”)
129 plt.plot( np.arange(0,N),H.history[”valloss”], label=”valloss”)
130 plt.plot(np.arange(0,N),H.history[”accuracy”], label=”t rainacc”)
131 plt.plot(np.arange(0,N),H.history[”valaccuracy”], label =”valacc”)
132 pl t.title(”TrainingLossandAccuracy”)
133 plt.xlabel(”Epoch#”)
134 plt .ylabel(”Loss/Accuracy”)
135 pl t.legend(loc=”lower left”)
136 pl t.savefig(”plot.png”)
50
References
Book in print [1] D. Sarunyagate, Ed., Lasers. New York: McGraw-Hill, 1996.
[4] G. Liu, K. Y. Lee, and H. F. Jordan, "TDM and TWDM de Bruijn networks and
Journal article shufflenets for optical communications," IEEE Trans. Comp., vol. 46, pp. 695-
701, June 1997.
[7] L. Liu and H. Miao, "A specification based approach to testing polymorphic
attributes," in Formal Methods and Software Engineering: Proceedings of the
Conference paper 6th International Conference on Formal Engineering Methods, ICFEM 2004,
Seattle, WA, USA, November 8-12, 2004, J. Davies, W. Schulte, M. Barnett,
Eds. Berlin: Springer, 2004. pp. 306-19.
[8] T. J. van Weert and R. K. Munro, Eds., Informatics and the Digital Society:
Conference Social, ethical and cognitive issues: IFIP TC3/WG3.1&3.2 Open Conference on
proceedings Social, Ethical and Cognitive Issues of Informatics and ICT, July 22-26, 2002,
Dortmund, Germany. Boston: Kluwer Academic, 2003.
[9] J. Riley, "Call for new look at skilled migrants," The Australian, p. 35, May 31,
Newspaper article
2005. [Online]. Available: Factiva, http://global.factiva.com. [Accessed May 31,
(from database)
2005].
[10] K. E. Elliott and C.M. Greene, "A local adaptive protocol," Argonne National
Technical report
Laboratory, Argonne, France, Tech. Rep. 916-1010-BB, 1997.
51
[11] J. P. Wilkinson, “Nonlinear resonant circuit devices,” U.S. Patent 3 624 125,
Patent
Jul. 16, 1990.
Standard [12] IEEE Criteria for Class IE Electric Systems, IEEE Standard 308, 1969.
Thesis/ [1] J. O. Williams, “Narrow-band analyzer,” Ph.D. dissertation, Dept. Elect. Eng.,
Dissertation Harvard Univ., Cambridge, MA, 1993.
[1] Dr.VandanaS.Bhat,ArpitaDurgaShambavi,KomalMainalli,KMManushree,
Shraddha V Lakamapur, “Review on Literature Survey of
HumanRecognitionwithFaceMask”,Issue1,20Mar,2021
[2] ZhongyuanWang,GuangchengWang,BaojinHuang,ZhangyangXiong,QiHong,Ha
oWu,PengYi,KuiJiang,NanxiWang,YingjiaoPei,HelingChen,Yu Miao, Zhibing
Huang, and Jinbi Liang, “Masked Face Recognition
DatasetandApplication”,version2,23Mar,2020
[3] M.H.Yang,D.J.Kriegman,andN.Ahuja,”DetectingFacesinImages:Asur-
vey”,IEEETrans.patternanalysisandmachineintelligence,vol.24,01Jan,2002.
[5] X.Zhang,S.RenandJ.Sun,”Deepresiduallearningforimagerecogni-tion”,June,2016.
52
[7] S. Kumar, A. Negi, J. N. Singh and H. Verma, ”A deep learning for brain
tumormri images semantic segmentation using fcn”, 2018 4th International
ConferenceonComputingCommunicationandAutomation(ICCCA),pp.1-
4,Dec2018
[9] T. Poggio and L. Stringa, “A project for an intelligent system: Vision and Learn-
ing,”Int.J.QuantumChem.,vol.42,2017
[10] MingjieJiang,XinqiFanandHongYan,RETINAFACEMASK:AFACEMASK
DETECTOR,8Jun,2020.
53