聊天機器人是一種計算機程序,它了解您的查詢意圖以使用解決方案進行回答。聊天機器人是業(yè)內(nèi)最受歡迎的自然語言處理應用。因此,如果您想構建端到端聊天機器人,本文適合您。在本文中,我將帶您了解如何使用 Python 創(chuàng)建端到端聊天機器人。
1. 效果圖
訓練的意圖及回復越多,機器人將越靈活準確。
用例少不準確或者基本是提供的內(nèi)容的回答。
2. 原理
2.1 什么是端到端聊天機器人?
端到端聊天機器人是指可以在不需要人工幫助的情況下從頭到尾處理完整對話的聊天機器人。
要創(chuàng)建端到端聊天機器人,需要編寫一個計算機程序,該程序可以理解用戶請求,生成適當?shù)捻憫?,并在必要時采取行動。這包括收集數(shù)據(jù),選擇編程語言和NLP工具,訓練聊天機器人,以及在將其提供給用戶之前對其進行測試和完善。 部署后,用戶可以通過向聊天機器人發(fā)送多個請求來與聊天機器人進行交互,聊天機器人可以自行處理整個對話。
2.2 創(chuàng)建端到端聊天機器人步驟
- 定義意向
- 創(chuàng)建訓練數(shù)據(jù)
- 訓練聊天機器人
- 構建聊天機器人
- 測試聊天機器人
- 部署聊天機器人
3. 源碼
3.1 streamlit安裝
python3.7.6+ streamlit 0.68.0,1.20.0,1.21.0 都不行,只有1.9版本ok文章來源:http://www.zghlxwxcb.cn/news/detail-429862.html
pip install streamlit==1.9
文章來源地址http://www.zghlxwxcb.cn/news/detail-429862.html
3.2 源碼
# 端到端聊天機器人
# streamlit run ete_chatbot.py
import os
import nltk
import ssl
import streamlit as st
import random
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
ssl._create_default_https_context = ssl._create_unverified_context
nltk.data.path.append(os.path.abspath("nltk_data"))
nltk.download('punkt')
# 定義聊天機器人的一些意圖。可以添加更多意圖,使聊天機器人更有用且功能更強大
intents = [
{
"tag": "greeting",
"patterns": ["Hi", "Hello", "Hey", "How are you", "What's up"],
"responses": ["Hi there", "Hello", "Hey", "I'm fine, thank you", "Nothing much"]
},
{
"tag": "goodbye",
"patterns": ["Bye", "See you later", "Goodbye", "Take care"],
"responses": ["Goodbye", "See you later", "Take care"]
},
{
"tag": "thanks",
"patterns": ["Thank you", "Thanks", "Thanks a lot", "I appreciate it"],
"responses": ["You're welcome", "No problem", "Glad I could help"]
},
{
"tag": "about",
"patterns": ["What can you do", "Who are you", "What are you", "What is your purpose"],
"responses": ["I am a chatbot", "My purpose is to assist you", "I can answer questions and provide assistance"]
},
{
"tag": "help",
"patterns": ["Help", "I need help", "Can you help me", "What should I do"],
"responses": ["Sure, what do you need help with?", "I'm here to help. What's the problem?", "How can I assist you?"]
},
{
"tag": "age",
"patterns": ["How old are you", "What's your age"],
"responses": ["I don't have an age. I'm a chatbot.", "I was just born in the digital world.", "Age is just a number for me."]
},
{
"tag": "weather",
"patterns": ["What's the weather like", "How's the weather today"],
"responses": ["I'm sorry, I cannot provide real-time weather information.", "You can check the weather on a weather app or website."]
},
{
"tag": "budget",
"patterns": ["How can I make a budget", "What's a good budgeting strategy", "How do I create a budget"],
"responses": ["To make a budget, start by tracking your income and expenses. Then, allocate your income towards essential expenses like rent, food, and bills. Next, allocate some of your income towards savings and debt repayment. Finally, allocate the remainder of your income towards discretionary expenses like entertainment and hobbies.", "A good budgeting strategy is to use the 50/30/20 rule. This means allocating 50% of your income towards essential expenses, 30% towards discretionary expenses, and 20% towards savings and debt repayment.", "To create a budget, start by setting financial goals for yourself. Then, track your income and expenses for a few months to get a sense of where your money is going. Next, create a budget by allocating your income towards essential expenses, savings and debt repayment, and discretionary expenses."]
},
{
"tag": "credit_score",
"patterns": ["What is a credit score", "How do I check my credit score", "How can I improve my credit score"],
"responses": ["A credit score is a number that represents your creditworthiness. It is based on your credit history and is used by lenders to determine whether or not to lend you money. The higher your credit score, the more likely you are to be approved for credit.", "You can check your credit score for free on several websites such as Credit Karma and Credit Sesame."]
}
]
# Create the vectorizer and classifier 創(chuàng)建矢量化器和分類器
vectorizer = TfidfVectorizer()
clf = LogisticRegression(random_state=0, max_iter=10000)
# 準備意圖數(shù)據(jù)并訓練模型
tags = []
patterns = []
for intent in intents:
for pattern in intent['patterns']:
tags.append(intent['tag'])
patterns.append(pattern)
# 訓練模型
x = vectorizer.fit_transform(patterns)
y = tags
clf.fit(x, y)
def chatbot(input_text):
input_text = vectorizer.transform([input_text])
tag = clf.predict(input_text)[0]
for intent in intents:
if intent['tag'] == tag:
response = random.choice(intent['responses'])
return response
# 為了部署聊天機器人,將使用 Python 中的 streamlit 庫,它提供了驚人的功能,只需幾行代碼即可為機器學習應用程序創(chuàng)建用戶界面
counter = 0
def main():
global counter
st.title("Chatbot")
st.write("Welcome to the chatbot. Please type a message and press Enter to start the conversation.")
counter += 1
user_input = st.text_input("You:", key=f"user_input_{counter}")
if user_input:
response = chatbot(user_input)
st.text_area("Chatbot:", value=response, height=100, max_chars=None, key=f"chatbot_response_{counter}")
if response.lower() in ['goodbye', 'bye']:
st.write("Thank you for chatting with me. Have a great day!")
st.stop()
if __name__ == '__main__':
main()
參考
- https://thecleverprogrammer.com/2023/03/27/end-to-end-chatbot-using-python/
到了這里,關于使用 Python 創(chuàng)建端到端聊天機器人的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!