Echo Dot (3rd Gen) - Smart speaker with Alexa - Charcoal

Use your voice to play a song, artist, or genre through Amazon Music, Apple Music, Spotify, Pandora, and others. With compatible Echo devices in different rooms, you can fill your whole home with music.

Buy Now

Wireless Rechargeable Battery Powered WiFi Camera.

Wireless Rechargeable Battery Powered WiFi Camera is home security camera system lets you listen in and talk back through the built in speaker and microphone that work directly through your iPhone or Android Mic.

Buy Now

Know How to Develop it Using Python Programming Language

0
72


Manoj Rupareliya
Source

Chatbots have gained huge popularity in the market these days. This advanced technology has proven to be extremely helpful for businesses as well as customers. The majority of nowadays prefer to have interaction with a chatbot instead of interacting with the customer service provider staff.

Facebook recently released data that have justified how helpful a chatbot is to mankind, in the data it was found that more than 2 billion messages are sent between businesses and their prospective customers on a monthly basis.

One of the HubSpot shows that more than 71% of people want to get customer support through messaging apps. They also said that it is one of the quick and effective ways to get answers for their issues, hence it’s not wrong to say that chatbots have a bright future. And businesses who opt for it can make their business future proof, even many of the businesses have even stepped ahead for developing advanced chatbot solutions for their business.

A chatbot can be termed as one of the intelligent pieces of software which possesses the capabilities of performing and communicating actions just similar to humans. Nowadays, most of them use this piece of software for various purposes, they use it for customer interaction as well as for marketing on social network sites. This advanced software can help them to offer instant answers to their customer’s questions in less time than before ever. Mainly there are two types of chatbots which businesses can consider developing, this type include:

  • Retrieval based model.
  • Generative based model.

This type of chatbots uses predefined input responses and patterns to answer to any of the prospective customers. It uses a heuristic approach to find an appropriate response for the customer’s query in less time. Most of the organizations opt to develop such kind of goal-oriented chatbots to customize the flow and tone to drive customers a great experience.

Generative based chatbots are not defined on any kind of predefined responses. It is simply based on seq to seq neural networks. It is just similar to machine translation, where any of the individuals can translate the source code into different languages as per their needs. In a similar way, this type of chatbots transforms an input into an output, it simply requires a huge amount of data and is based on Deep Neural networks.

In one of the Oracle surveys, more than 80% of businesses responded that they would like to use and plan to integrate chatbots within their working environment by 2020. Nowadays, most of the customers expect that brands must respond to them within the blink of an eye. And business owners who fail to do so will definitely be left behind in today’s competitive market. Hence it becomes vital for businesses to opt for advanced chatbot development.

There are various ways of developing an advanced chatbot solution, any of the individuals can develop a chatbot using deep learning techniques, they can even make use of Python for crafting chatbot. The type of chatbot will be trained on the dataset that contains categories (intents), responses, patterns, and much more. Explore to know how you can develop your first chatbot using Python as the programming language.

When it comes to implementing the chatbot, then we can use Keras, which is one of the other deep learning libraries. We can also make use of NLTK, it is a Natural Language Processing toolkit, there is the availability of many other libraries that we can use for crafting advanced chatbot very quickly than ever before. If you want to make sure whether all the libraries are installed perfectly or not, then run the below command.

There are mainly 5 steps which any of the individuals have to follow when it comes to developing chatbot with the help of Python as the programming language.

  • Import & load the data file.
  • Preprocess data.
  • Create training & testing data.
  • Build the model.
  • Predict the response.

First of all, give the name make to the file which you are developing, you can give any of the names as per your choice. Here we have given train_chatbot.py name to the file. Now let’s import all the essential packages which we need to develop the chatbot, also let’s initialize all the variables which we need for crafting the Python project. The data format here is in JSON format, hence it becomes mandatory to use the JSON package to parse the JSON file into the chatbot project which you are developing using Python.

  • Code to Import and Load Data File:
import nltk
nltk.download(‘punkt’)
nltk.download(‘wordnet’)
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import json
import pickle
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.optimizers import SGD
import random
words=[]
classes = []
documents = []
ignore_words = [‘?’, ‘!’]
data_file = open(‘intents.json’).read()
intents = json.loads(data_file)

Code: (Source)

While working with text data, it becomes essential for us to perform different preprocess on the data. This process is very crucial, especially when it comes to developing deep learning or a machine learning model. Tokenizing is one of the basic and essential processes which broke the whole text into small parts just similar to the words.

Here is the small code which helps individuals to craft advance tokenize and pattern the sentence using nltk.word_tokenize() function. This also helps in appending each word on the list more efficiently and systematically. We have developed a list of classes for a few of the tags, explore the code to know which are those.

for intent in intents[‘intents’]:
for pattern in intent[‘patterns’]:
# take each word and tokenize it
w = nltk.word_tokenize(pattern)
words.extend(w)
# adding documents
documents.append((w, intent[‘tag’]))
# adding classes to our class list
if intent[‘tag’] not in classes:
classes.append(intent[‘tag’])

Code: (Source)

Now let’s see how we can lemmatize each word from the list, also let’s explore to know how we can avoid duplicate words from the project which we are planning to craft. Lemmatizing is a simple process that is used for transforming words into a lemma form, it can later be used for storing a Python object that can later be used for the prediction purpose.

words = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_words]

words = sorted(list(set(words)))

classes = sorted(list(set(classes)))

print (len(documents), “documents”)

print (len(classes), “classes”, classes)

print (len(words), “unique lemmatized words”, words)

pickle.dump(words,open(‘words.pkl’,’wb’))

pickle.dump(classes,open(‘classes.pkl’,’wb’))

Code: (Source)

Developing Training and Testing Data

Now let’s create the testing and training data that we can use for providing input and output. A pattern can be considered as input, while the output can be considered as a class through which the pattern belongs to. But as we all know, the computer does not pose the capabilities to understand the text, so it converts into the number to generate the needed output.

# initializing training data
training = []
output_empty = [0] * len(classes)
for doc in documents:# initializing bag of words
bag = []
# list of tokenized words for the pattern
pattern_words = doc[0]
# lemmatize each word — create base word, in attempt to represent related wordspattern_words = [lemmatizer.lemmatize(word.lower()) for word in pattern_words]# create our bag of words array with 1, if word match found in current patternfor w in words:
bag.append(1) if w in pattern_words else bag.append(0)
# output is a ‘0’ for each tag and ‘1’ for current tag (for each pattern)output_row = list(output_empty)
output_row[classes.index(doc[1])] = 1
training.append([bag, output_row])
# shuffle our features and turn into np.arrayrandom.shuffle(training)
training = np.array(training)
# create train and test lists. X — patterns, Y — intentstrain_x = list(training[:,0])
train_y = list(training[:,1])
print(“Training data created”)

Code: (Source)

Now the training data is almost ready to use, now it is the time to craft a deep neural network that consists of more than three layers. We have used Keras sequential API for crafting this model, once after crafting it for 200 epochs, we can easily achieve 100% accuracy with the model which we are thinking of crafting. We have named this model as ‘chatbot_model.h5’ you can give the name as per your choice and convenience.

# Create a model — 3 layers. First layer 128 neurons, second layer 64 neurons and 3rd output layer contains number of neurons# equal to number of intents to predict output intent with softmaxmodel = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation=’relu’))
model.add(Dropout(0.5))
model.add(Dense(64, activation=’relu’))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation=’softmax’))
# Compile model. Stochastic gradient descent with Nesterov accelerated gradient gives good results for this modelsgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss=’categorical_crossentropy’, optimizer=sgd, metrics=[‘accuracy’])
#fitting and saving the modelhist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save(‘chatbot_model.h5’, hist)
print(“model created”)

Code: (Source)

Now the whole model is ready for the use of the users. It helps you create a perfect graphical user interface for the chatbot file. If you are not good at coding, then you can take the support of the angularjs development company, which can help you in creating the same chatbot file very easily and quickly than ever before. Name this file as gui_chatbot.py

