import re
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import sys
class LearningChatbot:
def __init__(self):
self.vectorizer = TfidfVectorizer(lowercase=True, token_pattern=r'(?u)\b\w+\b')
self.inputs = []
self.responses = []
self.trained = False
def preprocess(self, text):
# Simple preprocessing: lowercase and remove punctuation (handled by vectorizer mostly)
text = text.lower().strip()
text = re.sub(r'[^\w\s]', ' ', text)
return ' '.join(text.split()) # Normalize spaces
def add_training_data(self, user_input, bot_response):
processed_input = self.preprocess(user_input)
if processed_input: # Avoid empty
self.inputs.append(processed_input)
self.responses.append(bot_response)
self._train()
def _train(self):
if self.inputs:
self.vectorizer.fit(self.inputs)
self.trained = True
def get_response(self, user_input):
processed_input = self.preprocess(user_input)
if not self.trained or not self.inputs:
return self._get_default_response()
# Transform current input
input_vec = self.vectorizer.transform([processed_input])
# Compute similarities to all training inputs
training_vecs = self.vectorizer.transform(self.inputs)
similarities = cosine_similarity(input_vec, training_vecs)[0]
# Find best match
best_idx = np.argmax(similarities)
best_similarity = similarities[best_idx]
# Threshold for "good enough" match (tune as needed: 0.0 always matches closest, 1.0 exact)
if best_similarity > 0.4:
print(f"(Match confidence: {best_similarity:.2f})", file=sys.stderr)
return self.responses[best_idx]
# No good match: learn a new response interactively
print("I don't know that yet. Teach me what to respond:", file=sys.stderr)
new_response = input().strip()
if new_response:
self.add_training_data(user_input, new_response)
print("(Learned! Added to memory.)", file=sys.stderr)
return new_response
else:
return self._get_default_response()
def _get_default_response(self):
defaults = [
"Interesting. Tell me more.",
"I'm still learning. Can you teach me?",
"Sorry, I don't understand yet."
]
import random
return random.choice(defaults)
def main():
bot = LearningChatbot()
# Seed with some initial training data for a basic personality
training_data = [
("hello", "Hi! How can I help you today?"),
("hi", "Hello there!"),
("how are you", "I'm doing great, thanks for asking!"),
("bye", "Goodbye! Have a nice day."),
("what is your name", "I'm a learning chatbot built with Python and scikit-learn."),
("thank you", "You're welcome!"),
("quit", "See you later!"),
("help", "Just chat with me. If I don't know something, teach me by providing a response."),
("tell me a joke", "Why did the programmer quit? Because he didn't get arrays!"),
]
for user_in, bot_resp in training_data:
bot.add_training_data(user_in, bot_resp)
print("Learning Chatbot ready! Type 'quit' to exit.")
print("Try saying something new - I'll ask to learn from it.\n")
while True:
try:
user_input = input("You: ").strip()
if user_input.lower() in ['quit', 'exit', 'bye']:
print("Bot: Goodbye!")
break
if not user_input:
continue
response = bot.get_response(user_input)
print(f"Bot: {response}\n")
except KeyboardInterrupt:
print("\nBot: Goodbye!")
break
except EOFError:
break
if __name__ == "__main__":
main()
How it works:
Preprocessing: Converts input to lowercase, removes punctuation, normalizes spaces.
TF-IDF Vectorization: Uses scikit-learn's TfidfVectorizer to convert text to vectors.
Learning Mechanism:
Stores pairs of (processed user input, bot response).
For new input, computes cosine similarity to all stored inputs.
If similarity > 0.4 (tunable threshold), responds with the closest match.
Otherwise, interactively learns: prompts you for a response, stores the pair, and uses it immediately.
Seeding: Starts with basic responses for common phrases.
Console Loop: Simple chat interface. Handles 'quit', empty inputs, etc.
Dependencies: numpy, scikit-learn (install with pip install numpy scikit-learn).
Example Interaction:
code
You: hello
Bot: Hi! How can I help you today?
You: What's the weather?
(I don't know that yet. Teach me what to respond: It's sunny!)
Bot: It's sunny!
(Learned! Added to memory.)
Run it, chat, and watch it learn! The threshold ensures it doesn't hallucinate bad matches. Adjust 0.4 for stricter/looser matching.