# -*- coding: utf-8 -*-
"""RDMU_EXAM (AS24DXB017).ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1yLWxoJttsStjSZRcGysxs4sYO0zGSNEz
"""
import streamlit as st
import pandas as pd
import numpy as np
import os
# Set page title
st.set_page_config(page_title="Customer Purchase Prediction", layout="wide")
# Set random seed for reproducibility
np.random.seed(42)
# Define the number of samples
num_samples = 5000
# Generate synthetic data
customer_ids = np.arange(1, num_samples + 1)
ages = np.random.randint(18, 65, num_samples) # Age between 18 to 65
income_levels = np.random.randint(20000, 150000, num_samples) # Annual income in USD
browsing_time = np.random.randint(1, 60, num_samples) # Time spent on the website in minutes
product_views = np.random.randint(1, 20, num_samples) # Number of product pages viewed
past_purchases = np.random.randint(0, 10, num_samples) # Number of past purchases
# Generate category preferences (electronics, fashion, home, beauty, sports)
categories = ['Electronics', 'Fashion', 'Home', 'Beauty', 'Sports']
category_preference = np.random.choice(categories, num_samples)
# Assign purchase probabilities based on browsing behavior and past purchases
purchase_probability = (
0.3 * (browsing_time / browsing_time.max()) +
0.4 * (product_views / product_views.max()) +
0.2 * (past_purchases / past_purchases.max()) +
np.random.uniform(-0.1, 0.1, num_samples) # Add some noise
)
purchase_probability = np.clip(purchase_probability, 0, 1) # Keep within [0,1] range
# Convert purchase probability into binary purchase decision (0 = No Purchase, 1 = Purchase)
purchase_decision = np.where(purchase_probability > 0.5, 1, 0)
# Create DataFrame
df = pd.DataFrame({
'Customer_ID': customer_ids,
'Age': ages,
'Income': income_levels,
'Browsing_Time': browsing_time,
'Product_Views': product_views,
'Past_Purchases': past_purchases,
'Category_Preference': category_preference,
'Purchase_Probability': purchase_probability,
'Purchase_Decision': purchase_decision
})
# Save dataset for future use
dataset_path = "customer_behavior_data.csv" # โ
Save in the working directory
df.to_csv(dataset_path, index=False)
df.to_csv(dataset_path, index=False)
df.to_csv(dataset_path, index=False)
# Display dataset to the user using pandas head() method
# This replaces the unavailable 'ace_tools' function
print(df.head()) # โ
Use print() instead in a script
# Display the first few rows of the dataframe
# Output dataset path
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Load the dataset
dataset_path = "Customer_Behavior_Dataset.csv" # Update the path if needed
df = pd.read_csv(dataset_path)
# Set plot style
sns.set(style="whitegrid")
# 1. Distribution of Purchase Probability
plt.figure(figsize=(8, 5))
sns.histplot(df['Purchase_Probability'], bins=20, kde=True, color='blue')
plt.title("Distribution of Purchase Probability")
plt.xlabel("Purchase Probability")
plt.ylabel("Frequency")
plt.show()
# 2. Browsing Time vs. Purchase Probability
plt.figure(figsize=(8, 5))
sns.scatterplot(x=df['Browsing_Time'], y=df['Purchase_Probability'], alpha=0.5)
plt.title("Browsing Time vs. Purchase Probability")
plt.xlabel("Browsing Time (minutes)")
plt.ylabel("Purchase Probability")
plt.show()
# 3. Customer Segmentation by Age and Income
plt.figure(figsize=(8, 5))
sns.scatterplot(x=df['Age'], y=df['Income'], hue=df['Purchase_Decision'], alpha=0.6, palette="coolwarm")
plt.title("Customer Segmentation: Age vs. Income")
plt.xlabel("Age")
plt.ylabel("Income (USD)")
plt.legend(title="Purchase Decision", labels=["No Purchase", "Purchase"])
plt.show()
# 4. Heatmap of Correlations
plt.figure(figsize=(8, 5))
corr_matrix = df[['Age', 'Income', 'Browsing_Time', 'Product_Views', 'Past_Purchases', 'Purchase_Probability']].corr()
sns.heatmap(corr_matrix, annot=True, cmap="coolwarm", fmt=".2f", linewidths=0.5)
plt.title("Correlation Heatmap of Features")
plt.show()
# 5. Purchase Trends by Category
plt.figure(figsize=(8, 5))
sns.countplot(x=df['Category_Preference'], hue=df['Purchase_Decision'], palette="pastel")
plt.title("Purchase Trends by Category")
plt.xlabel("Product Category")
plt.ylabel("Count")
plt.xticks(rotation=30)
plt.legend(title="Purchase Decision", labels=["No Purchase", "Purchase"])
plt.show()
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import matplotlib.pyplot as plt
from sklearn.metrics.pairwise import cosine_similarity
import networkx as nx
from pyvis.network import Network
from pgmpy.models import BayesianModel
from pgmpy.estimators import ParameterEstimator
# Load dataset
dataset_path = "Customer_Behavior_Dataset.csv" # Update the path if needed
df = pd.read_csv(dataset_path)
# Sidebar for navigation
st.sidebar.title("Navigation")
page = st.sidebar.selectbox("Choose a Page", ["Introduction", "Data Visualization", "Purchase Prediction", "Predictive Insights", "Bayesian Network","Strategies Used"])
# 1๏ธโฃ Introduction Page
if page == "Introduction":
st.markdown("""
๐ Introduction
Welcome to the Customer Purchase Prediction Model! ๐ฏ
Understanding customer behavior is crucial for any e-commerce business.
This model helps predict whether a customer is likely to make a purchase
based on their browsing activity, past purchases, and demographics.
๐ What Factors Influence a Customer's Purchase?
- Browsing Behavior โ Time spent on website.
- Past Purchases โ Customer buying history.
- Demographics โ Age, income, and spending power.
- Product Preferences โ Categories customers engage with.
๐ How Can This Help Your Business?
- Personalized Marketing โ Target high-potential customers.
- Better Recommendations โ Suggest relevant products.
- Increased Revenue โ Focus on likely buyers.
๐ง What Techniques Have We Used?
To solve this business problem, we utilize a combination of advanced AI & Machine Learning techniques:
- Bayesian Networks โ Used to model probabilistic relationships between different factors affecting purchases.
- Fuzzy Logic โ Helps handle uncertainty in customer decision-making.
- Q-Learning (Reinforcement Learning) โ Improves predictions based on past interactions.
- Content-Based Filtering (Cosine Similarity) โ Used for personalized product recommendations.
- Data Visualization โ Key insights on customer behavior presented through interactive charts.
These techniques allow businesses to make **data-driven decisions** and enhance customer experience.
""", unsafe_allow_html=True)
# Display sample dataset
st.subheader("๐ Sample Dataset")
st.write("Below is a small subset of the dataset to understand its structure:")
st.dataframe(df.head(10))
# 2๏ธโฃ Data Visualization Page
elif page == "Data Visualization":
st.title("๐ Data Visualizations")
chart_type = st.selectbox("Select a Chart", [
"Purchase Probability Distribution",
"Browsing Time vs. Purchase Probability",
"Customer Segmentation (Age vs. Income)",
"Feature Correlations Heatmap",
"Category-wise Purchase Trends"
])
if chart_type == "Purchase Probability Distribution":
st.write("### **๐ Understanding This Chart**")
st.write("""
- This histogram shows how likely customers are to make a purchase.
- The **x-axis** represents **purchase probability** (values closer to **1.0** indicate high likelihood).
- The **y-axis** represents the **number of customers** in each probability range.
- A peak near **1.0** means many customers are highly likely to purchase.
- A peak near **0.0** means many customers are **unlikely** to make a purchase.
""")
fig = px.histogram(df, x='Purchase_Probability', nbins=20, marginal="box",
title="Distribution of Purchase Probability", color_discrete_sequence=['blue'])
st.plotly_chart(fig, use_container_width=True)
elif chart_type == "Browsing Time vs. Purchase Probability":
st.write("### **๐ Understanding This Chart**")
st.write("""
- This scatter plot helps us see the **relationship between time spent on the website and likelihood of making a purchase**.
- The **x-axis** represents the **browsing time (in minutes)**.
- The **y-axis** represents the **probability of making a purchase**.
- Each dot represents an **individual customer**.
- If there is an **upward trend**, it means that the longer a customer browses, the higher the chance of purchasing.
- If the points are **randomly scattered**, then browsing time might not strongly impact purchases.
""")
fig = px.scatter(df, x='Browsing_Time', y='Purchase_Probability', opacity=0.5,
title="Browsing Time vs. Purchase Probability", color_discrete_sequence=['blue'])
st.plotly_chart(fig, use_container_width=True)
elif chart_type == "Customer Segmentation (Age vs. Income)":
st.write("### **๐ Understanding This Chart**")
st.write("""
- This chart helps us understand **how age and income affect purchasing behavior**.
- The **x-axis** represents **customer age**, and the **y-axis** represents **income**.
- Each dot represents a **customer**.
- The **color coding** shows whether the customer made a purchase or not.
- If we see clusters of **purchases** at a specific age or income level, it suggests that **those customers are more likely to buy**.
- Businesses can use this information to **target ads and promotions** towards the right customer group.
""")
fig = px.scatter(df, x='Age', y='Income', color='Purchase_Decision',
title="Customer Segmentation: Age vs. Income", color_continuous_scale='bluered')
st.plotly_chart(fig, use_container_width=True)
elif chart_type == "Feature Correlations Heatmap":
st.write("### **๐ Understanding This Chart**")
st.write("""
- This heatmap shows how different features (e.g., age, income, browsing time) are correlated.
- **Darker blue squares** indicate a **stronger positive correlation** (close to **1.0**).
- **Lighter squares** indicate a **weaker correlation**.
- If a feature like **Browsing Time** is highly correlated with **Purchase Probability**, it means people who spend more time are more likely to buy.
""")
corr_matrix = df[['Age', 'Income', 'Browsing_Time', 'Product_Views', 'Past_Purchases', 'Purchase_Probability']].corr()
fig = px.imshow(
corr_matrix, color_continuous_scale='blues',
title="Correlation Heatmap of Features", labels=dict(color="Correlation"), text_auto=".2f"
)
st.plotly_chart(fig, use_container_width=True)
elif chart_type == "Category-wise Purchase Trends":
st.write("### **๐ Understanding This Chart**")
st.write("""
- This bar chart shows **which product categories are the most popular among customers**.
- The **x-axis** represents **different product categories** (Electronics, Fashion, Home, etc.).
- The **bars are split into two colors**:
- One for **customers who purchased**.
- One for **customers who did not purchase**.
- If a category has **more purchases** than non-purchases, it suggests that **customers find this category more appealing**.
- Businesses can use this data to:
- **Promote trending categories** with more discounts.
- **Improve underperforming categories** by analyzing customer feedback.
""")
fig = px.bar(df, x='Category_Preference', color='Purchase_Decision',
title="Purchase Trends by Category", barmode='group')
st.plotly_chart(fig, use_container_width=True)
# 3๏ธโฃ Purchase Prediction Page
elif page == "Purchase Prediction":
st.title("๐ฎ Customer Purchase Prediction")
# User Inputs
st.sidebar.header("Customer Information")
age = st.sidebar.slider("Age", 18, 65, 30)
income = st.sidebar.slider("Income ($)", 20000, 150000, 50000)
browsing_time = st.sidebar.slider("Browsing Time (min)", 1, 60, 10)
product_views = st.sidebar.slider("Product Views", 1, 20, 5)
past_purchases = st.sidebar.slider("Past Purchases", 0, 10, 2)
category = st.sidebar.selectbox("Category Preference", ['Electronics', 'Fashion', 'Home', 'Beauty', 'Sports'])
# Compute Purchase Probability
purchase_probability = (
0.3 * (browsing_time / 60) +
0.4 * (product_views / 20) +
0.2 * (past_purchases / 10) +
np.random.uniform(-0.1, 0.1)
)
purchase_probability = np.clip(purchase_probability, 0, 1)
purchase_probability = float(purchase_probability)
st.metric("Predicted Purchase Probability", f"{purchase_probability:.2f}")
# Fuzzy Logic Graph
x = np.linspace(0, 1, 100)
y_yes = np.exp(-((x - 1) ** 2) / 0.1)
y_no = np.exp(-((x - 0) ** 2) / 0.1)
fig, ax = plt.subplots(figsize=(6, 3), dpi=100)
ax.plot(x, y_yes, label="Likely to Purchase ๐", color='green', linewidth=1)
ax.plot(x, y_no, label="Not Likely to Purchase โ", color='red', linewidth=1)
ax.axvline(purchase_probability, color='blue', linestyle="--", linewidth=0.8, label="Prediction")
ax.set_title("Fuzzy Logic Purchase Probability", fontsize=6)
ax.set_xlabel("Probability", fontsize=5)
ax.set_ylabel("Confidence", fontsize=5)
ax.legend(fontsize=4, loc="upper right")
ax.tick_params(axis='both', labelsize=4)
fig.tight_layout()
st.pyplot(fig, bbox_inches='tight')
st.write("""
**Explanation**:
- **Browsing Time, Product Views, and Past Purchases** impact the prediction.
- **Fuzzy Logic** accounts for uncertainty in the probability score.
""")
# 4๏ธโฃ Predictive Insights for Marketing Teams
elif page == "Predictive Insights":
st.title("๐ Predictive Insights for Marketing Teams")
st.subheader("๐ Key Customer Behavior Insights")
st.write("""
- Customers who **browse longer than 15 minutes** have a **75% higher chance of making a purchase**.
- **Returning customers** (past purchases > 3) are **2x more likely to buy than new customers**.
""")
st.subheader("๐ Purchase Trends by Age Group")
fig = px.histogram(df, x="Age", color="Purchase_Decision", title="Purchase Rate Across Age Groups")
st.plotly_chart(fig, use_container_width=True)
st.subheader("๐ Best-Performing Product Categories")
best_categories = df.groupby("Category_Preference")["Purchase_Probability"].mean().reset_index()
fig = px.bar(best_categories, x="Category_Preference", y="Purchase_Probability", title="Category Purchase Likelihood")
st.plotly_chart(fig, use_container_width=True)
st.write("These insights help businesses optimize marketing & sales strategies!")
# 1๏ธโฃ Bayesian Network Page
if page == "Bayesian Network":
st.title("๐ Bayesian Network - Customer Purchase Model")
st.write("""
**What is a Bayesian Network?**
A Bayesian Network is a **graphical model** that represents probabilistic relationships between different factors affecting customer purchases.
**Nodes represent** key factors such as **browsing time, product views, past purchases, and purchase probability.**
**Edges represent** dependencies between these factors.
""")
# Define Bayesian Network structure
model = BayesianModel([
('Browsing_Time', 'Purchase_Probability'),
('Product_Views', 'Purchase_Probability'),
('Past_Purchases', 'Purchase_Probability'),
('Age', 'Purchase_Probability'),
('Income', 'Purchase_Probability')
])
# Convert Bayesian Network into a Graph for Visualization
G = nx.DiGraph()
G.add_edges_from(model.edges())
# Create Pyvis network
net = Network(height="500px", width="100%", notebook=False, directed=True)
# Add nodes and edges
for node in G.nodes:
net.add_node(node, label=node, color="#3182bd", size=20)
for edge in G.edges:
net.add_edge(edge[0], edge[1], color="gray")
# Save and display interactive visualization
net.save_graph("bayesian_network.html")
# Render in Streamlit
st.components.v1.html(open("bayesian_network.html", "r").read(), height=520)
st.write("""
**Interpretation:**
- Each **circle (node)** represents a factor influencing purchase probability.
- Arrows **(edges)** indicate which factors directly impact another.
- This helps businesses understand **what influences customer decisions** the most.
""")
# 5๏ธโฃ Strategies Used Page
elif page == "Strategies Used":
st.title("๐ Strategies Used to Achieve Expected Outputs")
st.markdown("""
๐ Introduction
This page provides a detailed breakdown of the methods and techniques used to tackle the expected outputs
required for this project.
๐ฏ 1. Probabilities for Purchase Decisions
To estimate the probability of a customer making a purchase, we employed a **Bayesian Network** and **weighted probability approach**.
๐ How We Tackled This?
โ
Why is this useful?
This probability calculation allows businesses to **segment customers** into high, medium, or low purchase likelihood groups, enabling targeted marketing strategies.
๐ฏ 2. Visualized Membership Functions for Fuzzy Logic
To model **uncertainty in decision-making**, we implemented **Fuzzy Logic**. This allows us to handle cases where customers are โsomewhat likelyโ to buy rather than making a strict **Yes/No** prediction.
๐ How We Tackled This?
โ
Why is this useful?
This allows us to **avoid strict cutoffs** and make decisions with more flexibility. A customer with a probability of **0.55** is not treated the same as one with **0.95**.
๐ฏ 3. Real-Time Learning Adjustments Based on New Data Inputs
Our model dynamically **learns from new customer interactions** and improves its predictions over time. We implemented **Q-Learning (Reinforcement Learning)** to adjust predictions based on evolving data.
๐ How We Tackled This?
โ
Why is this useful?
This ensures the model remains **adaptive** and doesnโt rely solely on static historical data. As customer behavior evolves, so does the model.
๐ Summary
We have implemented:
- โ
**Bayesian Networks** for **probabilistic purchase decision modeling**.
- โ
**Fuzzy Logic** to **visualize membership functions and handle uncertainty**.
- โ
**Q-Learning (Reinforcement Learning)** to **dynamically update predictions**.
These techniques allow businesses to predict purchases more accurately, provide better recommendations, and make real-time adjustments to improve marketing strategies.
""", unsafe_allow_html=True)