In the last tutorial we set up and trained a model for our chatbot. Now preproccesing our data and training the model took a little bit of time, time that we don’t want to wait each time we want to use the model. So the first step of this tutorial is going to be changing some aspects of our code to load our model and data if it has already been created. Keep in mind that after doing this if you want to make changes to the model you will have to delete the saved model files or rename them.
With these tweaks we will only retrain the model and recreate our data if we haven’t done so already.
Now its time to actually use the model! Ideally we want to generate a response to any sentence the user types in. To do this we need to remember that our model does not take string input, it takes a bag of words. We also need to realize that our model does not spit out sentences, it generates a list of probabilities for all of our classes. This makes the process to generate a response look like the following: – Get some input from the user – Convert it to a bag of words – Get a prediction from the model – Find the most probable class – Pick a response from that class
defbag_of_words(s,words):bag=[0for_inrange(len(words))]s_words=nltk.word_tokenize(s)s_words=[stemmer.stem(word.lower())forwordins_words]forseins_words:fori,winenumerate(words):ifw==se:bag[i]=1returnnumpy.array(bag)defchat():print("Start talking with the bot (type quit to stop)!")whileTrue:inp=input("You: ")ifinp.lower()=="quit":breakresults=model.predict([bag_of_words(inp,words)])results_index=numpy.argmax(results)tag=labels[results_index]fortgindata["intents"]:iftg['tag']==tag:responses=tg['responses']print(random.choice(responses))chat()
The bag_of_words function will transform our string input to a bag of words using our created words list. The chat function will handle getting a prediction from the model and grabbing an appropriate response from our JSON file of responses.
Now run the program and enjoy chatting with your bot!
In the next tutorial we will add some more finishing touches and talk about some tweaks we can make to the model.