0% found this document useful (0 votes)
20 views51 pages

Groupdocument

The document discusses the development and benefits of AI-driven chatbots for mental health support, addressing the barriers individuals face in seeking traditional therapy. These chatbots utilize Natural Language Processing and Machine Learning to provide personalized, accessible, and confidential assistance, aiming to improve mental well-being and reduce stigma. The system also incorporates emergency protocols and continuous learning to adapt to user needs, ultimately empowering individuals to manage their mental health effectively.

Uploaded by

rahulrd252002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views51 pages

Groupdocument

The document discusses the development and benefits of AI-driven chatbots for mental health support, addressing the barriers individuals face in seeking traditional therapy. These chatbots utilize Natural Language Processing and Machine Learning to provide personalized, accessible, and confidential assistance, aiming to improve mental well-being and reduce stigma. The system also incorporates emergency protocols and continuous learning to adapt to user needs, ultimately empowering individuals to manage their mental health effectively.

Uploaded by

rahulrd252002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

AI-DRIVEN ASSISTANT CHATBOT FOR MENTAL

DISTURBANCE

ABSTRACT

Mental disturbance affects how a person thinks and behaves. They change their mood and
make it difficult to function at home, work, school, or in your community. It’s important to
note that having poor mental status doesn’t always mean you have a behavioral health
disorder. Almost 15% of the total population around the world is suffering from mental health
issues. This became one of the major concerns worldwide. Conventional methods like
Ayurvedic Medicine, Philosophical, and Spiritual Approaches are used to solve these
problems. But, they have disadvantages such as lack of evidence, harmful practices, delayed
treatment, etc. Millions of people wouldn’t go to a psychiatrist although doing so would
benefit greatly. When a person feels low he or she should share their feelings with another
person but, it is impossible for many people. Introverts won’t share their feelings with others
most of them have the fear of judgment. AI-driven chatbots have become the trend in the last
few years. This system overcomes the above issues by introducing AI-powered assistant
chatbots into the game. Nowadays millions of people worldwide are using AI-powered
assistant chatbots. This system detects mental disturbances in the early stages and cures them
initially, providing accessible, personalized, and effective support. Mental disturbances make
people lose concentration in day-to-day life like home, work, and other places. The history of
AI-driven assistant chatbots for mental disturbances is marked by rapid progress, increasing
recognition, and growing potential to transform mental health support. The objective of this
chatbot is to provide an efficient, cost-efficient solution for finding and solving mental health
problems. Utilizing Natural Language Processing (NLP) and Machine Learning (ML)
algorithms, these chatbots offer a confidential and accessible platform for users to share their
emotions, concerns, and experiences. Integrating traditional wisdom with modern technology
and AI-driven chatbots holds promise for enhanced mental health support and wellness.
CHAPTER 1

INTRODUCTION

1.1 Overview

A chatbot is a computer program that simulates a human conversation with an end user. Not
all chatbots are equipped with Artificial Intelligence (AI), but modern chatbots increasingly
use AI techniques such as NLP to understand user questions and automate responses to them.

This generation of chatbots with generative AI capabilities will provide even more enhanced
functionality, as they will understand common language and complex queries, adapt to a
user's style of conversation, and use empathy when answering users' questions.

1.2 Research Motivation

Clinical applications of AI for mental health care have experienced a rapid rise in the past few
years. AI-enabled chatbot software and applications have been used in significant medical
treatments that were previously only available by experienced healthcare professionals. Such
initiatives, such as “virtual psychiatrists” in mental health, try to improve nursing
performance and cost management, as well as meet the mental health needs of huge
populations.

There are millions of people in this world who wouldn’t go to a psychiatrist instead doing so
would benefit them so much. These people have so many reasons for not approaching a
psychiatrist they are fear of judgment, social stigma, etc. To help these people an AI-driven
mental health assistant chatbot is used which acts as a personal assistant and provides mental
health assistance.

1.3 Problem Statement

Despite the awareness of mental health and accessible traditional therapeutic methods have
brought barriers to people's pursuit of mental health care. Those obstacles include the
availability of the number of professionals in this field, the high price of therapy sessions,
the shame people have when reaching out, and the inability to obtain help urgently during a
state of urgency. Thus, individuals do not receive support when needed or at all, which then
deteriorates mental health problems and deteriorates the general well-being of the individual.
1.5 Objective

The Objective of this AI-driven chatbot is to provide immediate and accessible mental health
support in the wake of traditional therapy methods that have limitations concerning
accessibility and stigma. Other key features include personalized interaction powered by
advanced NLP, which allows the chatbot to answer responses based on individual user inputs
and adapt over time. According to the specific issues, coping strategies and self-help
techniques would be given to them. It will also enable mood tracking and feedback
mechanisms to people, thereby helping them to track their mental state. The anonymity of the
chatbot will reduce stigma over time regarding the seeking of help from anyone at any time
and place. This would also provide access to human therapists when appropriate, making it a
hybrid model, hence smoothly transitioning between AI support and professional care. It has
emergency protocols ensuring user safety in case of self-harm or suicidal thoughts,
connecting users with crisis services as needed. Continuous learning and improvement will
be part of the system, as user feedback will guide enhancements based on the latest research
in mental health and AI technology. Ultimately, this AI-driven chatbot aims to empower
people to take charge of their mental health and improve overall well-being by providing
accessible, personalized support.

1.5 Advantages
 Anxiety and Depression Support.
 Stress Management.
 Self-Care and Wellness.
 Workplace Wellness Initiatives.
 24/7 Availability.
 Global reach.
 User-friendly.
 Time Saving.
1.6 Applications
 Mental Health Education.
 Self-care and Wellness.
 Medical Billing and Insurance Support.
 Medical Research and Studies.
 Corporate Mental Health Research.
1. Accurate
2. User friendly
3. Time Saving
4. Secured
5. Availability around the
clock
6. Quickresponse to
common queries
7. Reduced Waiting
Times
8. Schedule Appointmen
9. Accurate
10.  User friendly
11.  Time Saving
12.  Secured
13.  Availability around
the clock
14. Quickresponse to

common queries
15. Reduced Waiting

Times
16. Schedule

Appointment User-Frien
CHAPTER 2

LITERATURE SURVEY

2.1 Introduction

AI-driven assistant chatbots are becoming an important tool in mental health care. Advanced
technology is the medium through which easy access and personal support have been given to
those facing challenges of mental health. This survey explores the usage of AI chatbots by
people and demonstrates the effectiveness and benefits of their use. In the literature, we find
studies that evaluate the performance and real-world application of AI chatbots in mental
health. These studies highlight how attention mechanisms enhance chatbot responses by
focusing on crucial parts of conversations.

2.2 Related Work

Mirko Casu, et al. [1] This study aimed to conduct a scoping review to evaluate the
effectiveness and feasibility of AI chatbots in treating mental health conditions. The author
utilized multiple databases, including Scopus, and PsycNet, as well as AI-powered tools like
Microsoft Copilot and Consensus. They developed chatbots that mimic human interaction
through written text, providing accessible health information and services. The research
provides accessible and scalable mental health interventions. Chatbots have demonstrated
effectiveness in improving mental well-being, addressing specific conditions like depression,
anxiety, and substance use disorders, and facilitating preventive care and health promotion.
Kirti Tomar, et al. [2] This study aimed at the promise and potential of using AI-powered
chatbots to provide accessible, immediate, and personalized support for mental health. These
chatbots help users manage their mental well-being through real-time coping strategies,
empathetic conversations, and continuous learning to adapt to individual needs. The authors
utilized it to understand and interpret user inputs, enabling the chatbot to respond
appropriately to predict user needs and continuously improve responses based on interactions.
They are dedicated to helping people identify their depressive or anxious symptoms, manage
their stress, and prevent the onset of mental illness. The research provides a one-step platform
where users find relevant information to help them in their journey. The users will also get
information related to stress management tips and other useful exercises.

