Chatbot with Machine Learning
Abstract
Section titled “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
Section titled “Prerequisites”- Python 3.8 or above
- A code editor or IDE
- Basic understanding of ML and chatbots
- Required libraries:
nltk,scikit-learn,pandas
Before you Start
Section titled “Before you Start”Install Python and the required libraries:
pip install nltk scikit-learn pandasGetting Started
Section titled “Getting Started”Create a Project
Section titled “Create a Project”- Create a folder named
chatbot-with-machine-learning. - Open the folder in your code editor or IDE.
- Create a file named
chatbot_with_machine_learning.py. - Copy the code below into your file.
Write the Code
Section titled “Write the Code”Chatbot with Machine Learning
pch.viewSource"""
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
def ask(prompt="", default=""):
"""Read a line, or fall back to `default` when nobody is there to type.
Without this the script raises EOFError the moment it runs unattended — in
a test, a scheduled job, or the build that captures this output for the
docs. The fallback is printed rather than silent, so a reader can always
tell which answers were typed and which were assumed.
"""
try:
return input(prompt).strip() or default
except EOFError:
print(f"{default} (no input available, using the default)")
return default
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 = ask('You: ', '1')
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
Section titled “Example Usage”python chatbot_with_machine_learning.pyHow it fits together
Section titled “How it fits together”Read from the top: this is what runs when you execute the file, and which function calls which. It is generated from the code, so it cannot drift from it.
flowchart TD
RUN(["python chatbot_with_machine_learning.py"])
build_dataset("build_dataset")
train_model("train_model")
get_response("get_response")
chat("chat")
main("main")
RUN --> main
chat --> get_response
main --> build_dataset
main --> chat
main --> train_model
What it produces
Section titled “What it produces”Running the file exactly as it ships takes 3.1 s and prints:
usage: chatbot_with_machine_learning.py [-h] [--train] [--model MODEL]
[--chat]
Chatbot with Machine Learning
options:
-h, --help show this help message and exit
--train Train model
--model MODEL Path to save/load model
--chat Start chatExplanation
Section titled “Explanation”Key Features
Section titled “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
Section titled “Code Breakdown”- What it imports (lines 6–12)
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 nltkbuild_dataset— the function (lines 22–28)
def build_dataset(intents):
X, y = [], []
for intent in intents:
for pattern in intent['patterns']:
X.append(pattern)
y.append(intent['intent'])
return X, ytrain_model— the function (lines 30–38)
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, vectorizerchat— the function (lines 46–54)
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))main— the function (lines 56–73)
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()The file defines 5 top-level symbols in all; the whole thing is above under Write the Code.
Features
Section titled “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
Section titled “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
Section titled “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
Section titled “Real-World Applications”- Customer Support Bots
- Virtual Assistants
- Educational Tools
Conclusion
Section titled “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.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading