Chatbot Product Recommendations using NLP
Chatbot Product Recommendations using NLP
Business Objective: Provide instant assistance to customers on product recommendations on a Customer Service Chatbot at eCommerce business
Tip: Try it in Google Colab!
1. Generate Dataset
import pandas as pd
# Create a synthetic dataset for customer queries and interactions
data = {
'query': ['How can I track my order?', 'Do you have this item in stock?', 'Can I return this product?',
'Which products are trending?', 'Can you recommend a laptop for programming?'],
'intent': ['order_tracking', 'product_availability', 'return_policy',
'trending_products', 'product_recommendation'],
'response': ['To track your order, please visit our website and go to the order tracking section.',
'Yes, the item is currently in stock.',
'Our return policy allows returns within 30 days of purchase.',
'Our trending products include electronics, clothing, and accessories.',
'Sure! Based on your needs, we recommend the XYZ laptop for programming.']
}
# Create a DataFrame from the data
customer_data = pd.DataFrame(data)
# Display the dataset
print("Customer Service Dataset:")
print(customer_data)
Model Building- NLP
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import MultinomialNB
# Define a TF-IDF Vectorizer
tfidf_vectorizer = TfidfVectorizer()
# Define a Naive Bayes Classifier
naive_bayes_classifier = MultinomialNB()
# Create an NLP Pipeline
nlp_pipeline = Pipeline([
('tfidf_vectorizer', tfidf_vectorizer),
('classifier', naive_bayes_classifier)
])
# Fit the pipeline on the dataset
nlp_pipeline.fit(customer_data['query'], customer_data['intent'])
# Function to predict intent based on query
def predict_intent(query):
return nlp_pipeline.predict([query])[0]
# Test the model
query = "Can you recommend a laptop for gaming?"
predicted_intent = predict_intent(query)
print(f"Predicted Intent for query '{query}': {predicted_intent}")
Show and Save the Results
# Predict intents for a list of queries
queries = ["How do I track my order?", "Is this item available for shipping?", "What is your refund policy?"]
predicted_intents = [predict_intent(q) for q in queries]
# Display the results
print("\nPredicted Intents for Queries:")
for i, query in enumerate(queries):
print(f"Query: {query} | Predicted Intent: {predicted_intents[i]}")
# Save the results to a CSV file
results_df = pd.DataFrame({'Query': queries, 'Predicted Intent': predicted_intents})
results_df.to_csv('nlp_results.csv', index=False)
print("\nResults saved to 'nlp_results.csv' file.")
Get the code: Github
Comments
Post a Comment