Chatbot with Machine Learning
Abstract
Chatbot with Machine Learning is a Python project that uses ML to build a chatbot. The application features intent recognition, response generation, and a CLI interface, demonstrating best practices in conversational AI and ML.
Prerequisites
- Python 3.8 or above
- A code editor or IDE
- Basic understanding of ML and chatbots
- Required libraries:
nltk
nltk
,scikit-learn
scikit-learn
,pandas
pandas
Before you Start
Install Python and the required libraries:
Install dependencies
pip install nltk scikit-learn pandas
Install dependencies
pip install nltk scikit-learn pandas
Getting Started
Create a Project
- Create a folder named
chatbot-with-machine-learning
chatbot-with-machine-learning
. - Open the folder in your code editor or IDE.
- Create a file named
chatbot_with_machine_learning.py
chatbot_with_machine_learning.py
. - Copy the code below into your file.
Write the Code
⚙️ Chatbot with Machine Learning
Chatbot with Machine Learning
"""
Chatbot with Machine Learning
A full chatbot implementation using scikit-learn and NLTK. Includes intent classification, response generation, training, and CLI for chat interaction.
"""
import pandas as pd
import numpy as np
import argparse
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import joblib
import nltk
nltk.download('punkt')
# Example intents dataset
intents = [
{'intent': 'greeting', 'patterns': ['hello', 'hi', 'hey'], 'responses': ['Hello!', 'Hi there!', 'Hey!']},
{'intent': 'goodbye', 'patterns': ['bye', 'goodbye', 'see you'], 'responses': ['Goodbye!', 'See you later!', 'Bye!']},
{'intent': 'thanks', 'patterns': ['thanks', 'thank you'], 'responses': ['You are welcome!', 'No problem!']},
]
def build_dataset(intents):
X, y = [], []
for intent in intents:
for pattern in intent['patterns']:
X.append(pattern)
y.append(intent['intent'])
return X, y
def train_model(X, y, model_path=None):
vectorizer = TfidfVectorizer()
X_vec = vectorizer.fit_transform(X)
clf = LogisticRegression()
clf.fit(X_vec, y)
if model_path:
joblib.dump((clf, vectorizer), model_path)
print(f"Model saved to {model_path}")
return clf, vectorizer
def get_response(intent):
for item in intents:
if item['intent'] == intent:
return np.random.choice(item['responses'])
return "I don't understand."
def chat(model, vectorizer):
print("Chatbot is ready! Type 'quit' to exit.")
while True:
user_input = input('You: ')
if user_input.lower() == 'quit':
break
X_vec = vectorizer.transform([user_input])
intent = model.predict(X_vec)[0]
print('Bot:', get_response(intent))
def main():
parser = argparse.ArgumentParser(description="Chatbot with Machine Learning")
parser.add_argument('--train', action='store_true', help='Train model')
parser.add_argument('--model', type=str, default='chatbot_model.pkl', help='Path to save/load model')
parser.add_argument('--chat', action='store_true', help='Start chat')
args = parser.parse_args()
if args.train:
X, y = build_dataset(intents)
train_model(X, y, args.model)
elif args.chat:
if not os.path.exists(args.model):
print(f"Model file {args.model} not found. Train the model first.")
return
clf, vectorizer = joblib.load(args.model)
chat(clf, vectorizer)
else:
parser.print_help()
if __name__ == "__main__":
main()
Chatbot with Machine Learning
"""
Chatbot with Machine Learning
A full chatbot implementation using scikit-learn and NLTK. Includes intent classification, response generation, training, and CLI for chat interaction.
"""
import pandas as pd
import numpy as np
import argparse
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import joblib
import nltk
nltk.download('punkt')
# Example intents dataset
intents = [
{'intent': 'greeting', 'patterns': ['hello', 'hi', 'hey'], 'responses': ['Hello!', 'Hi there!', 'Hey!']},
{'intent': 'goodbye', 'patterns': ['bye', 'goodbye', 'see you'], 'responses': ['Goodbye!', 'See you later!', 'Bye!']},
{'intent': 'thanks', 'patterns': ['thanks', 'thank you'], 'responses': ['You are welcome!', 'No problem!']},
]
def build_dataset(intents):
X, y = [], []
for intent in intents:
for pattern in intent['patterns']:
X.append(pattern)
y.append(intent['intent'])
return X, y
def train_model(X, y, model_path=None):
vectorizer = TfidfVectorizer()
X_vec = vectorizer.fit_transform(X)
clf = LogisticRegression()
clf.fit(X_vec, y)
if model_path:
joblib.dump((clf, vectorizer), model_path)
print(f"Model saved to {model_path}")
return clf, vectorizer
def get_response(intent):
for item in intents:
if item['intent'] == intent:
return np.random.choice(item['responses'])
return "I don't understand."
def chat(model, vectorizer):
print("Chatbot is ready! Type 'quit' to exit.")
while True:
user_input = input('You: ')
if user_input.lower() == 'quit':
break
X_vec = vectorizer.transform([user_input])
intent = model.predict(X_vec)[0]
print('Bot:', get_response(intent))
def main():
parser = argparse.ArgumentParser(description="Chatbot with Machine Learning")
parser.add_argument('--train', action='store_true', help='Train model')
parser.add_argument('--model', type=str, default='chatbot_model.pkl', help='Path to save/load model')
parser.add_argument('--chat', action='store_true', help='Start chat')
args = parser.parse_args()
if args.train:
X, y = build_dataset(intents)
train_model(X, y, args.model)
elif args.chat:
if not os.path.exists(args.model):
print(f"Model file {args.model} not found. Train the model first.")
return
clf, vectorizer = joblib.load(args.model)
chat(clf, vectorizer)
else:
parser.print_help()
if __name__ == "__main__":
main()
Example Usage
Run ML chatbot
python chatbot_with_machine_learning.py
Run ML chatbot
python chatbot_with_machine_learning.py
Explanation
Key Features
- Intent Recognition: Identifies user intent using ML.
- Response Generation: Generates responses based on intent.
- Error Handling: Validates inputs and manages exceptions.
- CLI Interface: Interactive command-line usage.
Code Breakdown
- Import Libraries and Setup Chatbot
chatbot_with_machine_learning.py
import nltk
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
chatbot_with_machine_learning.py
import nltk
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
- Intent Recognition and Response Generation Functions
chatbot_with_machine_learning.py
def train_chatbot(X, y):
vectorizer = CountVectorizer()
X_vec = vectorizer.fit_transform(X)
model = MultinomialNB()
model.fit(X_vec, y)
return model, vectorizer
def get_response(model, vectorizer, text):
X_vec = vectorizer.transform([text])
intent = model.predict(X_vec)[0]
responses = {'greeting': 'Hello! How can I help you?', 'unknown': 'Sorry, I did not understand.'}
return responses.get(intent, 'Sorry, I did not understand.')
chatbot_with_machine_learning.py
def train_chatbot(X, y):
vectorizer = CountVectorizer()
X_vec = vectorizer.fit_transform(X)
model = MultinomialNB()
model.fit(X_vec, y)
return model, vectorizer
def get_response(model, vectorizer, text):
X_vec = vectorizer.transform([text])
intent = model.predict(X_vec)[0]
responses = {'greeting': 'Hello! How can I help you?', 'unknown': 'Sorry, I did not understand.'}
return responses.get(intent, 'Sorry, I did not understand.')
- CLI Interface and Error Handling
chatbot_with_machine_learning.py
def main():
print("Chatbot with Machine Learning")
# X = [...] # Training data
# y = [...] # Labels
# model, vectorizer = train_chatbot(X, y)
# text = input('You: ')
# print('Bot:', get_response(model, vectorizer, text))
print("[Demo] Chatbot logic here.")
if __name__ == "__main__":
main()
chatbot_with_machine_learning.py
def main():
print("Chatbot with Machine Learning")
# X = [...] # Training data
# y = [...] # Labels
# model, vectorizer = train_chatbot(X, y)
# text = input('You: ')
# print('Bot:', get_response(model, vectorizer, text))
print("[Demo] Chatbot logic here.")
if __name__ == "__main__":
main()
Features
- ML Chatbot: Intent recognition and response generation
- Modular Design: Separate functions for each task
- Error Handling: Manages invalid inputs and exceptions
- Production-Ready: Scalable and maintainable code
Next Steps
Enhance the project by:
- Integrating with real conversation datasets
- Supporting advanced ML models
- Creating a GUI for chatbot
- Adding context management
- Unit testing for reliability
Educational Value
This project teaches:
- Conversational AI: ML and chatbot design
- Software Design: Modular, maintainable code
- Error Handling: Writing robust Python code
Real-World Applications
- Customer Support Bots
- Virtual Assistants
- Educational Tools
Conclusion
Chatbot with Machine Learning demonstrates how to build a scalable and accurate chatbot using Python. With modular design and extensibility, this project can be adapted for real-world applications in customer support, education, and more. For more advanced projects, visit Python Central Hub.
Was this page helpful?
Let us know how we did