Farhan Aslam. [3] The purpose of this research paper is to explore the current advancements
and leading innovations in AI-powered chatbot technology and examine their impact on
various industries. The study aims to analyze the application of NLP algorithms, machine
learning models, and deep learning in chatbot technology to gain insights into their
capabilities and limitations.

Luke Balcomb. [4] In this article, the authors explained AI chatbots are intelligent
conversational computer systems that think, learn, and complete tasks in combination with
humans or independently, NLP and ML algorithms expand their capabilities, improve
productivity, and provide conversation, guidance, and support. There are opportunities where
AI chatbots provide insightful responses beyond human capacity. However, they may lack a
personalized and empathetic touch. It is proposed that artificial intelligence may help
overcome such limitations, whereby humans and AI enable each other’s strengths to
collaborate on a common task or goal for efficient, safer, sustainable, and enjoyable work and
lives.

Gerard Anmella, et al. [5] This study explained that the chatbot was useful in screening for
the presence and severity of anxiety and depressive symptoms. Although anxiety and
depressive symptoms were not significantly reduced, there were significant reductions in
work-related burnout on follow-up self-assessments, thus suggesting the potential
effectiveness of Vickybot. Emergencies were accurately identified and prompt interventions
with successful outcomes were provided. Subjective perceptions of use (acceptability,
usability, and satisfaction) were high, in contrast to low objective-use metrics (completion,
adherence, compliance, and engagement), and the feasibility of the intervention was
moderate. Our results are promising but suggest the need to adapt and enhance the
smartphone-based solution to improve engagement.

Megha Gupta, et al. [6] This prospective study aims to examine the efficiency and use of an
AI-CBT intervention for chronic pain (Wysa for Chronic Pain app) using a conversational
agent (with no human intervention). To the best of our knowledge, this is the first such study
for chronic pain using a fully automated, free-text–based conversational agent.

Batyrkhan Omarov, et al. [7] This study described clinical applications of AI for mental
health care have experienced a meteoric rise in the past few years. AI-enabled chatbot
software and applications have been administering significant medical treatments that were
previously only available from experienced and competent healthcare professionals. Such
initiatives, which range from “virtual psychiatrists” to “social robots” in mental health, strive
to improve nursing performance and cost management, as well as meet the mental health
needs of vulnerable and underserved populations. Nevertheless, there is still a substantial gap
between recent progress in AI mental health and the widespread use of these solutions by
healthcare practitioners in clinical settings. Furthermore, treatments are frequently developed
without clear ethical concerns. While AI-enabled solutions show promise in the realm of
mental health.

David B.Olawade, et al. [8] This paper adopts a narrative review approach to
comprehensively investigate the utilization of AI in mental healthcare. The screening and
eligibility criteria for paper selection involved the inclusion of papers published in peer-
reviewed journals, conference proceedings, or reputable online databases, focusing on the
application of AI in mental healthcare, including review papers providing an overview,
analysis, or synthesis of existing literature. Exclusion criteria encompassed papers failing to
meet the inclusion criteria, duplicates, non-English publications, or those unrelated to the
review topic. The screening process consisted of three stages: title screening, abstract
screening, and full-text eligibility assessment, with papers not meeting inclusion criteria
being excluded at each stage. The authors utilized mental health chatbots to help patients with
anxiety and depression and provide valuable support to mental healthcare.

Ghazala Bilquise, et al. [9] This research explained how an artificial neural-based approach is
used to develop emotionally intelligent chatbots. Artificial neural network-based chatbots
apply both the retrieval-based and generative approaches for producing responses. It is
crucial to select preprocessing steps carefully when building an emotionally intelligent
chatbot, as different preprocessing techniques suit different contexts. For example, the NLP
process is primarily used to collect, tokenize, and parse information. Parsing is a technique
that implements algorithms.

Adwitiya Ray, et al. [10] This study detailed AI has immense potential to redefine our
diagnosis and help in better understanding of mental illnesses. A person’s mental health
depends on his/her unique bio-psycho-social profile but, we have a comparatively narrow
understanding of the interactions between these biological, psychological, and social systems.
There is substantial heterogeneity in the pathophysiology of mental illness and identification
of biomarkers will help to get more objective and refined definitions of these illnesses. AI
technologies have the ability to develop better pre-diagnostic screening tools and work out
risk models to determine an individual’s predisposition for or possibility of developing
mental illness.

Prabod Rathnayaka, et al. [11] This review explained conversational agents (chatbots)
automate the function of communicative labor, in written conversations. For instance, in
industrial settings, chatbots are used to provide information, and instructions, detect fatigue,
and address exceptions, while in healthcare, chatbots have been used for automated post-
treatment communications and support groups, counseling, and healthcare service
administrative support. Moreover, most chatbots are designed using Frequently Asked
Questions for information provision or process specific in executing a well-defined repetitive
or sequential series of tasks via conversational inputs. The major challenge for chatbots is in
emulating the natural flow of conversation between humans and the exchange of information
through this natural dialogue. NLP techniques and AI algorithms have been proposed and
leveraged to address this challenge.

K. Denecke, et al. [12] In this research paper, the authors talks about the use of
conversational agents, such as SERMO, that implement methods from CBT that help support
mentally ill people in regulating their emotions and dealing with their thoughts and feelings.
The study conducted on SERMO's user experience shows that the app was efficient, and
attractive to use. Although the fun of use was rated neutral, the overall findings suggest that
SERMO is a promising tool to help support the mental health of people worldwide.

Denecke, et al. [13] Explained that with the help of AI, the way humans are able to
understand each other and give a response accordingly is fed into the chatbot systems, i.e.
into systems that are supposed to communicate with a user. The bot understands the user’s
query and triggers an accurate response. In the healthcare domain, such chatbot-based
systems gain interest since they promise to increase adherence to electronically delivered
treatment and disease management programs. In this chapter, the authors provided an
overview of chatbot systems in mental health. AI is exploited in such systems for natural
language understanding, to create a human-like conversation, and to make appropriate
recommendations given a specific user utterance and mental state. Potential benefits of
chatbots have been shown with respect to psychoeducation and adherence.

Sagar Badlani, et al. [14] This study explained how a chatbot responds to user queries by
selecting the most pertinent answer from its knowledge database after determining Sentence
similarity using Turn Frequency-Inverse Document Frequency. Similarity. Due to its
multilingual capabilities, perfect chatbot system for use in rural India. English, Hindi, and
Gujarati are the three languages currently supported by the chatbot program. The chatbot
program engages in an NLP-based conversation with the user and supports text conversion.
In an attempt to predict disease, five alternative machine-learning algorithms were examined.
The random forest classifier has the highest accuracy (98.43%) and gives the best results.
Accordingly, it serves as the main classifier of the system. They are affordable and on-
demand and provide first guidance over one-on-one discussions. Doctors can utilize
healthcare chatbots to keep tabs on their patients.

Eliane M. Boucher, et al. [15] Explained that the most common application of chatbots within
Digital mental health interventions is to deliver content. While chatbots cannot simulate
traditional psychotherapy, they will administer psychotherapeutic interventions that do not
involve a high degree of therapeutic competence. For example, some chatbots using NLP can
simulate a therapeutic conversational style that implements and teaches users about various
therapeutic techniques. Chatbots employing principles of CBT are the most common and
well-studied one meta-analysis found that 10 out of 17 chatbots primarily used CBT. One
such chatbot, Woebot, delivers CBT to users via instant messaging employing NLP and
mimicking human clinicians and social discourse. Other chatbots utilize a variety of
therapeutic approaches, such as acceptance and commitment therapy and mindfulness.

Athulya N, et al. [16] In this research the authors created a medical chatbot that can diagnose
diseases and provide basic information about the disease before consulting
a doctor. Healthcare costs will be reduced, and more people will have access to medical
information, by adopting a medical chatbot. Chatbots are computer programs that
communicate with users using natural language. In this system, the user communicates with
the chatbot by SMS and the chatbot will reply to him by speech and text. If the user chats
with the chatbot, the bot will recognize the illness related to the user's queries. The bot
recommends experts who specialize in solving user problems and offers suggestions to solve
them. Multiple users use this system simultaneously without lag. The goal of this project is to
quickly and accurately predict diseases from their symptoms to consumers. For disease
prediction, a decision tree algorithm is used. By providing predictive diagnosis, chatbots
significantly contribute to the transformation of the healthcare sector.

Dosovitsky G, et al. [17] This research discusses a study on chatbots and mental health,
which found that user engagement was affected by the length, complexity, content, and style
of questions within the modules and routing between modules. The authors suggests that
developers should focus on usability and engagement by developing short, simple, and
consistent modules and testing them with small iterative studies before expanding the
content. The authors emphasize the importance of addressing high attrition rates and the
potential for scalable interventions and personalized interventions in the future.

Hiba Hussain, et al. [18] This study aims to provide consumers with rapid and precise disease
prediction based on symptoms and comprehensive pathology report analysis. ML and NLP
methods are used to create the disease prediction chatbot. We have employed the Decision
Tree and k-nearest neighbors classification algorithms for the disease prediction. The
efficiency of different methods is evaluated, and the best model is selected based on its
accuracy. This paper's results show that Decision Trees and KNNs have accuracy rates of
92.6% and 95.74%, respectively. This project anticipates offering medical advice on the
anticipated disease. The idea of OCR is used to analyze pathology reports. The free and open-
source OCR engine is called Tesseract. The language adopted from the report is used to
simplify the interpretation of results and to present a graphical breakdown of test results.

Danielle Belgrave, et al. [19] In this article, the authors explained the Application of
clustering for data labeling and subsequent development of a classifier to determine the
mental health state of a person as mentally stressed, neutral, or happy, development of a
framework to automatically predict low-, moderate-, and high-risk of suicide given mental
health history, risk assessment and clinical intervention data.

Laranjo L, et al. [20] This article reviews the current applications and evaluation measures of
conversational agents with unconstrained natural language input capabilities for health-
related purposes. A total of 17 articles met the inclusion criteria, and dialogue management
strategies were mostly finite-state and frame-based. Half of the conversational agents
supported consumers with health tasks such as self-care. The only randomized controlled trial
found a significant effect in reducing depression symptoms. The study concludes that more
robust experimental designs and standardized reporting are needed in this emerging
field of research.

2.3 Research Gaps

 Limited Personalization and Empathy in Chatbots.


 Limited Data on Long-Term Outcomes.
 Lack of Standardized Evaluation Metrics.
 The interface is not user-friendly.
 High maintenance.

2.4 Summary

Mental health has excellent potential to be supported with AI chatbots indeed, a solution to
conditions like depression, anxiety, and stress becomes accessible, scalable, and cost-
effective. The benefits of using them include support immediately available, coping
strategies, and education available, a few can learn with users to improve over time. Still, the
challenges abound in many different aspects very low user engagement calls for more
empathetic, more personalized responses, and many issues arise concerning clinical
integration. There is a need for further research into chatbots to be used in human care
advancing their capacity to understand emotions, long-term effectiveness, and working
through complexities of mental issues in the human mind. Standardized metrics will be
needed to establish success and ensure responsible application in the healthcare domain.
CHAPTER 3

EXISTING SYSTEM
Traditional therapy methods, such as talk therapy and CBT, have been the primary form of
mental health treatment for decades. While these methods have proven effective for many,
they have limitations. For example, traditional therapy is expensive, time-consuming, and not
always accessible, especially for those living in rural or remote areas. Moreover, there is a
stigma attached to seeking treatment that prevents many people from seeking help.

Humans have studied mental disturbances, and over centuries, diverse cultures have
developed unique ways to address these challenges. Traditional Chinese medicine, for
instance, has used the power of herbs like ginseng and ginkgo biloba to influence mood and
consciousness. Spiritual and religious practices, such as prayer, meditation, and rituals, have
been employed to seek divine intervention or spiritual guidance, offering hope.

Strong community bonds and social support networks have been important to mental well-
being in many traditional societies. Sharing experiences, offering empathy, and engaging in
collective rituals provide comfort and healing.
Physical therapies like yoga, tai chi, and acupuncture have been employed to balance energy
flow and promote mental well-being. These practices often combine physical movement,
breathing exercises, and meditation to harmonize the mind and body.

While these traditional methods offer some relief, it's important to remember that they should
not be considered substitutes for modern, evidence-based treatments for serious mental health
conditions. Consulting with a qualified mental health professional is crucial for proper
diagnosis and treatment. When integrated with modern medical approaches, some of these
traditional methods offer an approach to mental health care, providing a comprehensive
framework for addressing the complex interplay between mind, and body.

Limitations

 Traditional therapy methods, such as talk therapy and CBT, can be quite expensive.
 These methods often require significant time commitments.
 Therapy isn't always accessible, particularly for those in rural or remote areas.
 There is a social stigma attached to seeking mental health treatment, deterring many from
getting help.
 Diverse cultural practices may not align with modern mental health treatments, causing
potential conflicts.
 Traditional societies often rely heavily on strong community bonds, which might not be
available to everyone.
 Practices like yoga and acupuncture require physical participation, which might not be
feasible for all individuals.
 Traditional methods like herbal remedies and spiritual practices are not standardized,
leading to inconsistent results.
CHAPTER 4

PROPOSED SYSTEM

4.1 Overview

The name of our proposed AI-driven chatbot for mental health support is “Pandora” and it is
designed to provide accessible, text-based assistance for individuals experiencing various
mental disturbances. By engaging users in personalized conversations, the chatbot allows
them to express their feelings and concerns openly, showing a sense of connection and
understanding. This interaction is vital for those who feel isolated or unsure about discussing
their mental health with others.

The chatbot can also identify distress crises. If the user shows hopelessness, extreme anxiety,
or suicidal thoughts, the chatbot will know how to respond to it, and it will immediately
provide access to resources and even make a referral for professional assistance. It ensures
that users have resources available to them at a time when they need it most.

It is a mental health-aware resource through the provision of basic support to people trying to
better their mental health, giving a safe non-judgmental environment in which the user feels
at ease and can interact to examine thoughts and feelings as the individual chooses.
The interaction of this personalized assistant chatbot provides personalized content such as
jokes, humourous words, etc. Providing support around the clock gives the feel that it is
working only for you. This system helps in detecting health concerns at an early stage and
provides preventive measures for avoiding mental disturbances.
Figure: Block Diagram

