0% found this document useful (0 votes)
32 views24 pages

Whats App

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

Whats App

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 24
OUTPUT ' A chatbot or chatterbot is a software application = to conduct an on-line chat conversation via text 0" ‘' to-speech, in lieu of providing direct contact with 4 live human agent.!7 Designed to convincingly simulate the way a human would behave as a conversational Partner, chatbot systems typically require continuous tuning and testing, and many in production remain unable to adequately converse, while none of them can Pass the standard Turing test.'°! The term "ChatterBot" was originally coined by Michael Mauldin (creator of the first Verbot) in 1994 to describe these conversational programs.|4] Tabloare L Chatbots are used in dialog systems for various purposes including customer service, request routing, or information gathering. While some chatbot applications use extensive word-classification processes, natural-language processors, and sophisticated Al, others simply scan for genera keywords and generate responses using com phrases obtained from an associated library database. Most chatbots are accessed on-line via popups or through virtual assistants. The classified into usage categories that commerce (e-commerce via c entertainment, finance, [5] ~« Development proposes $45 % Among the most notable early chatbots are ELIZA (1966) and PARRY (1972).(9!/101(102) More recent notable programs include A.L.1.C.E., Jabberwacky and D.U.D.E (Agence Nationale de la Recherche and CNRS 2006). While ELIZA and PARRY were used exclusively to simulate typed conversation, many chatbots now include other functional features, such as games and web searching abilities. In 1984, a book called The Policeman's Beard is Half Constructed was published, allegedly written by the chatbot Racter (though the program as released would not have been capable of doing so).!"*I One pertinent field of Al research is natural-language processing. Usually, weak Al fields employ specialized software or programming languages created — specifically for the narrow function AIML,!2! which is specific conversational agent, an lessaging apps Many companies' chatbots run on messaging apps or simply via SMS. They are used for B2C customer service, sales and marketing.!"°! In 2016, Facebook Messenger allowed developers to place chatbots on their platform. There were 30,000 bots created for Messenger in the first six months, rising to 100,000 by September 2017.'""! Since September 2017, this has also been as part ofa pilot program on WhatsApp. Airlines KLM and Aeroméxico both announced their participation in the testing;!20![21!l22)I25] both airlines had previously launched customer services on the Facebook Messenger platform. The bots usually appear as one of the user's contacts, but can sometimes act as participants in a group chat. Many banks, insurers, media companies, e-commerce companies, airlines, hotel chains, retailers, health care providers, government entities and restaurant chains have used chatbots to answer simple questions, increase customer engagement,!**! for promotion, and to offer additional ways to order from them, |2°!!25) bout the Python Project — PChatbot ,.. In this Python project with source code, we are going to build a chatbot using deep learning techniques The chatbot will be trained on the dataset which contains categories (intents), pattern and responses. We use a special recurrent neural network (LSTM) to classify which category the user’s message belongs to and then we will give a random response from the list of responses. Let’s create a retrieval based chatbot using NLTK, Keras, Python, etc. Download Chatbot Code & Dataset The dataset we will be using is ‘intents.json’. This is a JSON file that contains the patterns we need to find and the responses we want to return to the user. Please download python chatbot code & dataset from th | following link: Python Chatbot Code & Dat Prerequisites The Project requires you to have good knowledge of Python, Keras>and - Along with them, we will use some helping modules which you can download using the python-pip command. pip install tensorflow, keras, Pickle, nltk first, let us see the file structure and the type of will be creating: @ ae ¢ Intents.json — The data file which has predefined patterns and responses. © train_chatbot.py — In this Python file, we wrote z script to build the model and train our chatbot. © Words.pkl — This is a pickle file in which we store the words Python object that contains a list of our vocabulary. ¢ Classes.pkl — The classes pickle file contains the list of categori e Chatbot_model.h5 — This is the trained model that contains information about the model and has weights of the neurons. ¢ Chatgui.py — This is the Python script in which wi implemented GUI for our chathot. Users ean easily irst, make a file name as train_chatbot.py. We import the necessary packages for our chatbot and initialize the variables we will use in our Python project The data file is in JSON format so we used the json package to parse the JSON file into Python. mport nltk import from nltk rdNetLemmatizer = WordNetLemmatizer import pickle import numpy as np from keras.models import Sequential k - layers import Dense, vation, Dropout from keras.optimizers import SGD import random words= classes = documents = [] ignore_words = [)25aaiaas data_file = open (‘intents.json" ) .read () intents = json.loads (data file) 2. Preprocess data When working with text data, we need to perform various preprocessing on the data before we make a machine learning or a deep learning model. Based on the requirements we need to apply various operations to preprocess the data thing you can do on Tokenizing is the most basic and firs text data. Tokenizing is the process of breaking the whole text into small parts like words. Here we iterate through the patterns and tokenize the sentence using nltk.word_tokenize() function and append rds list. We also create a list of classes each word in the w for our tags. for intent in intents for pattern in intent ("patter nltk.word_tokenize (pattern) words.extend (w) if intent['tag') not in classes: classes.append (intent [' taq')) ow we will lemmatize each word and remove duplicate s of words from the list. Lemmatizing is the proce: a word into its lemma form and then creating converting $s which we will use a pickle file to store the Python obje while predicting lemmatizer.lemmatize (w. lowe: words = ignore_words w in words if w not in sorted (list (set (words) ) words = i x classes = sorted (list (set (clas betty and ten print (len(documents), "documents" i print + "classes", class i rd ‘ i I "unique lemmatizec len (words), words) .pkl', ‘v +pkl pickle.dump (words, open ('word pickle.dump (classes, open ('cla ) We will create the training data in which we will Wide the input and the output. Our input will be the tern and output will be the cl ass our input pattern longs to. But the Sones doesn’t understand text so training = | 1 output_empty 0 len (classes) fee Ex , bag of | for doc in documents: # initi ‘ J of w bag | th ut pattern_words = doc{[0 Pattern words = lemmatizer, lemmatize (word. lower () ) for word in pattern words 4 | for w in words: J bag.append(1) if w in pattern words else bag. append (0) - Build the model We have our training data ready, now we will build a deep 3 layers. We use the K neural network that sequential API for this. After training the model for 200 epochs, we achieved 100% accuracy on our model, Let us save the model as ‘chatbot_model.h5’. model = Sequential 1 model.add (Dense (128, input_shape= ain_x[{0]),), activatio 1.add (Dropout (0.5 add (Dense (64, activation='relu' model .add (Dropout (0.5) ) model.add (Dense (len (train_y[0]), activation='softmax"')) iit sgd = SGD(1r=0.01, de nesterov=True) model.compile (loss='ca optimizer=sgd, metrics ay=le-6, moment al "accurac ’ f j 1 saving t mod: hist = model. fit (np.array(train_x), np.array(train_y), epochs=200, batch_s 1 fitting ics deat hist = model. fit (np.array train_x), np.array(train_y), epochs=200, batch « verbose=1 1 model.save(' model.h5', hist) 1g. print ("model created") redict the response (Graphical User face) Fro predict the senta, a Ne sentences and get a response from the user S Create a new file ‘c hatapp.py’ We will lo; i ad the trained model and then use a raphical a interface that will Predict the response from the bot. The model will only tell us the class it belongs to, so we will implement some functions which will identify the class and then retrieve us a random response from the list of responses, Again we import the necessary packages and load the ‘words.pkl’ and ‘classes.pkl’ pickle files which we have created when we trained our model: import nltk from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer () 4 import pickle import numpy as np from keras.models import load_model model = load_model('chatbot_model.h5! import json import random intents = json.loads (open('intents.json') ,read{ words = pickle. load (open ('words.pkl','rb')) Classes: = pickle.load(open('classes.pkl', 'rb')) dict the class, we will need to provide input in the le way as we did while training. So we will create some mctions that will perform text preprocessing and then predict the class. def clean_up_sentenc words = nltk.word_tokenize enc i sentence words = lemmatizer.lemmatize (word for word in sentence _words return sentence words def bow(se detail show sentence_words clean_up_sentence (sentence bag = [0] *len(words for s in sentence words for i,w in enumerate (words) : ifw bagli] = 1 if show details: print ("found in bag: $s" % w) return (np.array (bag) ) bag: gs" ¢ + &: a return (np.array (bag def predict _class(sentence, moc p = bow (sentence, words, show_details=False res. = model .predict (np.array([p])) [0 ERROR_THRESHOLD = 0.25 results = i,r| for i,r in enumerate (res) if r>ERROR_THRESHOLD probability results.sort (key=lambda x: x{1], reverse-True) return list = [] for r in results: return_list.append ( "intent": classes[r[0]], "probability str(r[1]))) return return_list S— def getResponse (ints, intents_json tag = ints[(0] ['intent 1 intent of_intents = on{'intents' in list_of intents: if(i['ta for tag random.choice break return result def chatbot_ response (text): ints = predict_class (text, model res = getResponse (ints, intents) return res Now we will develop a graphical user interface. Let’s use Tkinter library which is shipped with tons of useful ibraries for GUI. We will take the input message from th iser and then use the helper functions we have created t et the response from the bot and display it on the GUI. lere is the full source code for the GUI. import tkinter kin’ from def msg + (foreground="#4 a", 12 ChatLog. confi font= atbot_response (msg nsert (END, "Bo aie g (state=DISABLEL ChatLog. yview (END base = Tk base. title ("Hello" geometry ("4002 . resizable (width=FALSE, FALSE bd=0, bg="white Arial", ChatLog = Text (base, eight="8", width="50", font= ChatLog.config(state=DISABLED) #Bir x : Sctollbar = Sctol bar (base, Command=ChatLog.yview, cursor="heart" ChatLog['yscr Scrollbar. set illcommand'] = #Create Butt c 1m je SendButton = Button(base, font= 2rdana",12,'bold'), text="Send", width="12", height=5, bd=0, bg="#32de9" activebackground="#3c9d9b", fg="#£ffFEFI command= send ) #Create the box to enter mess EntryBox = Text (base, bd=0, height="5", bg= font="Ar #Enty scrollbar.place (x=376, y=6, height=38¢ ChatLog.place (x=6, y=6, height=386, width=370) EntryBox.place (x=128, y=401, height=¢ width=265) SendButton. place (x=6, y=401, height=¢ base.mainloop () “his is how our intents.json file looks like. e more info", "Not sure q underster 2", “What help you provider, "Haw ysl) | eaction list, Blood preamare txacking, We ug react dua rea Screenshots: Sg era rs eet rss SCs eer) Ce a ere Coe ee rab er ets eee ed I classes [ ‘adverse drug’, "blood pressure’, “blood pressure search”, 88 unique lemmatized wo "behavior", “blood", ‘by’, ern cree Poa Cesta ame cot st a later’, ‘list’, "load", ‘locate’ eo ee ‘provide’, ‘reaction’, ‘related’, com rere +, ‘suitable’, ‘support’, ‘task’, ‘thani | ‘transfer’, ‘up’, ‘want’, ‘what’, ‘whic Sere oe ad POPPE PICT Meese Ce 11a aaa edie ae ees rt ae x Pestana ated ee @s 211 Summary In this Python data science project, we understood about nted a deep learning version of a an customize chatbots and impleme: chatbot in Python which is accurate. You ¢ the data according to business requirements and train the Chatbots are used chatbot with great accuracy. are looking forward to everywhere and all businesses implementing bot in their workflow. I hope you will practice by customizing your own chatbot using Python and don't fo if you found the article useful, do share the rget to show us your work. And project with your friends and colleagues.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy