The user wants a Python script for a simple chatbot.
Key features requested:
- Simple.
- Learns from conversations.
- Uses basic machine learning.
Understanding "Learns from Conversations":
This usually implies that if the bot doesn't know the answer to a specific input, it asks the user for the correct answer and stores it. Next time that specific input (or a similar one) appears, it recalls the stored answer.
Alternatively, it could mean training a model on the fly, but for a "simple" script, a dictionary-based approach or a very basic cosine similarity search with a growing knowledge base is more practical and understandable than retraining a neural network in real-time.
Approach:
- Storage: I need a way to store the learned data. A JSON file is simple and persists data between sessions.
- Matching Strategy:
- Exact match: Too rigid.
- Fuzzy match / Similarity: This is where the "machine learning" aspect comes in for a simple script. TF-IDF (Term Frequency-Inverse Document Frequency) and Cosine Similarity are standard, lightweight techniques to measure text similarity. Scikit-learn is the standard library for this in Python.
- The Loop:
- User inputs text.
- Bot preprocesses text (lowercase, maybe remove punctuation).
- Bot compares input against its database of known questions.
- If a match is found (similarity > threshold), return the best answer.
- If no match, ask the user "I don't know. How should I respond?"
- Save the new question-answer pair to the database.
- Retrain (refit) the vectorizer or update the matrix.
Libraries:
sklearn: For TfidfVectorizer and cosine_similarity.
json: For saving/loading the brain.
numpy: Implicitly used by sklearn, good to have.
Code Structure:
- Class
ChatBot.
__init__: Load data, initialize vectorizer.
train: Fit the vectorizer on current questions.
get_response: Vectorize input, calculate similarities, return best match or ask to learn.
learn: Add to dictionary, retrain.
save: Dump to JSON.
Refining the "Machine Learning" part:
To keep it truly simple but functional, I'll use TfidfVectorizer.
- Convert all known questions into vectors.
- Convert the user's input into a vector.
- Compute cosine similarity between input vector and all known question vectors.
- Pick the one with the highest score.
- If score < threshold (e.g., 0.5), treat as unknown.
Edge Cases:
- Empty database: The bot must handle the case where the JSON is empty or doesn't exist. The vectorizer will fail if fit on empty data. I need a flag to handle the "first run" state.
- Quit command.
Drafting the Code (Mental or Scratchpad):
import json
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
class Bot:
def __init__(self):
self.memory_file = "memory.json"
self.data = {} # {question: answer}
self.load()
self.vectorizer = TfidfVectorizer()
if self.data:
self.train()
def train(self):
self.vectors = self.vectorizer.fit_transform(self.data.keys())
def respond(self, text):
if not self.data:
return self.learn_new(text)
# Calc similarity
input_vec = self.vectorizer.transform([text])
scores = cosine_similarity(input_vec, self.vectors)
# get max
Correction/Improvement:
If the database grows, re-vectorizing everything every time a single new line is added is inefficient. However, for a "simple" demonstration script, doing a full re-fit on every new learned interaction is acceptable and much easier to code than incremental vectorizer updates.
Code Polish:
I will add comments explaining why this is considered "Machine Learning" (it uses Vectorization and Cosine Similarity). I will also make the conversation loop clear.
Let's write the actual solution.
- Imports:
sklearn, json, os.
- Class
LearningBot:
load_memory: Load JSON.
save_memory: Save JSON.
train_model: Fit TF-IDF on questions.
respond: The core logic.
add_to_memory: Handle the "I don't know" case.
- Main execution block: The
while True loop.
Self-Correction during drafting:
The TfidfVectorizer needs a list of strings. self.data is a dictionary. I need to pass list(self.data.keys()) to the vectorizer.
If the user types "exit", handle that gracefully.
Let's finalize the code structure.
import json
import os
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# ... class definition ...
I will provide a robust example that creates a brain.json file so the user can see the learning persist.
User Experience:
User: "Hello"
Bot: "I don't know the answer. Please teach me."
User: "Hi there!"
Bot: "Thank you! I've learned that 'Hello' implies 'Hi there!'."
User: "Hello again"
Bot: "Hi there!" (High similarity match)
This looks good. It satisfies "simple", "learns", and "basic ML" (vectorization).
Here is a complete, runnable Python script for a chatbot that uses TF-IDF (Term Frequency-Inverse Document Frequency) and Cosine Similarity.
This is a form of basic machine learning used in Natural Language Processing. Instead of just looking for exact keyword matches, the bot converts sentences into mathematical vectors and calculates how mathematically similar your question is to the questions it has learned previously.
Prerequisites
You will need the scikit-learn library.
pip install scikit-learn numpy
The Python Code
Save this as chatbot.py and run it. It will create a file called memory.json to store what it learns.
import json
import os
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
class LearningChatBot:
def __init__(self, memory_file='memory.json'):
self.memory_file = memory_file
self.questions = []
self.answers = []
self.load_memory()
# Initialize the TF-IDF Vectorizer
# This converts text into numbers (vectors) based on word importance
self.vectorizer = TfidfVectorizer()
# Train the vectorizer on initial questions immediately if data exists
if self.questions:
self.vectorizer.fit(self.questions)
def load_memory(self):
"""Load conversation history from a JSON file."""
if os.path.exists(self.memory_file):
try:
with open(self.memory_file, 'r') as f:
data = json.load(f)
self.questions = data.get('questions', [])
self.answers = data.get('answers', [])
print(f"Bot: Loaded {len(self.questions)} memories from file.")
except json.JSONDecodeError:
print("Bot: Memory file corrupted. Starting fresh.")
else:
# Default seed data so the bot isn't completely empty on first run
self.questions = ["hello", "how are you", "what is your name"]
self.answers = ["Hi there!", "I am just a computer program.", "I am a Learning Bot."]
def save_memory(self):
"""Save conversation history to a JSON file."""
data = {
'questions': self.questions,
'answers': self.answers
}
with open(self.memory_file, 'w') as f:
json.dump(data, f, indent=4)
def get_response(self, user_input):
"""
1. Vectorize user input.
2. Calculate cosine similarity against known questions.
3. Return the best match or ask to learn.
"""
user_input = user_input.lower().strip()
if not user_input:
return "Please say something."
# If the bot has no memory yet (empty start)
if not self.questions:
return self.learn_new(user_input)
# 1. Transform user input into a vector using the existing vocabulary
# We handle the potential error if the input contains words the vectorizer has never seen
try:
# We must re-fit temporarily to include the new input in the matrix for comparison
# In a production app, you would use a more sophisticated approach (like SentenceTransformers)
all_sentences = self.questions + [user_input]
tfidf_matrix = self.vectorizer.fit_transform(all_sentences)
# The last vector is the user input
user_vector = tfidf_matrix[-1]
# The rest are the database
question_vectors = tfidf_matrix[:-1]
except ValueError:
return "I'm having trouble processing that."
# 2. Calculate Similarity
# Result is an array of similarity scores between 0 (no match) and 1 (perfect match)
similarity_scores = cosine_similarity(user_vector, question_vectors)
# Find the index of the highest score
best_match_index = np.argmax(similarity_scores)
best_score = similarity_scores[0][best_match_index]
# 3. Decide based on Threshold
# If similarity is > 0.7 (70%), we consider it a match
if best_score > 0.7:
return self.answers[best_match_index]
else:
return self.learn_new(user_input)
def learn_new(self, user_input):
"""
If the bot doesn't know the answer, it asks the user to teach it.
"""
print(f"Bot: I don't understand '{user_input}'. How should I respond?")
response = input("User (Teach me): ")
# Store the new Q&A
self.questions.append(user_input)
self.answers.append(response)
# Re-train the vectorizer with the expanded vocabulary
self.vectorizer.fit(self.questions)
# Save to file
self.save_memory()
return "Bot: Thanks! I've learned something new."
# --- Main Execution Loop ---
if __name__ == "__main__":
bot = LearningChatBot()
print("Bot: Hello! Talk to me. (Type 'exit' to quit)")
while True:
user_input = input("You: ")
if user_input.lower() in ['exit', 'quit', 'bye']:
print("Bot: Goodbye!")
break
response = bot.get_response(user_input)
print(f"Bot: {response}")
How it Works
-
TF-IDF (The "Brain"):
The bot doesn't understand English grammar; it understands math. It uses TfidfVectorizer to break sentences down into numbers.
- It counts how often a word appears (Term Frequency).
- It reduces the importance of common words (like "the", "is") and increases the importance of unique words (Inverse Document Frequency).
-
Cosine Similarity (The Matching Logic):
When you type "What is python?", the bot converts that into a vector. It then calculates the angle (cosine) between your vector and the vectors of all questions it knows.
- If you ask "Hello", and it knows "Hello", the angle is 0 (Similarity 1.0).
- If you ask "Hi", and it only knows "Hello", the similarity might be lower (e.g., 0.0 if no shared words). This is a limitation of simple TF-IDF.
-
The Learning Loop:
If the similarity score is low (below 0.7), the bot enters "Learning Mode." It asks you for the correct answer, appends it to its list, and immediately runs fit() again to update its mathematical model.
How to Test It
- Run the script.
- Type "Hello" (It should recognize the seed data).
- Type "Who made you?" (It won't know).
- It will ask: I don't understand 'who made you?'. How should I respond?
- You type: "I was made by Python code."
- Type "Who made you?" again.
- It should now reply: I was made by Python code.
- Close the program and reopen it. It will remember your answer because it saved it to
memory.json.