JSON Dataset

The chatbot is trained using a dataset containing examples of user inputs (patterns) and
corresponding responses.

Text Preprocessing

The input text (user's message) is cleaned, tokenized (split into words), and converted into a
format that the machine learning model can process.

4.2 Model Training

The model is trained using two methodologies one of which gives best accuracy and is
selected for testing.

4.2.1 Existing Methodology: Random Forest Classifier (RFC)

A Random Forest Classifier is used for Intent classification. Random Forest is a meta
estimator that fits the number of Decision Trees on various sub-samples of training data and
gives the average accuracy and controls the over-fitting.

A Random Forest is an ensemble learning method that operates by constructing multiple deci
sion trees during training and outputting the class that is the mode of the classes (classificatio
n) of the individual trees.

How it's used in Chatbot Development


Data Collection: Gather a dataset of user queries and corresponding responses.

Preprocessing: Clean and preprocess the data to make it suitable for training the model.

Feature Extraction: Extract relevant features from the text data, such as keywords, phrases, or
embeddings.

Training the Model: Use the Random Forest Classifier to train the chatbot on the dataset. The
classifier will learn to predict the appropriate response based on the input query.

Drawbacks

Struggles with sequential data like conversation flow.

It doesn't handle time dependencies well, which are crucial in dialogues.

Low accuracy.

4.2.2 Proposed Methodology: Long Short-Term Memory (LSTM)

LSTM networks, an advanced type of Recurrent Neural Network (RNN), are fundamental in
modern chatbot development due to their unique capability to handle long-term dependencies
and sequential data. Traditional RNNs often struggle with remembering long sequences,
leading to the vanishing gradient problem, where the influence of older inputs diminishes
over time. LSTMs mitigate this issue by incorporating memory cells and gates that control
the flow of information, allowing them to maintain context over extended dialogues.

In chatbot applications, this ability to retain and utilize context is crucial. Conversations are
inherently sequential and context-dependent, requiring the bot to remember past interactions
to generate relevant and coherent responses. LSTMs excel in such environments by
preserving information over long sequences, enabling the chatbot to understand references to
earlier parts of the conversation and providing contextually appropriate responses.

Training an LSTM-based chatbot involves feeding the model large datasets of conversations,
helping it learn language patterns and the nuances of human dialogue. This process includes
converting text data into numerical formats using embeddings, which the LSTM then
processes to predict and generate natural responses. The result is a chatbot capable of
engaging in meaningful, human-like conversations, enhancing user experience.
Advantages

Handles conversational context better due to memory of previous inputs.

Captures long-term dependencies, improving response relevance.

More accurate for NLP tasks and generating coherent dialogue.

The LSTM model performs better (98% accuracy), while the Random Forest model has lower
accuracy (26%).

Model Prediction

When the user types a message, the model predicts the intent (meaning) of the message based
on what it has learned during training.

Response Generation

The chatbot selects a response from a pre-defined set of responses that match the predicted
intent.

Chatbot Interaction

The chatbot interacts with the user, displaying appropriate responses based on the user's
message.

CHAPTER 6

SOFTWARE ENVIRONMENT

What is Python?

Below are some facts about Python.

 Python is currently the most widely used multi-purpose, high-level programming


language.
 Python allows programming in Object-Oriented and Procedural paradigms. Python
programs generally are smaller than other programming languages like Java.
 Programmers have to type relatively less and the indentation requirement of the language
makes them readable all the time.
 Python language is being used by almost all tech-giant companies like – Google,
Amazon, Facebook, Instagram, Dropbox, Uber… etc.
The biggest strength of Python is a huge collection of standard libraries which can be used for
the following –

 Machine Learning
 GUI Applications (like Kivy, Tkinter, PyQt etc. )
 Web frameworks like Django (used by YouTube, Instagram, and Dropbox)
 Image processing (like Opencv, Pillow)
 Web scraping (like Scrapy, BeautifulSoup, Selenium)
 Test frameworks
 Multimedia
Advantages of Python

1. Extensive Libraries

Python downloads with an extensive library and it contain code for various purposes like
regular expressions, documentation-generation, unit-testing, web browsers, threading,
databases, CGI, email, image manipulation, and more. So, we don’t have to write the
complete code for that manually.

2. Extensible

As we have seen earlier, Python can be extended to other languages. You can write some of
your code in languages like C++ or C. This comes in handy, especially in projects.

3. Embeddable

Complimentary to extensibility, Python is embeddable as well. You can put your Python code
in your source code of a different language, like C++. This lets us add scripting capabilities to
our code in the other language.

4. Improved Productivity

The language’s simplicity and extensive libraries render programmers more productive than
languages like Java and C++ do. Also, the fact that you need to write less and get more things
done.
5. IOT Opportunities

Since Python forms the basis of new platforms like Raspberry Pi, it finds the future bright for
the Internet Of Things. This is a way to connect the language with the real world.

6. Simple and Easy

When working with Java, you may have to create a class to print ‘Hello World’. But in
Python, just a print statement will do. It is also quite easy to learn, understand, and code. This
is why when people pick up Python, they have a hard time adjusting to other more verbose
languages like Java.

7. Readable

Because it is not such a verbose language, reading Python is much like reading English. This
is the reason why it is so easy to learn, understand, and code. It also does not need curly
braces to define blocks, and indentation is mandatory. This further aids the readability of the
code.

8. Object-Oriented

This language supports both the procedural and object-oriented programming paradigms.
While functions help us with code reusability, classes and objects let us model the real world.
A class allows the encapsulation of data and functions into one.

9. Free and Open-Source

Like said earlier, Python is freely available. But not only can you download Python for free,
but you can also download its source code, make changes to it, and even distribute it. It
downloads with an extensive collection of libraries to help you with your tasks.

10. Portable

When you code your project in a language like C++, you may need to make some changes to
it if you want to run it on another platform. But it isn’t the same with Python. Here, you need
to code only once, and you can run it anywhere. This is called Write Once Run Anywhere
(WORA). However, you need to be careful enough not to include any system-dependent
features.

11. Interpreted
Lastly, will say that it is an interpreted language. Since statements are executed one by one,
debugging is easier than in compiled languages.

Any doubts till now in the advantages of Python? Mention in the comment section.

Advantages of Python Over Other Languages

1. Less Coding

Almost all of the tasks done in Python requires less coding when the same task is done in
other languages. Python also has an awesome standard library support, so you don’t have to
search for any third-party libraries to get your job done. This is the reason that many people
suggest learning Python to beginners.

2. Affordable

Python is free therefore individuals, small companies or big organizations can leverage the
free available resources to build applications. Python is popular and widely used so it gives
you better community support.

The 2019 Github annual survey showed us that Python has overtaken Java in the most
popular programming language category.

3. Python is for Everyone

Python code can run on any machine whether it is Linux, Mac, or Windows. Programmers
need to learn different languages for different jobs but with Python, you can professionally
build web apps, perform data analysis and machine learning, automate things, do web
scraping and also build games and powerful visualizations. It is an all-rounder programming
language.

Disadvantages of Python

So far, we’ve seen why Python is a great choice for your project. But if you choose it, you
should be aware of its consequences as well. Let’s now see the downsides of choosing Python
over another language.

1. Speed Limitations
We have seen that Python code is executed line by line. But since Python is interpreted, it
often results in slow execution. This, however, isn’t a problem unless speed is a focal point
for the project. In other words, unless high speed is a requirement, the benefits offered by
Python are enough to distract us from its speed limitations.

2. Weak in Mobile Computing and Browsers

While it serves as an excellent server-side language, Python is much rarely seen on the client-
side. Besides that, it is rarely ever used to implement smartphone-based applications. One
such application is called Carbonnelle.

The reason it is not so famous despite the existence of Brython is that it isn’t that secure.

3. Design Restrictions

As you know, Python is dynamically-typed. This means that you don’t need to declare the
type of variable while writing the code. It uses duck-typing. But wait, what’s that? Well, it
just means that if it looks like a duck, it must be a duck. While this is easy on the
programmers during coding, it can raise run-time errors.

4. Underdeveloped Database Access Layers

Compared to more widely used technologies like JDBC (Java DataBase Connectivity) and
ODBC (Open DataBase Connectivity), Python’s database access layers are a bit
underdeveloped. Consequently, it is less often applied in huge enterprises.

5. Simple

No, we’re not kidding. Python’s simplicity can indeed be a problem. Take my example. I
don’t do Java, I’m more of a Python person. To me, its syntax is so simple that the verbosity
of Java code seems unnecessary.

This was all about the Advantages and Disadvantages of Python Programming Language.

History of Python

What do the alphabet and the programming language Python have in common? Right, both
start with ABC. If we are talking about ABC in the Python context, it's clear that the
programming language ABC is meant. ABC is a general-purpose programming language and
programming environment, which had been developed in the Netherlands, Amsterdam, at the
CWI (Centrum Wiskunde &Informatica). The greatest achievement of ABC was to influence
the design of Python. Python was conceptualized in the late 1980s. Guido van Rossum
worked that time in a project at the CWI, called Amoeba, a distributed operating system. In
an interview with Bill Venners1, Guido van Rossum said: "In the early 1980s, I worked as an
implementer on a team building a language called ABC at Centrum voor Wiskunde en
Informatica (CWI). I don't know how well people know ABC's influence on Python. I try to
mention ABC's influence because I'm indebted to everything I learned during that project and
to the people who worked on it. "Later on in the same Interview, Guido van Rossum
continued: "I remembered all my experience and some of my frustration with ABC. I decided
to try to design a simple scripting language that possessed some of ABC's better properties,
but without its problems. So I started typing. I created a simple virtual machine, a simple
parser, and a simple runtime. I made my own version of the various ABC parts that I liked. I
created a basic syntax, used indentation for statement grouping instead of curly braces or
begin-end blocks, and developed a small number of powerful data types: a hash table (or
dictionary, as we call it), a list, strings, and numbers."

Python Development Steps

Guido Van Rossum published the first version of Python code (version 0.9.0) at alt.sources in
February 1991. This release included already exception handling, functions, and the core data
types of list, dict, str and others. It was also object oriented and had a module system.

Python version 1.0 was released in January 1994. The major new features included in this
release were the functional programming tools lambda, map, filter and reduce, which Guido
Van Rossum never liked. Six and a half years later in October 2000, Python 2.0 was
introduced. This release included list comprehensions, a full garbage collector and it was
supporting unicode. Python flourished for another 8 years in the versions 2.x before the next
major release as Python 3.0 (also known as "Python 3000" and "Py3K") was released. Python
3 is not backwards compatible with Python 2.x. The emphasis in Python 3 had been on the
removal of duplicate programming constructs and modules, thus fulfilling or coming close to
fulfilling the 13th law of the Zen of Python: "There should be one -- and preferably only one
-- obvious way to do it."Some changes in Python 7.3:

Print is now a function.

 Views and iterators instead of lists


 The rules for ordering comparisons have been simplified. E.g., a heterogeneous list
cannot be sorted, because all the elements of a list must be comparable to each other.
 There is only one integer type left, i.e., int. long is int as well.
 The division of two integers returns a float instead of an integer. "//" can be used to have
the "old" behaviour.
 Text Vs. Data Instead of Unicode Vs. 8-bit
Purpose

We demonstrated that our approach enables successful segmentation of intra-retinal layers—


even with low-quality images containing speckle noise, low contrast, and different intensity
ranges throughout with the assistance of the ANIS feature.

Python

Python is an interpreted high-level programming language for general-purpose programming.


Created by Guido van Rossum and first released in 1991, Python has a design philosophy that
emphasizes code readability, notably using significant whitespace.

Python features a dynamic type system and automatic memory management. It supports
multiple programming paradigms, including object-oriented, imperative, functional and
procedural, and has a large and comprehensive standard library.

 Python is Interpreted − Python is processed at runtime by the interpreter. You do not need
to compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive − you can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python also acknowledges that speed of development is important. Readable and terse code is
part of this, and so is access to powerful constructs that avoid tedious repetition of code.
Maintainability also ties into this may be an all but useless metric, but it does say something
about how much code you have to scan, read and/or understand to troubleshoot problems or
tweak behaviors. This speed of development, the ease with which a programmer of other
languages can pick up basic Python skills and the huge standard library is key to another area
where Python excels. All its tools have been quick to implement, saved a lot of time, and
several of them have later been patched and updated by people with no Python background -
without breaking.

Modules Used in Project


NumPy

NumPy is a general-purpose array-processing package. It provides a high-performance


multidimensional array object, and tools for working with these arrays.

It is the fundamental package for scientific computing with Python. It contains various
features including these important ones:

 A powerful N-dimensional array object


 Sophisticated (broadcasting) functions
 Tools for integrating C/C++ and Fortran code
 Useful linear algebra, Fourier transform, and random number capabilities
Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional
container of generic data. Arbitrary datatypes can be defined using NumPy which allows
NumPy to seamlessly and speedily integrate with a wide variety of databases.

Pandas

Pandas is an open-source Python Library providing high-performance data manipulation and


analysis tool using its powerful data structures. Python was majorly used for data munging
and preparation. It had very little contribution towards data analysis. Pandas solved this
problem. Using Pandas, we can accomplish five typical steps in the processing and analysis
of data, regardless of the origin of data load, prepare, manipulate, model, and analyze. Python
with Pandas is used in a wide range of fields including academic and commercial domains
including finance, economics, Statistics, analytics, etc.

Matplotlib

Matplotlib is a Python 2D plotting library which produces publication quality figures in a


variety of hardcopy formats and interactive environments across platforms. Matplotlib can be
used in Python scripts, the Python and IPython shells, the Jupyter Notebook, web application
servers, and four graphical user interface toolkits. Matplotlib tries to make easy things easy
and hard things possible. You can generate plots, histograms, power spectra, bar charts, error
charts, scatter plots, etc., with just a few lines of code. For examples, see the sample plots and
thumbnail gallery.

For simple plotting the pyplot module provides a MATLAB-like interface, particularly when
combined with IPython. For the power user, you have full control of line styles, font
properties, axes properties, etc, via an object oriented interface or via a set of functions
familiar to MATLAB users.

Scikit – learn

Scikit-learn provides a range of supervised and unsupervised learning algorithms via a


consistent interface in Python. It is licensed under a permissive simplified BSD license and is
distributed under many Linux distributions, encouraging academic and commercial use.
Python

Python is an interpreted high-level programming language for general-purpose programming.


Created by Guido van Rossum and first released in 1991, Python has a design philosophy that
emphasizes code readability, notably using significant whitespace.

Python features a dynamic type system and automatic memory management. It supports
multiple programming paradigms, including object-oriented, imperative, functional and
procedural, and has a large and comprehensive standard library.

 Python is Interpreted − Python is processed at runtime by the interpreter. You do not need
to compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive − you can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python also acknowledges that speed of development is important. Readable and terse code is
part of this, and so is access to powerful constructs that avoid tedious repetition of code.
Maintainability also ties into this may be an all but useless metric, but it does say something
about how much code you have to scan, read and/or understand to troubleshoot problems or
tweak behaviors. This speed of development, the ease with which a programmer of other
languages can pick up basic Python skills and the huge standard library is key to another area
where Python excels. All its tools have been quick to implement, saved a lot of time, and
several of them have later been patched and updated by people with no Python background -
without breaking.

Install Python Step-by-Step in Windows and Mac

Python a versatile programming language doesn’t come pre-installed on your computer


devices. Python was first released in the year 1991 and until today it is a very popular high-
level programming language. Its style philosophy emphasizes code readability with its
notable use of great whitespace.
The object-oriented approach and language construct provided by Python enables
programmers to write both clear and logical code for projects. This software does not come
pre-packaged with Windows.

How to Install Python on Windows and Mac

There have been several updates in the Python version over the years. The question is how to
install Python? It might be confusing for the beginner who is willing to start learning Python
but this tutorial will solve your query. The latest or the newest version of Python is version
3.7.4 or in other words, it is Python 3.

Note: The python version 3.7.4 cannot be used on Windows XP or earlier devices.

Before you start with the installation process of Python. First, you need to know about your
System Requirements. Based on your system type i.e. operating system and based processor,
you must download the python version. My system type is a Windows 64-bit operating
system. So the steps below are to install python version 3.7.4 on Windows 7 device or to
install Python 3. Download the Python Cheatsheet here.The steps on how to install Python on
Windows 10, 8 and 7 are divided into 4 parts to help understand better.

Download the Correct version into the system

Step 1: Go to the official site to download and install python using Google Chrome or any
other web browser. OR Click on the following link: https://www.python.org

Now, check for the latest and the correct version for your operating system.

Step 2: Click on the Download Tab.


Step 3: You can either select the Download Python for windows 3.7.4 button in Yellow Color
or you can scroll further down and click on download with respective to their version. Here,
we are downloading the most recent python version for windows 3.7.4

Step 4: Scroll down the page until you find the Files option.

Step 5: Here you see a different version of python along with the operating system.
 To download Windows 32-bit python, you can select any one from the three options:
Windows x86 embeddable zip file, Windows x86 executable installer or Windows x86
web-based installer.
 To download Windows 64-bit python, you can select any one from the three options:
Windows x86-64 embeddable zip file, Windows x86-64 executable installer or Windows
x86-64 web-based installer.
Here we will install Windows x86-64 web-based installer. Here your first part regarding
which version of python is to be downloaded is completed. Now we move ahead with the
second part in installing python i.e. Installation

Note: To know the changes or updates that are made in the version you can click on the
Release Note Option.

Installation of Python

Step 1: Go to Download and Open the downloaded python version to carry out the
installation process.
Step 2: Before you click on Install Now, Make sure to put a tick on Add Python 3.7 to PATH.

Step 3: Click on Install NOW After the installation is successful. Click on Close.

With these above three steps on python installation, you have successfully and correctly
installed Python. Now is the time to verify the installation.

Note: The installation process might take a couple of minutes.

Verify the Python Installation

Step 1: Click on Start

Step 2: In the Windows Run Command, type “cmd”.


Step 3: Open the Command prompt option.

Step 4: Let us test whether the python is correctly installed. Type python –V and press Enter.

Step 5: You will get the answer as 3.7.4

Note: If you have any of the earlier versions of Python already installed. You must first
uninstall the earlier version and then install the new one.

Check how the Python IDLE works

Step 1: Click on Start

Step 2: In the Windows Run command, type “python idle”.


Step 3: Click on IDLE (Python 3.7 64-bit) and launch the program

Step 4: To go ahead with working in IDLE you must first save the file. Click on File > Click
on Save

Step 5: Name the file and save as type should be Python files. Click on SAVE. Here I have
named the files as Hey World.

Step 6: Now for e.g. enter print (“Hey World”) and Press Enter.
You will see that the command given is launched. With this, we end our tutorial on how to
install Python. You have learned how to download python for windows into your respective
operating system.

Note: Unlike Java, Python does not need semicolons at the end of the statements otherwise it
won’t work.

CHAPTER 7

SYSTEM REQUIREMENTS

SOFTWARE REQUIREMENTS

The functional requirements or the overall description documents include the product
perspective and features, operating system and operating environment, graphics requirements,
design constraints, and user documentation.

The appropriation of requirements and implementation constraints gives the general overview
of the project in regard to what the areas of strength and deficit are and how to tackle them.

 Python IDLE 3.7 version (or)


 Anaconda 3.7 (or)
 Jupiter (or)
 Google colab
HARDWARE REQUIREMENTS

Minimum hardware requirements are very dependent on the particular software being
developed by a given Enthought Python / Canopy / VS Code user. Applications that need to
store large arrays/objects in memory will require more RAM, whereas applications that need
to perform numerous calculations or tasks more quickly will require a faster processor.

 Operating system : Windows, Linux


 Processor : minimum intel i3
 Ram : minimum 4 GB
 Hard disk : minimum 250GB

CHAPTER 8

FUNCTIONAL REQUIREMENTS
OUTPUT DESIGN

Outputs from computer systems are required primarily to communicate the results of
processing to users. They are also used to provides a permanent copy of the results for later
consultation. The various types of outputs in general are:

 External Outputs, whose destination is outside the organization


 Internal Outputs whose destination is within organization and they are the
 User’s main interface with the computer.
 Operational outputs whose use is purely within the computer department.
 Interface outputs, which involve the user in communicating directly.
OUTPUT DEFINITION

The outputs should be defined in terms of the following points:

 Type of the output


 Content of the output
 Format of the output
 Location of the output
 Frequency of the output
 Volume of the output
 Sequence of the output
It is not always desirable to print or display data as it is held on a computer. It should be
decided as which form of the output is the most suitable.

INPUT DESIGN

Input design is a part of overall system design. The main objective during the input design is
as given below:

 To produce a cost-effective method of input.


 To achieve the highest possible level of accuracy.
 To ensure that the input is acceptable and understood by the user.

INPUT STAGES

The main input stages are listed as below:

 Data recording
 Data transcription
 Data conversion
 Data verification
 Data control
 Data transmission
 Data validation
 Data correction
INPUT TYPES

It is necessary to determine the various types of inputs. Inputs can be categorized as follows:

 External inputs, which are prime inputs for the system.


 Internal inputs, which are user communications with the system.
 Operational, which are computer department’s communications to the system?
 Interactive, which are inputs entered during a dialogue.
INPUT MEDIA

At this stage choice has to be made about the input media. To conclude about the input
media consideration has to be given to;

 of input
 Type Flexibility of format
 Speed
 Accuracy
 Verification methods
 Rejection rates
 Ease of correction
 Storage and handling requirements
 Security
 Easy to use
 Portability
Keeping in view the above description of the input types and input media, it can be said that
most of the inputs are of the form of internal and interactive.

Input data is to be the directly keyed in by the user, the keyboard can be considered to be the
most suitable input device.

ERROR AVOIDANCE

At this stage care is to be taken to ensure that input data remains accurate form the stage at
which it is recorded up to the stage in which the data is accepted by the system. This can be
achieved only by means of careful control each time the data is handled.

ERROR DETECTION

Even though every effort is make to avoid the occurrence of errors, still a small proportion of
errors is always likely to occur, these types of errors can be discovered by using validations
to check the input data.

DATA VALIDATION

Procedures are designed to detect errors in data at a lower level of detail. Data validations
have been included in the system in almost every area where there is a possibility for the user
to commit errors. The system will not accept invalid data. Whenever an invalid data is
keyed in, the system immediately prompts the user and the user has to again key in the data
and the system will accept the data only if the data is correct. Validations have been included
where necessary.
The system is designed to be a user friendly one. In other words the system has been
designed to communicate effectively with the user. The system has been designed with
popup menus.

USER INTERFACE DESIGN

It is essential to consult the system users and discuss their needs while designing the user
interface:

USER INTERFACE SYSTEMS CAN BE BROADLY CLASIFIED AS:

 User initiated interface the user is in charge, controlling the progress of the user/computer
dialogue. In the computer-initiated interface, the computer selects the next stage in the
interaction.
 Computer initiated interfaces
In the computer-initiated interfaces the computer guides the progress of the user/computer
dialogue. Information is displayed and the user response of the computer takes action or
displays further information.

USER-INITIATED INTERFACES

User-initiated interfaces fall into two approximate classes:

 Command-driven interfaces: In this type of interface the user inputs commands or queries
which are interpreted by the computer.
 Forms-oriented interface: The user calls up an image of the form to his/her screen and
fills in the form. The forms-oriented interface is chosen because it is the best choice.
COMPUTER-INITIATED INTERFACES

The following computer–initiated interfaces were used:

 The menu system for the user is presented with a list of alternatives and the user chooses
one; of the alternatives.
 Questions–answer type dialog system where the computer asks questions and takes action
based on the basis of the user's reply.
Right from the start the system is going to be menu-driven, the opening menu displays the
available options. Choosing one option gives another popup menu with more options. In this
way, every option leads the users to the data entry form where the user can key in the data.

ERROR MESSAGE DESIGN


The design of error messages is an important part of the user interface design. As user is
bound to commit some errors or other while designing a system the system should be
designed to be helpful by providing the user with information regarding the error he/she has
committed.

This application must be able to produce output at different modules for different inputs.

PERFORMANCE REQUIREMENTS

Performance is measured in terms of the output provided by the application. Requirement


specification plays an important part in the analysis of a system. Only when the requirement
specifications are properly given, it is possible to design a system, which will fit into required
environment. It rests largely in the part of the users of the existing system to give the
requirement specifications because they are the people who finally use the system. This is
because the requirements have to be known during the initial stages so that the system can be
designed according to those requirements. It is very difficult to change the system once it has
been designed and on the other hand designing a system, which does not cater to the
requirements of the user, is of no use.

The requirement specification for any system can be broadly stated as given below:

 The system should be able to interface with the existing system


 The system should be accurate
 The system should be better than the existing system
 The existing system is completely dependent on the user to perform all the duties.
CHAPTER 9

SOURCE CODE
import numpy as np

import pandas as pd

import warnings

warnings.filterwarnings('ignore')

#DATA READING

import json

with open('intents.json', 'r') as f:

data = json.load(f)

df = pd.DataFrame(data['intents'])

df

dic = {"tag":[], "patterns":[], "responses":[]}

for i in range(len(df)):

ptrns = df[df.index == i]['patterns'].values[0]


rspns = df[df.index == i]['responses'].values[0]

tag = df[df.index == i]['tag'].values[0]

for j in range(len(ptrns)):

dic['tag'].append(tag)

dic['patterns'].append(ptrns[j])

dic['responses'].append(rspns)

df = pd.DataFrame.from_dict(dic)

df

df['tag'].unique()

# DATA PREPROCESSING

from tensorflow.keras.preprocessing.text import Tokenizer

tokenizer = Tokenizer(lower=True, split=' ')

tokenizer.fit_on_texts(df['patterns'])

tokenizer.get_config()

vacab_size = len(tokenizer.word_index)

print('number of unique words = ', vacab_size)

from tensorflow.keras.preprocessing.sequence import pad_sequences

from sklearn.preprocessing import LabelEncoder

ptrn2seq = tokenizer.texts_to_sequences(df['patterns'])

X = pad_sequences(ptrn2seq, padding='post')

print('X shape = ', X.shape)

lbl_enc = LabelEncoder()

y = lbl_enc.fit_transform(df['tag'])

print('y shape = ', y.shape)


print('num of classes = ', len(np.unique(y)))

# RANDOM FOREST CLASSIFIER

rn.model_selection import train_test_split

from sklearn.ensemble import RandomForestClassifier

from sklearn.metrics import accuracy_score

X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 2: Initialize the Random Forest Classifier

rfc = RandomForestClassifier(n_estimators=100, random_state=42)

# Step 3: Train the model

rfc.fit(X_train, Y_train)

# Step 4: Make predictions

Y_pred = rfc.predict(X_test)

# Step 5: Evaluate performance

accuracy = accuracy_score(Y_test, Y_pred)

print(f'Existing RFC Accuracy: {accuracy:.2f}') #ACCURACY 26

#BUILD AND TRAIN MODEL

import tensorflow

from tensorflow import keras

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import Input, Embedding, LSTM, LayerNormalization, Dense,


Dropout
from tensorflow.keras.utils import plot_model

model = Sequential()

model.add(Input(shape=(X.shape[1])))

model.add(Embedding(input_dim=vacab_size+1, output_dim=100, mask_zero=True))

model.add(LSTM(32, return_sequences=True))

model.add(LayerNormalization())

model.add(LSTM(32, return_sequences=True))

model.add(LayerNormalization())

model.add(LSTM(32))

model.add(LayerNormalization())

model.add(Dense(128, activation="relu"))

model.add(LayerNormalization())

model.add(Dropout(0.2))

model.add(Dense(128, activation="relu"))

model.add(LayerNormalization())

model.add(Dropout(0.2))

model.add(Dense(len(np.unique(y)), activation="softmax"))

model.compile(optimizer='adam', loss="sparse_categorical_crossentropy",
metrics=['accuracy'])

model.summary()

plot_model(model, show_shapes=True)

model_history = model.fit(x=X,y=y, batch_size=10,


callbacks=[tensorflow.keras.callbacks.EarlyStopping(monitor='accuracy', patience=3)],
epochs=50) #ACCURACY 98

#MODEL TESTING
import re

import random

def generate_answer(pattern):

text = []

txt = re.sub('[^a-zA-Z\']', ' ', pattern)

txt = txt.lower()

txt = txt.split()

txt = " ".join(txt)

text.append(txt)

x_test = tokenizer.texts_to_sequences(text)

x_test = np.array(x_test).squeeze()

x_test = pad_sequences([x_test], padding='post', maxlen=X.shape[1])

y_pred = model.predict(x_test)

y_pred = y_pred.argmax()

tag = lbl_enc.inverse_transform([y_pred])[0]

responses = df[df['tag'] == tag]['responses'].values[0]

print("you: {}".format(pattern))

print("model: {}".format(random.choice(responses)))

generate_answer('Hi! How are you?')

generate_answer('Maybe I just didn\'t want to be born :)')

generate_answer('help me:')

generate_answer(':')

def chatbot():

print("Chatbot: Hi! I'm your friendly chatbot. How can I assist you today?")
while True:

user_input = input("You: ")

if user_input.lower() in ['quit', 'exit', 'q', 'bye']:

print("Chatbot: Goodbye!")

break

generate_answer(user_input)

if __name__ == "__main__":

chatbot( )

CHAPTER 10

RESULTS AND DISCUSSION

10.1 Results

Model Performance

The dataset came from intents.json, which comprises a few types of intents, patterns, and
responses. So the model was fitted to 50 epochs with accuracy-based early stopping,
achieving a satisfactory accuracy of almost 99. The architecture of the model is basically an
embedding layer and three LSTM layers followed by dense layers, allowing the model to
learn the pattern of the user's inputs and make reasonable responses accordingly.

Data Preparation

Input data was tokenized and converted to sequences. The labels were encoded as integers,
hence a compact representation of all the different intents.

Response Generation

The chatbot successfully generates responses based on user inputs, utilizing the trained model
to predict the appropriate tag from the input patterns.
User Interaction

The chatbot engages users in conversation, displaying adaptability to different types of


inputs, including informal language and personalized content.

10.2 Discussion

The chatbot's effectiveness depends on the quality of the training data. A well-designed
dataset will lead to better understanding and responses.

Adding more diverse patterns and responses, handling unexpected inputs gracefully, and
tuning model parameters could enhance performance.

A simple interface allows for interactive conversations, making it accessible for users.

CHAPTER 11

CONCLUSION AND FUTURE SCOPE

11.1 Conclusion

This project compares two methods that can be used to make a chatbot: first, the Random
Forest Classifier and then an LSTM deep learning model. The type of data are user input
patterns, such as a question or statement, along with the corresponding bot response. After
preprocessing the data involved in tokenization and the padding of text, this first trains the
Random Forest model. This is weak, because it can only get 26% accuracy since it has no
knowledge of the sequence or word order of a sentence. The accuracy of the LSTM model
comes out to be 98%. It is so because it can remember a sequence of words and its meaning.
In this model, since it has been trained using the LSTM model, the ability of the chatbot can
process real-time user inputs and predict what the intent is, and, thereby, return with the right
answer. This reflects the capabilities of LSTM in handling more sequential data, like texts,
than Random Forests.
REFERENCES

[1] Mirko Casu, Sergio Triscari, Sebastiano Battiato, Luca Guarnera, and Pasquale
Caponnetto, “AI Chatbots for Mental Health: A Scoping Review of Effectiveness, Feasibility,
and Applications”, Applied Sciences, 14(13), 5889, (2024).

[2] Kirti Tomar, Anjali Khushwaha, Ankit Giri, and Sreenu Banoth, “AI-Enabled Chatbot for
Regulating Mental Health”, IJRASET Journal For Research in Applied Science and
Engineering Technology, volume 11, 2321-9653, (2023).

[3] Farhan Aslam, “The Impact of AI on Chatbot Technology”, European Journal of


Technology, 7(3):62-72, (2023).

[4] Luke Balcombe, “AI Chatbots in Digital Mental Health”, Informatics, 10(4), 82, (2023).

[5] Gerard Anmella, et al, “Vickybot, a Chatbot for Anxiety-Depressive Symptoms and
Work-Related Burnout in Primary Care and Health Care Professionals: Development,
Feasibility, and Potential Effectiveness Studies”, Journal of Medical Internet Research, vol
25:e43293, (2023).

[6] Gupta M, Malik T, and Sinha C, “Delivery of a Mental Health Intervention for Chronic
Pain Through an Artificial Intelligence-Enabled App (Wysa): Protocol for a Prospective Pilot
Study”, JMIR Forum Res, 11(3):e36910, (2022).
[7] Batyrkhan Omarov, Sergazi Narynov, and Zhandos Zhumanov, “Artificial Intelligence-
Enabled Chatbots in Mental Health”, Computers, Materials & Continua, 74(3), 5105-5122,
(2022).

[8] David B.Olawade, Ojima Z.Wada, Aderonke Odetaya, Aanuoluwapo Clement, and
Judith.E, “Enhancing Mental Health with Artificial Intelligence”, Journal of Medicine,
Surgery, and Public Health, volume 3, 100099, (2022).

[9] Ghazala Bilquise, Samar Ibrahim, and Khaled Shaalan, “Emotionally Intelligent Chatbots:
A Systematic Literature Review”, Human Behavior and Emerging Technologies, volume 22,
issue 1, 9601630, (2022).

[10] Adwitiya Ray, Akansha Bhardwaj, Yogender Kumar Malik, Shipra Singh, and Rajiv
Gupta, “Artificial intelligence and Psychiatry: An overview”, Asian Journal of Psychiatry,
volume 70, 103021, (2022).

[11] Prabod Rathnayaka, Nishan Mills, Donna Burnett, Daswin De Silva, Damminda
Alahakoon, and Richard Gray, “A Mental Health Chatbot with Cognitive Skills for
Personalised Behavioural Activation and Remote HealthMonitoring”, Sensors, 22(10), 3653,
(2022).

[12] K. Denecke, S. Vaaheesan, and A. Arulnathan, "A Mental Health Chatbot for Regulating
Emotions - Concept and Usability Test", IEEE Transactions on Emerging Topics in
Computing, vol. 9, no. 3, pp. 1170-1182, (2021).

[13] Denecke, Kerstin , Abd-Razak, Alaa, Househ, and Mowafa, “ Artificial Intelligence for
Chatbots in Mental Health: Opportunities and Challenges”, In book: Multiple Perspectives on
Artificial Intelligence in Healthcare pp.115-128, (2021).

[14] Sagar Badlani, Tanvi Aditya, Meet Dave, and Sheetal Chaudhari, “Multilingual
Healthcare Chatbot Using Machine Learning”, 2nd International Conference for
Emerging Technology (INCET) Belgaum, (2021).

[15] Eliane M. Boucher, Nicole R. Harake, Haley E. Ward, Sarah Elizabeth Stoeckl, Junielly
Vargas, Jared Minkel, Acacia C. Parks, and Ran Zilca, “Artificially intelligent chatbots in
digital mental health interventions: a review”, Expert Review of Medical Devices, 18:sup 1,
37-49, (2021).
[16] Athulya N, Jeeshna K, S J Aadithyan, U Sreelakshmi, and Hairunizha Alias Nisha
Rose, “Healthcare Chatbot”, IJCRT volume 9, Issue 10 ISSN: 2320-2882, (2021).

[17] Dosovitsky G, Pineda BS, Jacobson NC, Chang C, Escobedo M, and Bunge EL, “
Artificial Intelligence Chatbot for Depression: Descriptive Study of Usage”, JMIR Form
Res,4(11):e17065, (2020).

[18] Hiba Hussain, Komal Aswani, Mahima Gupta, and Dr. G.T.Thampi, “Implementation
of Disease Prediction Chatbot and Report Analyzer using the Concepts of NLP, Machine
Learning ”, International Research Journal of Engineering and
Technology(IRJET), volume: 07 issue: 04 e-ISSN: 2395-0056, (2020).

[19] Danielle Belgrave, Gavin Doherty, and Anja Thieme, “Machine learning in mental
health: a systematic review of the HCI literature to support the development of effective and
implementable ML systems”, vol. 27, No. 5, Article 34, (2020).

[20] Laranjo L, Dunn AG, Tong HL, Kocaballi AB, Chen J, Bashir R, Surian D, Gallego B,
Magrabi F, Lau AYS, and Coiera E, “ Conversational agents in healthcare: a systematic
review”, Journal of the American Medical Informatics Association, 25 (9):1248-1258,
(2018).

You might also like