Machine Learning for Stress Detection
Machine Learning for Stress Detection
A PROJECT REPORT
(FINAL PROJECT)
Submitted by
JITHISH M 20EUEC068
KAMALESH A 20EUEC070
KARAN P 20EUEC071
IN
MARCH-2024
BONAFIDE CERTIFICATE
supervision.
SIGNATURE SIGNATURE
3
TABLE OF CONTENTS
ABSTRACT 3
LIST OF CONTENTS 4
LIST OF TABLE 7
LIST OF FIGURE 8
LIST OF ABBREVIATION 9
10
1 INTRODUCTION
10
1.1 Background
10
1.2 Motivation
11
1.3 Proposed Solution
11
1.4 Necessity
12
1.5 Advantages
2 LITERATURE SURVEY 15
3 SYSTEM DESIGN 25
4
4.1 NODEMCU (ESP8266) 28
4.1.1 NODEMCU 28
4.2 Pin Diagram of ESP8266 29
4.2.1 Pin diagram of 30
ESP8266
30
4.3 Features of ESP8266
4.4 Port B (PB [7:0]) XTAL1/
31
XTAL2/TOSC1/TOSC2
4.5 Port C (PC [5:0])
32
4.6 PC6/RESET 32
4.7 Port D (PD [7:0]) 32
4.8 AVCC 33
4.9 NODEMCU UNO Board 33
Description
4.9.1 NODEMCU UNO
Board 33
5
4.15.2 DHT11 Module 40
Pinout
4.15.3 Arduino UNO 41
SOFTWARE DESCRIPTION
5 42
WORKING 56
6
6.1 Facial Expression analysis
56
with CNN
6.2 Physiological Monitoring with
MAX30100 and KNN
56
6.3 Integration of facial and
Physiological data 56
6.4 Validation and Evaluation 57
58
RESULTS
7
62
8 CONCLUSION
63
9 REFERENCES
6
LIST OF TABLE
7.2.2 60
Classification report of KNN
7
LIST OF FIGURES
8
LIST OF ABBREVIATION
9
CHAPTER 1
INTRODUCTION
1.1 BACKGROUND:
The increasing awareness of mental health and well-being has led to a
growing demand for innovative technologies capable of monitoring and
addressing emotion-related issues. Traditional emotion assessment methods,
such as self-reporting or physiological measurements, face challenges in
providing real-time and objective insights into an individual's emotion levels.
Leveraging advancements in computer vision and deep learning, this project
aims to pioneer a more accurate and efficient approach to emotion detection,
focusing on facial cues as indicators of emotion.
1.2 MOTIVATION:
The motivation behind this work stems from the limitations of existing
emotion detection methods and the potential impact on individual well-being.
Accurate and timely identification of emotion is crucial for early intervention
and personalized support. By combining the capabilities of OpenCV's face
detection with a pre-trained Convolutional Neural Network (CNN) model, we
aim to create a robust system that can adapt to diverse datasets and provide
10
nuanced emotion assessments. The motivation is rooted in the potential of this
technology to contribute significantly to mental health monitoring, offering
individuals and healthcare professionals valuable insights for timely
interventions.
1.4 NECESSITY:
In contemporary society, the escalating prevalence of emotion-related
concerns has brought forth a pressing need for advanced and non-intrusive
emotion detection methods. Conventional approaches, often reliant on self-
reporting or physiological measurements, face limitations in terms of
precision and real-time capabilities. The challenges associated with these
traditional methods underscore the necessity for a more accurate and efficient
emotion detection system. Such a system would not only address the growing
concerns surrounding mental well-being but also contribute to early
intervention strategies, thereby mitigating the potential impact of prolonged
emotion on individuals.
11
1.5 ADVANTAGES:
Real-time Monitoring:
The emotion detection system enables real-time monitoring of emotion levels,
allowing for prompt identification and timely interventions.
Non-intrusive Assessment:
Leveraging facial recognition, the system offers a non-intrusive approach to
emotion detection, enhancing user comfort and acceptability.
12
support for improved mental well-being. In modern society, the escalating
prevalence of stress-related concerns has highlighted the imperative need for
accurate and non-intrusive stress detection methods. Conventional approaches
often fall short in terms of precision and real-time capabilities.
The proposed method unfolds in three key steps. Initially, facial images are
captured through a web camera, utilizing the Haar cascade algorithm from
OpenCV for robust face detection. This ensures the efficient isolation of facial
regions for subsequent analysis. Following this, the isolated faces undergo
processing through a pre-trained Convolutional Neural Network (CNN) model,
specifically tailored for stress estimation. The CNN is meticulously trained on
a diverse dataset to identify nuanced facial cues indicative of stress, thereby
enhancing the accuracy of stress level assessments.
13
In parallel, an additional dimension is added to the stress detection system by
incorporating emotion analysis using a k-Nearest Neighbors (KNN) algorithm.
This step aims to extract emotional features from facial expressions,
contributing to a more comprehensive understanding of the individual's
mental state. The combination of OpenCV's face detection, the deep learning
model, and KNN for emotion analysis creates a potent and adaptable multi-
modal stress detection system.
The integration of facial recognition, deep learning, and machine learning
techniques provides a holistic approach to stress detection, capturing both
physiological and emotional aspects. The proposed system holds promise for
real-time stress monitoring in various settings, from workplaces to personal
well-being applications. The multi-modal nature of the system enhances its
versatility, making it a valuable tool for mental health initiatives and
interventions.
14
CHAPTER 2
LITERATURE SURVEY
15
[Link]: Facial Emotion Recognition using Deep Learning
Authors: Shubhanjay Pandey,Sonakshi Handoo,Yogesh,
Publication: 2022 International Mobile and Embedded Technology
Conference (MECON)
As it is known, sentiments influence information processing, attitude
formation, and decision making to a great extent in real-world scenarios.
Several recent efforts have been published about FER or facial expression
recognition, however, due to the diversity of human faces and fluctuations in
pictures, reliable and robust FER systems remain a challenge. Till date, every
study and work has proposed either a single network or an ensemble model.
The accuracy of ensemble models is higher, but they were associated with
many models and datasets and a few tweaked datasets to improve the accuracy,
increasing the computing complexity. While the majority of research in this
field focuses on improving accuracy, this study utilizes the proposed model to
a real-world scenario in which a personu2019s face contains a mix of
emotions, and a single-label sentiment can be highly noisy in such situations.
In view of this scenario, we developed and tested 15-20 models and methods.
In this paper, we propose a single standalone-based CNN model with its
implementation on a real-time Intelligent System for Sentiment Recognition,
which validates accuracy through transfer learning and performs tasks such as
face detection, sentiment classification, and providing a live list of
probabilistic labels in Realtime from a webcam feed in one blended step. The
proposed model achieves an accuracy of 76.62 % outperforming all
standalone-based models like VGG16, VGG19, EfficientNetB7, and other
proposed models on the FER2013 dataset solely, which is a challenging and
noisy crowd-sourced dataset, without using any other auxiliary dataset.",
16
Publication: 2020 International Conference for Emerging Technology
(INCET)
Human Emotion detection from image is one of the most powerful and
challenging research task in social communication. Deep learning (DL) based
emotion detection gives performance better than traditional methods with
image processing. This paper presents the design of an artificial intelligence
(AI) system capable of emotion detection through facial expressions. It
discusses about the procedure of emotion detection, which includes basically
three main steps: face detection, features extraction, and emotion
classification. This paper proposed a convolutional neural networks (CNN)
based deep learning architecture for emotion detection from images. The
performance of the proposed method is evaluated using two datasets Facial
emotion recognition challenge (FERC-2013) and Japaness female facial
emotion (JAFFE). The accuracies achieved with proposed model are 70.14
and 98.65 percentage for FERC-2013 and JAFFE datasets respectively.",
17
recognition. The existing approaches are also suffered from some challenges
and those challenges should be addressed and considered for accurately
predicting the users' emotional state. The application of emotion detection is
also very vast and a few of the major applications are also discussed. Finally,
a brief analysis of existing Machine learning approaches and their conclusion
is given.",
18
solvers in the field of artificial intelligence. The emotions on a human face say
so much about our thought process and give a glimpse of what's going on
inside the mind. Real time emotion recognition is to acquaint the machine
with human like ability to recognize and analyse human emotions. This
project aims to categorize a facial image into one of the seven emotions which
we are considering in this study, by building a multi class classifier. In this
paper we are using convolutional neural networks (CNNs) for training over
gray scale images obtained from fer2013 dataset. We experimented with
different depths and max pooling layers to get the best accuracy and
ultimately achieving 89.98% accuracy. To combat overfitting, we have used
technique like dropout. We are also analyzing the performance of different
network architectures like shallow network and modern deep network in
recognizing human emotion. We also present the real-time implementation of
emotion recognition in web-camera which provides accurate results for
multiple faces simultaneously. The results obtained from the research are
quite interesting.",
19
[Link]: Emotion Recognition System from Speech and Visual Information
based on Convolutional Neural Networks
Authors: Nicolae-Cu0103tu0103lin Ristea,Liviu Cristian
Duu0163u,Anamaria Radoi,
Publication: 2019 International Conference on Speech Technology and
Human-Computer Dialogue (SpeD)
Emotion recognition has become an important field of research in the human-
computer interactions domain. The latest advancements in the field show that
combining visual with audio information lead to better results if compared to
the case of using a single source of information separately. From a visual
point of view, a human emotion can be recognized by analyzing the facial
expression of the person. More precisely, the human emotion can be described
through a combination of several Facial Action Units. In this paper, we
propose a system that is able to recognize emotions with a high accuracy rate
and in real time, based on deep Convolutional Neural Networks. In order to
increase the accuracy of the recognition system, we analyze also the speech
data and fuse the information coming from both sources, i.e., visual and audio.
Experimental results show the effectiveness of the proposed scheme for
emotion recognition and the importance of combining visual with audio data.",
20
Network (CNN). We explain these algorithms through the fundamental
research papers and go through their application to the task of FER.",
21
made out of two squares coordinated by the territory of the eyes and mouth,
delicate regions to changes human's demeanor and that are especially pertinent
for the disentangling of enthusiastic articulations. At long last we utilize the
blended picture as a contribution to a feed-forward neural organization
prepared by back-engendering. Such investigation of blended pictures causes
it conceivable, to acquire important data through the mix of appropriate
information in a similar picture and diminish the preparation set time while
saving grouping rate. It is appeared by test results that the proposed
calculation can distinguish feeling with great exactness.",
[Link]: Emotion Detection with Facial Feature Recognition Using CNN &
OpenCV
Authors: Sarwesh Giri,Gurchetan Singh,Babul Kumar,Mehakpreet
Singh,Deepanker Vashisht,Sonu Sharma,Prince Jain,
Publication: 2022 2nd International Conference on Advance Computing and
Innovative Technologies in Engineering (ICACITE)
Emotion Detection through Facial feature recognition is an active domain of
research in the field of human-computer interaction (HCI). Humans are able to
share multiple emotions and feelings through their facial gestures and body
language. In this project, in order to detect the live emotions from the human
facial gesture, we will be using an algorithm that allows the computer to
automatically detect the facial recognition of human emotions with the help of
Convolution Neural Network (CNN) and OpenCV. Ultimately, Emotion
Detection is an integration of obtained information from multiple patterns. If
computers will be able to understand more of human emotions, then it will
mutually reduce the gap between humans and computers. In this research
paper, we will demonstrate an effective way to detect emotions like neutral,
happy, sad, surprise, angry, fear, and disgust from the frontal facial expression
of the human in front of the live webcam.",
22
[Link]: Emotion Detection using Deep Facial Features
Authors: Hari Kishan Kondaveeti,Mogili Vishal Goud,
Publication: 2020 IEEE International Conference on Advent Trends in
Multidisciplinary Research and Innovation (ICATMRI)
Emotion Detection became one of the most efficient and challenging activities
in human interactions. In general, facial gestures are normal and clear means
of expressing their feelings and intentions to human beings. The main features
of non-verbal conversations are facial expressions. The study of the
techniques of Face Emotion Recognition involves three key phases, like pre-
processing, extracting of features and, classification techniques. This paper
proposes the comparison of deep learning architectures available in Keras for
emotion detection using the Deep Facial Features in images using Transfer
Learning from famous pre-trained models like VGG-16, ResNet152V2,
InceptionV3, and Xception and generating bottleneck features for our input
images. The performance of these models is evaluated based on the dataset
which is a combination of the Cohn-Kanade Dataset (CK+) and Japanese
female facial emotion (JAFFE). For the above-mentioned architectures, the
accuracies obtained are 83.16 %, 82.15 %, 77.1 %, 78.11 % respectively.",
23
recommendation systems, pattern recognition etc. Emotion plays a vital role in
determining the thoughts, behaviour and feeling of a human. An emotion
recognition system can be built by utilizing the benefits of deep learning and
different applications such as feedback analysis, face unlocking etc. can be
implemented with good accuracy. The main focus of this work is to create a
Deep Convolutional Neural Network (DCNN) model that classifies 5 different
human facial emotions. The model is trained, tested and validated using the
manually collected image dataset.",
24
CHAPTER 3
SYSTEM DESIGN
25
3.3 BLOCK DIAGRAM
26
3.4 METHODLOGY
The project's methodology begins with the collection of a diverse dataset for
training the Convolutional Neural Network (CNN) used for facial expression
analysis. This dataset encompasses a broad spectrum of facial expressions
associated with different stress levels. Concurrently, data from the
MAX30100 sensor, capturing physiological parameters such as temperature
and blood pressure, is collected. The K-Nearest Neighbors (KNN) algorithm
is then employed to process the sensor data. The integration of these two
datasets is achieved through advanced machine learning algorithms,
facilitating a comprehensive and nuanced synthesis of facial and physiological
metrics. This dual-modality approach enhances the depth and accuracy of
stress level assessment, overcoming the limitations of singular methodologies.
27
CHAPTER 4
HARDWARE DESCRIPTION
The Atmel AVR® core combines a rich instruction set with 32 general
purpose working registers. All the 32 registers are directly connected to the
Arithmetic Logic Unit (ALU), allowing two independent registers to be
accessed in a single instruction executed in one clock cycle. The resulting
architecture is more code efficient while achieving throughputs up to ten times
faster than conventional CISC microcontrollers. The ESP8266/P provides the
following features: 32Kbytes of In-System Programmable Flash with Read-
While-Write capabilities, 1Kbytes EEPROM, 2Kbytes SRAM, 23 general
purpose I/O lines, 32 general purpose working registers, Real Time Counter
(RTC), three flexible Timer/Counters with compare modes and PWM, 1 serial
programmable USARTs , 1 byte-oriented 2-wire Serial Interface (I2C), a 6-
channel 10- bit ADC (8 channels in TQFP and QFN/MLF packages) , a
programmable Watchdog Timer with internal Oscillator, an SPI serial port,
28
and six software selectable power saving modes.
This allows very fast start-up combined with low power consumption. In
Extended Standby mode, both the main oscillator and the asynchronous timer
continue to run. Atmel offers the QTouch® library for embedding capacitive
touch buttons, sliders and wheels functionality into AVR microcontrollers.
The patented charge-transfer signal acquisition offers robust sensing and
includes fully debounced reporting of touch keys and includes Adjacent Key
Suppression® (AKS™) technology for unambiguous detection of key events.
The easy-to-use Q Touch Suite toolchain allows you to explore, develop and
debug your own touch applications. The device is manufactured using
Atmel’s high density non-volatile memory technology. The On-chip ISP Flash
allows the program memory to be reprogrammed In-System through an SPI
serial interface, by a conventional non-volatile memory programmer, or by an
On-chip Boot program running on the AVR core.
29
Fig 4.2.1 Pin diagram of ESP8266
30
RTC: Yes with Separate Oscillator
MSSP: SPI and I²C Master and Slave Support
USART: Yes
External Oscillator: up to 20MHz
ADVANTAGES/ IMPROVEMENTS IN ESP8266
Still runs on 5 V, so legacy 5 V stuff interfaces cleaner
Even though it's 5 V capable, newer parts can run to 1.8 V. This wide range is
very rare.
Nice instruction set, very good instruction throughput compared to other
processors (HCS08, PIC12/16/18).
High quality GCC port (no proprietary crappy compilers!)
"PA" variants have good sleep mode capabilities, in micro-amperes.
Well rounded peripheral set
Q Touch capability
Pin Descriptions table
VCC
Digital supply voltage.
GND
Ground.
31
circuit.
Depending on the clock selection fuse settings, PB7 can be used as output
from the inverting Oscillator amplifier.
If the Internal Calibrated RC Oscillator is used as chip clock source, PB [7:6]
is used as TOSC [2:1] input for the Asynchronous Timer/Counter2 if the AS2
bit in ASSR is set.
4.6 PC6/RESET
If the RSTDISBL Fuse is programmed, PC6 is used as an I/O pin. Note that
the electrical characteristics of PC6 differ from those of the other pins of Port
C.
If the RSTDISBL Fuse is unprogrammed, PC6 is used as a Reset input. A low
level on this pin for longer than the minimum pulse length will generate a
Reset, even if the clock is not running. Shorter pulses are not guaranteed to
generate a [Link] various special features of Port ‘C’ are elaborated in the
Alternate Functions of Port C section.
32
(selected for each bit). The Port D output buffers have symmetrical drive
characteristics with both high sink and source capability. As inputs Port D
pins that are externally pulled low will source current if the pull-up resistors
are activated. The Port D pins are tri-stated when a reset condition becomes
active, even if the clock is not running.
4.8 AVCC
AVCC is the supply voltage pin for the A/D Converter, PC [3:0], and PE [3:2].
It should be externally connected to VCC, even if the ADC is not used. If the
ADC is used, it should be connected to VCC through a low-pass filter. Note
that PC [6:4] use digital supply voltage, VCC.
33
NODEMCU board can be powered by using the USB cable from computer.
All we need to do is connect the USB cable to the USB connection (1).
Power (Barrel Jack)
NODEMCU boards can be powered directly from the AC mains power supply
by connecting it to the Barrel Jack.
34
which can be used to ground wer circuit.
Vin (9) − This pin also can be used to power the NODEMCU board from an
external power source, like AC mains power supply.
Analog pins
The NODEMCU UNO board has five analog input pins A0 through A5.
These pins can read the signal from an analog sensor like the humidity sensor
or temperature sensor and convert it into a digital value that can be read by the
microprocessor.
4.13 MAX30100 :
The MAX30100 is an integrated pulse oximetry and heartrate monitor sensor
solution. It combines two LEDs, a photodetector, optimized optics, and low-
noise analog signal processing to detect pulse oximetry and heart-rate signals.
The MAX30100 operates from 1.8V and 3.3V power supplies and can be
powered down through software with negligible standby current, permitting
the power supply to remain connected at all times.
Applications
● Wearable Devices
● Fitness Assistant Devices
● Medical Monitoring Devices
35
• Programmable Sample Rate and LED Current for Power Savings
• Ultra-Low Shutdown Current (0.7µA, typ)
● Advanced Functionality Improves Measurement Performance
• High SNR Provides Robust Motion Artifact Resilience
• Integrated Ambient Light Cancellation
• High Sample Rate Capability
• Fast Data Output Capability
36
Fig 4.13.2 Humidity Sensor
37
Fig 4.13.4 8-bit SOIC-14 IC
Note that the sampling rate of the DHT11 is 1Hz, meaning you can get new
data from it once every second.
38
4.15 Supporting Circuitry
The module comes with all the essential supporting circuitry, so it should be
ready to run without any extra components.
The DHT11 sensors usually require external pull-up resistor of 10KΩ between
VCC and Out pin for proper communication between sensor and the Arduino.
However, the module has a built-in pull-up resistor, so you need not add it.
The module also has a decoupling capacitor for filtering noise on the power
supply.
DHT11 Module Pinout
The DHT11 module is fairly easy to connect. It has only three pins:
39
Fig 4.15.2 DHT11 Module Pinout
40
Fig 4.15.3 Audrino UNO
41
CHAPTER 5
SOFTWARE DESCRIPTION
42
in version 1.0 and later, the software will automatically rename the extension
to .ino.
Tabs, Multiple Files, and Compilation
Allows you to manage sketches with more than one file (each of which
appears in its own tab). These can be normal Arduino code files (no
extension), C files (.c extension), C++ files (.cpp), or header files (.h).
Uploading
Before uploading your sketch, you need to select the correct items from
the Tools Board and Tools Serial Portmenus. The boards are described below.
On the Mac, the serial port is probably something
like /dev/tty.usbmodem241(for an Uno or Mega2560 or Leonardo)
or /dev/[Link]-1B1 (for a Duemilanove or earlier USB board),
or/dev/tty.USA19QW1b1P1.1 (for a serial board connected with a Keyspan
USB-to-Serial adapter). On Windows, it's probably COM1 or COM2 (for a
serial board) or COM4, COM5, COM7, or higher (for a USB board) - to find
out, you look for USB serial device in the ports section of the Windows
Device Manager. On Linux, it should be /dev/ttyUSB0,/dev/ttyUSB1 or
similar.
Once you've selected the correct serial port and board, press the upload button
in the toolbar or select the Upload item from the File menu. Current Arduino
boards will reset automatically and begin the upload. With older boards (pre-
Diecimila) that lack auto-reset, you'll need to press the reset button on the
board just before starting the upload. On most boards, you'll see the RX and
TX LEDs blink as the sketch is uploaded. The Arduino environment will
display a message when the upload is complete, or show an error.
When you upload a sketch, you're using the Arduino bootloader, a small
program that has been loaded on to the microcontroller on your board. It
allows you to upload code without using any additional hardware. The
bootloader is active for a few seconds when the board resets; then it starts
43
whichever sketch was most recently uploaded to the microcontroller. The
bootloader will blink the on-board (pin 13) LED when it starts (i.e. when the
board resets).
Libraries
Libraries provide extra functionality for use in sketches, e.g. working with
hardware or manipulating data. To use a library in a sketch, select it from
the Sketch Import Library menu. This will insert one or more statements at
the top of the sketch and compile the library with your sketch. Because
libraries are uploaded to the board with your sketch, they increase the amount
of space it takes up. If a sketch no longer needs a library, simply delete it from
the top of your code.
There is a list of libraries in the reference. Some libraries are included with the
Arduino software. Others can be downloaded from a variety of sources.
Starting with version 1.0.5 of the IDE, you do can import a library from a zip
file and use it in an open sketch. See these instructions for installing a third-
party library.
5.2 PROGRAMMING
The Arduino Uno can be programmed with the Arduino software (download).
Select "Arduino Uno from the Tools Board menu (according to the
microcontroller on your board). For details, see the reference and tutorials.
The ATmega328 on the Arduino Uno comes preburned with a bootloader that
allows you to upload new code to it without the use of an external hardware
programmer. It communicates using the original STK500 protocol
(reference, C header files).
You can also bypass the bootloader and program the microcontroller through
the ICSP (In-Circuit Serial Programming) header; see these instructions for
details.
The ATmega16U2 (or 8U2 in the rev1 and rev2 boards) firmware source code
44
is available . The ATmega16U2/8U2 is loaded with a DFU bootloader, which
can be activated by:
• On Rev1 boards: connecting the solder jumper on the back of the board
(near the map of Italy) and then resetting the 8U2.
• On Rev2 or later boards: there is a resistor that pulling the 8U2/16U2
HWB line to ground, making it easier to put into DFU mode.
You can then use Atmel's FLIP software (Windows) or the DFU
programmer (Mac OS X and Linux) to load a new firmware. Or you can use
the ISP header with an external programmer (overwriting the DFU
bootloader). See this user-contributed tutorial for more information.
Automatic (Software) Reset
Rather than requiring a physical press of the reset button before an upload, the
Arduino Uno is designed in a way that allows it to be reset by software
running on a connected computer. One of the hardware flow control lines
(DTR) of theATmega8U2/16U2 is connected to the reset line of
the ATmega328 via a 100 nanofarad capacitor. When this line is asserted
(taken low), the reset line drops long enough to reset the chip. The Arduino
software uses this capability to allow you to upload code by simply pressing
the upload button in the Arduino environment. This means that the bootloader
can have a shorter timeout, as the lowering of DTR can be well-coordinated
with the start of the upload.
This setup has other implications. When the Uno is connected to either a
computer running Mac OS X or Linux, it resets each time a connection is
made to it from software (via USB). For the following half-second or so, the
bootloader is running on the Uno. While it is programmed to ignore
malformed data (i.e. anything besides an upload of new code), it will intercept
the first few bytes of data sent to the board after a connection is opened. If a
sketch running on the board receives one-time configuration or other data
when it first starts, make sure that the software with which it communicates
45
waits a second after opening the connection and before sending this data.
The Uno contains a trace that can be cut to disable the auto-reset. The pads on
either side of the trace can be soldered together to re-enable it. It's labeled
"RESET-EN". You may also be able to disable the auto-reset by connecting a
110 ohm resistor from 5V to the reset line; see this forum thread for details.
46
every single feature, or even every commonly used feature. Instead, it
introduces many of Python’s most notes worthy features, and will give you a
good idea of the language’s flavor and style. After reading it, you will be able
to read and write Python modules and programs, and you will be ready to
learn more about the various Python library modules described in library-
index. If you do much work on computers, eventually you find that there’s
some task you’d like
to automate. For example, you may wish to perform a search-and-replace over
a large number of text files, or rename and rearrange a bunch of photo files in
a complicated way. Perhaps you’d like to write a small custom database, or a
specialized
GUI application or a simple game. If you’re a professional software developer,
you may have to work with several C/C++/Java libraries but find the usual
write/compile/test/re-compile cycle is too slow. Perhaps you’re writing a test
suite for such a library and find writing the testing code a tedious task. Or
maybe you’ve written a program that could use an extension language, and
you don’t want to design and implement a whole new language for your
application.
Typing an end-of-file character (Control-D on Unix, Control-Z on Windows)
at the primary prompt causes the interpreter to exit with a zero exit status. If
that doesn’t work, you can exit the interpreter by typing the following
command: quit(). The interpreter’s line-editing features include interactive
editing, history substitution and code completion on systems that support read
line. Perhaps the quickest check to see whether command line editing is
supported is typing Control-P to the first Python prompt you get. If it beeps,
you have command line editing; see Appendix Interactive Input Editing and
History Substitution for an introduction to the keys. Ifnothing appears to
happen, or if ^P is echoed, command line editing isn’t available; you’ll only
be able to use backspace to remove characters from the current line. The
47
interpreter operates somewhat like the Unix shell: when called with standard
input connected to a tty device, it reads and executes commands interactively;
when called with a file name argument or with a file as standard input, it reads
and executes a script from that file. A second way of starting the interpreter is
python -c command [arg] ..., which executes the statement(s) in command,
analogous to the shell’s -c option. Since Python statements often contain
spaces or other characters that are special to the shell, it is usually advised to
quote commands in its entirety with single [Link] Python modules are
also useful as scripts. These can be invoked using python-m module
[arg]...,which executes the source file for the module as if you had spelled out
its full name on the command line. When a script file is used, it is sometimes
useful to be able to run the script and enter interactive mode afterwards. This
can be done by passing -i before the script.
There are tools which use doc strings to automatically produce online or
printed documentation or to let the user interactively browse through code; it’s
good practice to include doc strings in code that you write, so make a habit of
it. The execution of a function introduces a new symbol table used for the
local variables of the function. More precisely, all variable assignments in a
functions to read the value in the local symbol table; whereas variable
references first look in the local symbol table, then in the local symbol tables
of enclosing functions, then in the global symbol table, and finally in the table
of built-in names. Thus, global variables cannot be directly assigned a value
within a function (unless named in a global statement), although they may be
referenced. The actual parameters (arguments) to a function call are
introduced in the local symbol table of the called function when it is called;
thus, arguments are passed using call by value (where the value is always an
object reference, not the value of the object).1 When a function calls another
function, a new local symbol table is created for that call. A function
definition introduces the function name in the current symbol table. The value
48
of the function name has a type that is recognized by the interpreter as a user-
defined function. This value can be assigned to another name which can then
also be used as a function.
Annotations are stored in the annotations attribute of the function as a
dictionary and haven o effect on any other part of the function. Parameter
annotations are defined by a colon after the parameter name, followed by an
expression evaluating to the value of the annotation. Return annotationsare
defined by a literal ->, followed by an expression, between the parameter list
and the colon denoting the end of the def statement.
The comparison operators in and not in check whether a value occurs (does
not occur) in a sequence. The operator is and does not compare whether two
objects are really the same object; this only matters for mutable objects like
lists. All comparison operators have the same priority, which is lower than
that of all numerical operators. Comparisons can be chained. For example, a <
b == c tests whether a is less than b and moreover b equals c. Comparisons
may be combined using the Boolean operators and the outcome of a
comparison (or of any other Boolean expression) may be negated with not.
These have lower priorities than comparison operators; between them, not has
the highest priority and or the lowest, so that A and not B or C is equivalent to
(A and (not B)) or C. As always, parentheses can be used to express the
desired composition. The Boolean operators and are so-called short-circuit
operators: their arguments are evaluated from left to right, and evaluation
stops as soon as the outcome is determined. For example, if A and C are true
but Bis false, A and B and C does not evaluate the expression C. When used
as a general value and not as a Boolean, the return value of a short-circuit
operator is the last evaluated argument.
Classes provide a means of bundling data and functionality together. Creating
a new class creates a new type of object, allowing new instances of that type
to be made. Each class instance can have attributes attached to it for
49
maintaining its state. Class instances can also have methods (defined by its
class) for modifying its state. Compared with other programming languages,
Python’s class mechanism adds classes with a minimum of new syntax and
semantics. It is a mixture of the class mechanisms found in C++ and Modula-
3. Python classes provide all the standard features of Object Oriented
Programming: the class inheritance mechanism allows multiple base classes, a
derived class can override any methods of its base class or classes, and a
method can call the method of a base class with the same name. Objects can
contain arbitrary amounts and kinds of data. As is true for modules, classes
partake of the dynamic nature of Python: they are created at runtime, and can
be modified further after creation. In C++ terminology, normally class
members (including the data members) are public (except see below Private
Variables), and all member functions are virtual. A sin Modula-3, there are no
short hands for referencing the object’s members from its methods: the
method function is declared with an explicit first argument representing the
object, which is provided implicitly by the call. A sin Small talk, classes
themselves are objects. This providesSemantics for importing and renaming.
Unlike C++ and Modula-3, built-in types can be used as base classes for
extension by the user. Also, like in C++, most built-in operators with special
syntax (arithmetic operators, sub scripting etc.) can be redefined for class
instances.(Lacking universally accepted terminology to talk about classes, I
will make occasional use of Smalltalk and C++ terms. I would use Modula-3
terms, since its object- oriented semantics are closer to those of Python than
C++, but I expect that few readers have heard of it.)
Objects have individuality, and multiple names (in multiple scopes) can be
bound to the same object. This is known as aliasing in other languages. This is
usually not appreciated on a first glance at Python, and can be safely ignored
when dealing with immutable basic types (numbers, strings, tuples).However,
aliasing has a possibly surprising effect on these mantic of Python code
50
involving mutable objects such as lists, dictionaries, and most other types.
This is usually used to the benefit of the program, since aliases behave like
pointers in some respects. For example, passing an object is cheap since only
a pointer is passed by the implementation; and if a function modifies an object
passed as an argument, the caller will see the change — this eliminates the
need for two different argument passing mechanisms as in Pascal.
A namespace is a mapping from names to objects. Most name spaces are
currently implemented as Python dictionaries, but that’s normally not
noticeable in any way (except for performance), and it may change in the
future. Examples of name spaces are: these to f built-in names (containing
functions such as abs(), and built-in exception names); the global names in a
module; and the local names in a function invocation. In a sense the set of
attributes of an object also form a namespace. The important thing to know
about namespaces is that there is absolutely no relation between names in
different namespaces; for instance, two different modules may both define a
function maximize without confusion — users of the modules must prefix it
with the module name. By the way, I use the word attribute for any name
following a dot — for example, in the expression z. real, real is an attribute of
the object z. Strictly speaking, references to names in modules are attribute
references: in the expression [Link], modname is a module
object and funcname is an attribute of it. In this case there happens to be a
straight forward mapping between the module’s attributes and the global
names defined in the module: they share the same namespace!1 Attributes
may be read-only or writable. In the latter case, assignment to attributes is
possible. Module attributes are writable: you can write
modname.the_answer = 42. Writable attributes may also be deleted with the
del statement. For example, del mod name .the_ answer will remove the
attribute the_answer from the object named by mod name. Namespaces are
created at different moments and have different lifetimes. The namespace
51
containing the built-in names is created when the Python interpreter starts up,
and is never deleted. The global namespace for a module is created when the
module definition is read in; normally, module namespaces also last until the
interpreter [Link] statements executed by the top-level invocation of the
interpreter, either read from a script file or interactively, are considered part of
a module called main, so they have their own global namespace.(The built-in
names actually also live in a module; this is called built ins.) The local
namespace for a function is created when the function is called, and deleted
when the function returns or raises an exception that is not handled within the
function. (Actually, forgetting would be a better way to describe what actually
happens.) Of course, recursive invocations each have their own local
namespace.
To speed uploading modules, Python caches the compiled version of each
module in the pycache directory under the name [Link], where
the version encodes the format of the compiled file; it generally contains the
Python version number. For example, in CPython release 3.3 the compiled
version of [Link] would be cached as pycache/[Link]. This
naming convention allows compiled modules from different releases and
different versions of Python to coexist. Python checks the modification date of
the source against the compiled version to see if it’s out of date and needs to
be recompiled. This is a completely automatic process. Also, the compiled
modules are platform-independent, so the same library can be shared among
systems with different architectures. Python does not check the cache in two
circumstances. First, it always recompiles and does not store the result for the
module that’s loaded directly from the command line. Second, it does not
check the cache if there is no source module. To support anon-source
(compiled only) distribution, the compiled module must be in the source
directory, and there must not be a source module. Some tips for experts:
You can use the -O or -OO switches on the Python command to reduce the
52
size of a compiled module. The -O switch removes assert statements, the -OO
switch removes both assert statements and doc strings. Since some programs
may rely on having these available, you should only use this option if you
know what you’re doing. “Optimized” modules have an opt- tag and are
usually smaller. Future releases may change the effects of optimization. A
program doesn’t run any faster when it is read from a .pyc file than when it is
read from a .py file; the only thing that’s faster about .pyc files is the speed
with which they are loaded. The module compile all can create .pyc files for
all modules in a directory. There is more detail on this process, including a
flow chart of the decisions
53
% ./configure
% make
% make install
The configure script supports several common options, for a detailed list, type
% ./configure --help
There are also some compile time options which can be found in
src/Thonny .h. Please see Appendix C for more information. In the case that
your system lacks dynamic linking loader support, you probably want to pass
the option --disable-vte to the configure script. This prevents
compiling Thonny with dynamic linking loader support to automatically load
[Link].4 if available. Thonny has been successfully compiled and tested
under Debian 3.1 Sarge, Debian 4.0 Etch, Fedora Core 3/4/5, Linux From
Scratch and FreeBSD 6.0. It also compiles under Microsoft Windows.
At startup, Thonny loads all files from the last time Thonny was launched.
You can disable this feature in the preferences dialog (see Figure 3-4). If you
specify some files on the command line, only these files will be opened, but
you can find the files from the last session in the file menu under the "Recent
files" item. By default this contains the last 10 recently opened files. You can
change the amount of recently opened files in the preferences dialog. You can
start several instances of Thonny , but only the first will load files from the
last session. To run a second instance of Thonny , do not specify any file
names on the command-line, or disable opening files in a running instance
using the appropriate command line option.
Thonny detects an already running instance of itself and opens files from the
54
command-line in the already running instance. So, Thonny can be used to
view and edit files by opening them from other programs such as a file
manager. If you do not like this for some reason, you can disable using the
first instance by using the appropriate command line option If you have
installed [Link] in your system, it is loaded automatically by Thonny , and
you will have a terminal widget in the notebook at the bottom. If Thonny
cannot find [Link] at startup, the terminal widget will not be loaded. So
there is no need to install the package containing this file in order to run
Thonny . Additionally, you can disable the use of the terminal widget by
command line option, for more information see [Link] can use this
terminal (from now on called VTE) nearly as an usual terminal program like
xterm. There is basic clipboard support. You can paste the contents of the
clipboard by pressing the right mouse button to open the popup menu and
choosing Paste. To copy text from the VTE, just select the desired text and
then press the right mouse button and choose Copy from the pop up menu. On
systems running the X Window System you can paste the last selected text by
pressing the middle mouse button in the VTE (on 2-button mice, the middle
button can often be simulated by pressing both mouse buttons together). As
long as a project is open, the Make and Run commands will use the project’s
settings, instead of the defaults. These will be used whichever document is
currently displayed. The current project’s settings are saved when it is closed,
or when Thonny is shut down. When restarting Thonny , the previously
opened project file that was in use at the end of the last session will be
[Link] will run the corresponding executable file, shell script or
interpreted script in a terminal window. Note that the Terminal tool path must
be correctly set in the Tools tab of the Preferences dialog - you can use any
terminal program that runs a Bourne compatible shell and accept the "-e"
command line argument to start a command. After your program or script has
finished executing, you will be prompted to press the return key. This allows
55
you to review any text output from the program before the terminal window is
closed.
By default the Compile and Build commands invoke the compiler and linker
with only the basic arguments needed by all programs. Using Set Includes and
Arguments you can add any include paths and compile flags for the compiler,
any library names and paths for the linker, and any arguments you want to use
when running Execute.
Thonny has basic printing support. This means you can print a file by
passing the filename of the current file to a command which actually prints the
file.
However, the printed document contains no syntax highlighting.
56
CHAPTER 6
WORKING
57
Implement a user-friendly interface for real-time stress level visualization,
providing insights into both emotional and physiological aspects.
58
CHAPTER 7
RESULTS
7.1 Output of CNN and KNN :
59
Fig 7.1.3 Accuracy vs Epoch
60
7.2 Classification Reports :
7.2.1 CNN :
Confusion Matrix :
[[509 4]
[ 16 730]]
7.2.2 KNN :
61
Accuracy is: 0.9841143764889992
62
CHAPTER 8
CONCLUSION
The real-time nature of the analysis, coupled with the seamless fusion of
facial and physiological data, positions the system as a valuable tool for
mental health monitoring and personalized stress management.
63
CHAPTER 9
REFERENCES
64
Radoi,"Emotion Recognition System from Speech and Visual Information
based on Convolutional Neural Networks",2019 International Conference on
Speech Technology and Human-Computer Dialogue (SpeD)
[Link] Balasubramanian,Pranshu Diwan,Rajeshwar Nadar,Anuradha
Bhatia,"Analysis of Facial Emotion Recognition",2019 3rd International
Conference on Trends in Electronics and Informatics (ICOEI)
[Link] Vamsi Krishna,Navuluri Sainath,A. Mary Posonia,"Speech
Emotion Recognition using Machine Learning",2022 6th International
Conference on Computing Methodologies and Communication (ICCMC)
[Link] Bhardwaj,Ashutosh Dixit,Kshitij Yadav,Gokul Rajan V,"A
Study on Human Emotion Detection",2021 International Conference on
Advance Computing and Innovative Technologies in Engineering (ICACITE)
[Link] Giri,Gurchetan Singh,Babul Kumar,Mehakpreet Singh,Deepanker
Vashisht,Sonu Sharma,Prince Jain,"Emotion Detection with Facial Feature
Recognition Using CNN & OpenCV",2022 2nd International Conference on
Advance Computing and Innovative Technologies in Engineering (ICACITE)
[Link] Kishan Kondaveeti,Mogili Vishal Goud,"Emotion Detection using
Deep Facial Features",2020 IEEE International Conference on Advent Trends
in Multidisciplinary Research and Innovation (ICATMRI)
14.E. Pranav,Suraj Kamal,C. Satheesh Chandran,M.H. Supriya,"Facial
Emotion Recognition Using Deep Convolutional Neural Network",2020 6th
International Conference on Advanced Computing and Communication
Systems (ICACCS)
[Link] Bhogan,Kedar Sawant,Nidhi Gondalekar,Rachel Carvalho,Vassant
Kalangutkar,Alleena Mathew,"Facial Emotion Detection using Machine
Learning and Deep Learning Algorithms",2023 2nd International Conference
on Edge Computing and Applications (ICECAA)
65
Preprocessing and feature extraction are crucial to enhancing the performance of facial emotion recognition systems as they prepare and refine data for subsequent classification. Preprocessing removes noise and irrelevant data, improving image quality for analysis. Feature extraction simplifies the model learning process by highlighting significant attributes, such as facial landmarks, that are indicative of different emotions, thus enhancing accuracy and efficiency .
Machine learning, particularly through the use of sophisticated algorithms like deep learning, addresses the challenges of predicting human emotions by improving the accuracy and efficiency of facial recognition systems. These algorithms can handle high variability in data and uncover complex patterns that are not easily captured by traditional methods. However, challenges such as overfitting, data diversity, and real-time processing remain and need to be addressed for enhancing prediction accuracy .
Emotion detection systems have significant applications across various fields. In healthcare, they can be used to assess patient emotions to improve mental health diagnostics and treatment outcomes. In law enforcement, they assist in analyzing suspect emotions during interrogations to detect deceit or stress levels. Additionally, emotion detection can enhance human-computer interactions in customer service and entertainment by personalizing user experiences .
The primary steps involved in emotion detection using neural networks include face detection, feature extraction, and emotion classification. Convolutional neural networks (CNNs) contribute significantly to this process by providing a powerful architecture for efficiently extracting features from facial images, enabling accurate classification of emotions. CNNs handle complex features by using layers that gradually abstract facial characteristics, which are essential for differentiating emotions like happiness, anger, and sadness .
The most common facial expressions used in emotion recognition research include happiness, surprise, sadness, disgust, fear, and anger. These expressions are universal and provide clear, distinguishable cues to determine a person's emotional state. By quantifying these expressions through algorithms, researchers are able to consistently and accurately identify and classify emotions, which enhances the understanding of human behavior and aids in applications like mental health diagnostics and interactive systems .
Integrating audiovisual data in emotion recognition improves system accuracy by providing complementary information that visual data alone might miss. Audio cues can help disambiguate facial expressions, recognizing subtleties of emotions such as sarcasm or surprise that might not be apparent visually. Combining these data types leads to a more holistic understanding of human emotions and enhances recognition accuracy in real-time applications .
Experimental approaches to optimize CNNs for real-time emotion detection include varying network depths, employing max pooling, and utilizing dropout techniques to prevent overfitting. These methods have shown to significantly improve performance, achieving accuracies such as 89.98% on challenging datasets. The inclusion of real-time data from webcams also demonstrates effective parallel processing of multiple faces, showing the robustness and applicability of these models .
The evolution of machine learning and deep learning algorithms has significantly advanced the development of emotion recognition systems by enabling more sophisticated data analysis. These advancements allow systems to learn from vast datasets and uncover intricate patterns associated with human emotions, which traditional algorithms struggle to discern. As a result, systems now achieve higher accuracy, adaptability, and can be applied to a wider range of contexts and environments .
To mitigate overfitting in emotion detection models, researchers employ methodologies such as dropout layers and data augmentation. Dropout layers help by randomly disabling neurons during training, which promotes a robust network less sensitive to training data noise. Data augmentation increases dataset diversity, allowing models to generalize better. These approaches are effective in creating models that maintain high accuracy across unseen data instances .
CNN-based models achieve different levels of accuracy depending on the dataset used. For the FERC-2013 and JAFFE datasets, convolutional neural networks achieved accuracies of 70.14% and 98.65%, respectively. This indicates that the CNN model performs significantly better on the JAFFE dataset compared to FERC-2013, possibly due to differences in data quality, size, or variation within these datasets .