python nltk lemmatizer_Python聊天机器人–使用NLTK和Keras构建第一个聊天机器人
什么是聊天機器人?
聊天機器人是一款智能軟件,能夠傳達和執行類似于人類的動作。聊天機器人可以直接與客戶互動,在社交網站上進行營銷以及即時向客戶發送消息等方面被廣泛使用。根據聊天機器人的構建方式,它有兩種基本類型:基于檢索和基于生成的模型。
1.基于檢索的聊天機器人
基于檢索的聊天機器人使用預定義的輸入模式和響應。然后,使用某種啟發式方法來選擇適當的響應。它在行業中廣泛應用于制造目標導向的聊天機器人,我們可以在其中自定義聊天機器人的方式和流程,以帶給我們客戶的最佳體驗。
2.基于生成的聊天機器人
生成模型不是基于某些預定義的響應。它是基于seq2seq神經網絡。它與機器翻譯的想法相同。在機器翻譯中,我們將源代碼從一種語言翻譯為另一種語言,但是在這里,我們將把輸入轉換為輸出。它需要大量數據,并且基于深度神經網絡。
在這個項目中,我們將使用深度學習技術構建一個聊天機器人。聊天機器人將在包含類別(意圖),模式和響應的數據集上進行訓練。我們使用特殊的循環神經網絡(LSTM)對用戶消息所屬的類別進行分類,然后從響應列表中給出隨機響應。
數據集
我們將使用的數據集是“ intents.json”。這是一個JSON文件,其中包含我們需要查找的模式以及我們想要返回給用戶的響應。
如何制作聊天機器人
我們將使用Python構建聊天機器人,但首先,讓我們看一下將要創建的文件結構和文件類型:
Intents.json –具有預定義模式和響應的數據文件。train_chatbot.py –在此Python文件中,我們編寫了一個腳本來構建模型并訓練我們的聊天機器人。Words.pkl –這是一個pickle文件,我們將包含詞匯表列表的單詞Python對象存儲在其中。Classes.pkl –這也是一個pickle文件,這里是包含類別列表。Chatbot_model.h5 –這是經過訓練的模型,其中包含有關模型的信息并具有神經元的權重。Chatgui.py –這是我們為聊天機器人實現GUI的Python腳本。用戶可以輕松地與機器人互動。創建聊天機器人的5個步驟:
導入并加載數據文件預處理數據創建訓練和測試數據建立模型預測響應1、導入必要的庫并加載數據文件
首先,將文件名命名為train_chatbot.py。我們為聊天機器人導入必要的庫,并初始化將在Python項目中使用的變量。
數據文件為JSON格式,因此我們使用json庫將JSON文件解析為Python。
import nltkfrom nltk.stem import WordNetLemmatizerlemmatizer = WordNetLemmatizer()import jsonimport pickleimport numpy as npfrom keras.models import Sequentialfrom keras.layers import Dense, Activation, Dropoutfrom keras.optimizers import SGDimport randomwords=[]classes = []documents = []ignore_words = ['?', '!']data_file = open('intents.json').read()intents = json.loads(data_file)2、預處理數據
處理文本數據時,我們需要先對數據進行各種預處理,然后再進行機器學習或深度學習模型。標記化是您可以對文本數據進行的最基本的第一件事。標記化是將整個文本分成單詞之類的小部分的過程。
在這里,我們遍歷模式并使用nltk.word_tokenize()函數對句子進行標記化,然后將每個單詞附加在單詞列表中。我們還為標簽創建了一個類列表。
for intent in intents['intents']: for pattern in intent['patterns']: #tokenize each word w = nltk.word_tokenize(pattern) words.extend(w) #add documents in the corpus documents.append((w, intent['tag'])) # add to our classes list if intent['tag'] not in classes: classes.append(intent['tag'])現在,我們將對每個單詞進行詞法去除,并從列表中刪除重復的單詞。Lemmatizing是將單詞轉換成引理形式,然后創建一個pickle文件來存儲我們將在預測時使用的Python對象的過程。
# lemmatize, lower each word and remove duplicateswords = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_words]words = sorted(list(set(words)))# sort classesclasses = sorted(list(set(classes)))# documents = combination between patterns and intentsprint (len(documents), "documents")# classes = intentsprint (len(classes), "classes", classes)# words = all words, vocabularyprint (len(words), "unique lemmatized words", words)pickle.dump(words,open('words.pkl','wb'))pickle.dump(classes,open('classes.pkl','wb'))3、創建訓練和測試數據
現在,我們將創建訓練數據,在其中將提供輸入和輸出。我們的輸入將是模式,輸出將是我們的輸入模式所屬的類。但是計算機不理解文本,因此我們會將文本轉換為數字。
# create our training datatraining = []# create an empty array for our outputoutput_empty = [0] * len(classes)# training set, bag of words for each sentencefor doc in documents: # initialize our 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 words pattern_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")4、構建模型
我們已經準備好訓練數據,現在我們將構建一個具有3層的深度神經網絡。在訓練模型200個周期后,我們在模型上達到了100%的準確性。讓我們將模型另存為“ chatbot_model.h5”。
# Create 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 model hist = 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")5、預測響應
現在來預測句子并從用戶那里得到答復,讓我們創建一個新文件“ chatapp.py”。
我們將加載經過訓練的模型,然后使用圖形用戶界面來預測機器人的響應。該模型只會告訴我們它所屬的類,因此我們將實現一些函數,這些函數將識別該類,然后從響應列表中檢索一個隨機響應。
我們導入必要的庫并加載在訓練模型時創建的picks文件“ words.pkl”和“ classes.pkl”:
import nltkfrom nltk.stem import WordNetLemmatizerlemmatizer = WordNetLemmatizer()import pickleimport numpy as npfrom keras.models import load_modelmodel = load_model('chatbot_model.h5')import jsonimport randomintents = 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): # tokenize the pattern - split words into array sentence_words = nltk.word_tokenize(sentence) # stem each word - create short form for word sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words] return sentence_words# return bag of words array: 0 or 1 for each word in the bag that exists in the sentencedef bow(sentence, words, show_details=True): # tokenize the pattern sentence_words = clean_up_sentence(sentence) # bag of words - matrix of N words, vocabulary matrix bag = [0]*len(words) for s in sentence_words: for i,w in enumerate(words): if w == s: # assign 1 if current word is in the vocabulary position bag[i] = 1 if show_details: print ("found in bag: %s" % w) return(np.array(bag))def predict_class(sentence, model): # filter out predictions below a threshold 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] # sort by strength of 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預測完類后,我們將從意圖列表中獲得隨機響應
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']) break return resultdef chatbot_response(text): ints = predict_class(text, model) res = getResponse(ints, intents) return res現在,我們將對圖形用戶界面進行編碼。為此,我們使用python中已經提供的Tkinter庫。我們將接收來自用戶的輸入消息,然后使用我們創建的機器人來響應并將其顯示在GUI上。這是GUI的完整源代碼。
#Creating GUI with tkinterimport tkinterfrom tkinter import *def send(): msg = EntryBox.get("1.0",'end-1c').strip() EntryBox.delete("0.0",END)if msg != '': ChatLog.config(state=NORMAL) ChatLog.insert(END, "You: " + msg + '') ChatLog.config(foreground="#442265", font=("Verdana", 12 )) res = chatbot_response(msg) ChatLog.insert(END, "Bot: " + res + '') ChatLog.config(state=DISABLED) ChatLog.yview(END)base = Tk()base.title("Hello")base.geometry("400x500")base.resizable(width=FALSE, height=FALSE)#Create Chat windowChatLog = Text(base, bd=0, bg="white", , , font="Arial",)ChatLog.config(state=DISABLED)#Bind scrollbar to Chat windowscrollbar = Scrollbar(base, command=ChatLog.yview, cursor="heart")ChatLog['yscrollcommand'] = scrollbar.set#Create Button to send messageSendButton = Button(base, font=("Verdana",12,'bold'), text="Send", , height=5, bd=0, bg="#32de97", activebackground="#3c9d9b",fg='#ffffff', command= send )#Create the box to enter messageEntryBox = Text(base, bd=0, bg="white",, , font="Arial")#EntryBox.bind("", send)#Place all components on the screenscrollbar.place(x=376,y=6, height=386)ChatLog.place(x=6,y=6, height=386, width=370)EntryBox.place(x=128, y=401, height=90, width=265)SendButton.place(x=6, y=401, height=90)base.mainloop()6、運行聊天機器人
要運行chatbot,我們有兩個主要文件:train_chatbot.py和chatapp.py。
首先,我們使用終端中的命令訓練模型:
python train_chatbot.py如果我們在訓練過程中沒有看到任何錯誤,則說明我們已經成功創建了模型。
然后運行該應用程序,我們運行第二個文件。
python chatgui.py該程序將在幾秒鐘內打開一個GUI窗口。使用GUI,您可以輕松地與機器人聊天。
在這個簡單項目中,我們了解了聊天機器人,并在Python中實現了聊天機器人的深度學習版本。您可以根據業務需求自定義數據,并以很高的準確性訓練聊天機器人。聊天機器人無處不在,所有企業都希望在其工作流程中實施機器人。
總結
以上是生活随笔為你收集整理的python nltk lemmatizer_Python聊天机器人–使用NLTK和Keras构建第一个聊天机器人的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: idea springmvc_IDEA搭
- 下一篇: python中str用法_python中