Make sure that you use the Tkinter module in the GUI file, this might help you to create an advanced structure for your desktop application. This will allow you to capture the user message and perform the needed preprocess before putting the model into the trained model. The model will help them to predict the user’s message tag, it will select the response randomly and will provide the response to users after exploring their input perfectly.

import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
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’))
def clean_up_sentence(sentence):
sentence_words = nltk.word_tokenize(sentence)
sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
return sentence_words
def bag_of_words(sentence, words, show_details=True):
sentence_words = clean_up_sentence(sentence)
# bag of words — vocabulary matrixbag = [0]*len(words)
for s in sentence_words:
for i,word in enumerate(words):
if word == s:
# assign 1 if current word is in the vocabulary positionbag[i] = 1
if show_details:
print (“found in bag: %s” % word)
return(np.array(bag))
# filter below threshold predictionsp = bag_of_words(sentence, words,show_details=False)
res = model.predict(np.array([p]))[0]
results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
# sorting strength probabilityreturn_list = []
for r in results:
return_list.append({“intent”: classes[r[0]], “probability”: str(r[1])})
return return_list
def getResponse(ints, intents_json):
tag = ints[0][‘intent’]
list_of_intents = intents_json[‘intents’]
for i in list_of_intents:
if(i[‘tag’]== tag):
result = random.choice(i[‘responses’])
return result
#Creating tkinter GUIimport tkinter
def send():
msg = EntryBox.get(“1.0”,’end-1c’).strip()
EntryBox.delete(“0.0”,END)
if msg != ‘’:
ChatBox.config(state=NORMAL)
ChatBox.insert(END, “You: “ + msg + ‘nn’)
ChatBox.config(foreground=”#446665", font=(“Verdana”, 12 ))
ints = predict_class(msg)
res = getResponse(ints, intents)
ChatBox.insert(END, “Bot: “ + res + ‘nn’)
ChatBox.config(state=DISABLED)
ChatBox.yview(END)
root.title(“Chatbot”)
root.geometry(“400x500”)
root.resizable(width=FALSE, height=FALSE)
#Create Chat windowChatBox = Text(root, bd=0, bg=”white”, height=”8", width=”50", font=”Arial”,)
ChatBox.config(state=DISABLED)
#Bind scrollbar to Chat windowscrollbar = Scrollbar(root, command=ChatBox.yview, cursor=”heart”)
ChatBox[‘yscrollcommand’] = scrollbar.set
#Create Button to send messageSendButton = Button(root, font=(“Verdana”,12,’bold’), text=”Send”, width=”12", height=5,
bd=0, bg=”#f9a602", activebackground=”#3c9d9b”,fg=’#000000',
command= send )
#Create the box to enter messageEntryBox = Text(root, bd=0, bg=”white”,width=”29", height=”5", font=”Arial”)#EntryBox.bind(“<Return>”, send)scrollbar.place(x=376,y=6, height=386)
ChatBox.place(x=6,y=6, height=386, width=370)
EntryBox.place(x=128, y=401, height=90, width=265)
root.mainloop()

Code: (Source)

We have two name files, which we have named as chatapp.py and train_chatbot.py, which we can use to run the chatbot, which we have coded. First of all, train the model with the help of the command within the terminal window.

If you don’t find any error in the model, then consider that you have developed the model successfully. This assures that you have crafted the ranking model very successfully, now run the second file to find its error-free. Once both the files run without any error, you can consider that you have the chatbot efficiently without any error. Leverage the benefits of it by integrating it with the platform you want.

In today’s competitive world, it becomes vital for businesses to opt for an advanced solution. This can help them to provide their prospective customers with the best ever experience which they demand to have from any of the brands. Understand the importance of chatbot and step ahead for integrating it for your business.

You can consider developing a deep learning version of a chatbot with the help of Python as it is one of the best options which you can choose for developing an advanced solution for your business. This solution also allows you to customize the data as per the requirements of your business and can train it with great accuracy. This advanced solution is developed and used everywhere these days, they are looking ahead to implementing this advanced solution in their workflow.



Read More

LEAVE A REPLY

Please enter your comment!
Please enter your name here