RDMU_Exam / app.py
Anushree2000's picture
Update app.py
7925bab verified
Raw History Blame Contribute Delete
24 kB
# -*- 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("""
<h2 style='text-align: left; font-size: 28px;'>๐Ÿ“Œ <b>Introduction</b></h2>
<p style='font-size: 18px;'>Welcome to the <b>Customer Purchase Prediction Model!</b> ๐ŸŽฏ</p>
<p style='font-size: 16px;'>Understanding customer behavior is crucial for any <b>e-commerce business.</b>
This model helps predict <b>whether a customer is likely to make a purchase</b>
based on their <b>browsing activity, past purchases, and demographics.</b></p>
<hr>
<h3 style='font-size: 22px;'>๐Ÿ›’ What Factors Influence a Customer's Purchase?</h3>
<ul style='font-size: 16px;'>
<li><b>Browsing Behavior</b> โ†’ Time spent on website.</li>
<li><b>Past Purchases</b> โ†’ Customer buying history.</li>
<li><b>Demographics</b> โ†’ Age, income, and spending power.</li>
<li><b>Product Preferences</b> โ†’ Categories customers engage with.</li>
</ul>
<hr>
<h3 style='font-size: 22px;'>๐Ÿš€ How Can This Help Your Business?</h3>
<ul style='font-size: 16px;'>
<li><b>Personalized Marketing</b> โ†’ Target high-potential customers.</li>
<li><b>Better Recommendations</b> โ†’ Suggest relevant products.</li>
<li><b>Increased Revenue</b> โ†’ Focus on likely buyers.</li>
</ul>
<hr>
<h3 style='font-size: 22px;'>๐Ÿง  What Techniques Have We Used?</h3>
<p style='font-size: 16px;'>
To solve this business problem, we utilize a combination of advanced <b>AI & Machine Learning techniques</b>:
</p>
<ul style='font-size: 16px;'>
<li><b>Bayesian Networks</b> โ†’ Used to model probabilistic relationships between different factors affecting purchases.</li>
<li><b>Fuzzy Logic</b> โ†’ Helps handle uncertainty in customer decision-making.</li>
<li><b>Q-Learning (Reinforcement Learning)</b> โ†’ Improves predictions based on past interactions.</li>
<li><b>Content-Based Filtering (Cosine Similarity)</b> โ†’ Used for personalized product recommendations.</li>
<li><b>Data Visualization</b> โ†’ Key insights on customer behavior presented through interactive charts.</li>
</ul>
<p style='font-size: 16px;'>These techniques allow businesses to make **data-driven decisions** and enhance customer experience.</p>
<hr>
""", 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("""
<h3 style='font-size: 22px;'>๐Ÿ“Œ Introduction</h3>
<p style='font-size: 16px;'>This page provides a detailed breakdown of the methods and techniques used to tackle the expected outputs
required for this project.</p>
<hr>
<h3 style='font-size: 22px;'>๐ŸŽฏ 1. Probabilities for Purchase Decisions</h3>
<p style='font-size: 16px;'>
To estimate the probability of a customer making a purchase, we employed a **Bayesian Network** and **weighted probability approach**.
</p>
<h4 style='font-size: 18px;'>๐Ÿ“Œ How We Tackled This?</h4>
<ul style='font-size: 16px;'>
<li>We assigned **weights** to different customer behavior factors:
<ul>
<li>โณ <b>Browsing Time</b> (30%) โ†’ More browsing time means higher purchase probability.</li>
<li>๐Ÿ“ฆ <b>Product Views</b> (40%) โ†’ More viewed products indicate stronger purchase intent.</li>
<li>๐Ÿ›๏ธ <b>Past Purchases</b> (20%) โ†’ Repeat customers are more likely to buy again.</li>
<li>๐ŸŽฒ <b>Randomized Uncertainty</b> (10%) โ†’ Small randomness accounts for real-world variability.</li>
</ul>
</li>
<li>The formula used:
<pre style='background-color:#f4f4f4;padding:10px;border-radius:5px;'>
purchase_probability = (0.3 * (browsing_time / max_browsing)) +
(0.4 * (product_views / max_product_views)) +
(0.2 * (past_purchases / max_past_purchases)) +
np.random.uniform(-0.1, 0.1)
</pre>
</li>
<li>We then <b>normalized</b> the values to ensure they stayed within a **0 to 1 range**.</li>
</ul>
<h4 style='font-size: 18px;'>โœ… Why is this useful?</h4>
<p style='font-size: 16px;'>This probability calculation allows businesses to **segment customers** into high, medium, or low purchase likelihood groups, enabling targeted marketing strategies.</p>
<hr>
<h3 style='font-size: 22px;'>๐ŸŽฏ 2. Visualized Membership Functions for Fuzzy Logic</h3>
<p style='font-size: 16px;'>To model **uncertainty in decision-making**, we implemented **Fuzzy Logic**. This allows us to handle cases where customers are <i>โ€˜somewhat likelyโ€™</i> to buy rather than making a strict **Yes/No** prediction.</p>
<h4 style='font-size: 18px;'>๐Ÿ“Œ How We Tackled This?</h4>
<ul style='font-size: 16px;'>
<li>We used **membership functions** to define <b>fuzzy sets</b>:
<ul>
<li>๐Ÿ”ด **Not Likely to Purchase (Low Probability)** โ†’ 0 to 0.4 range.</li>
<li>๐ŸŸ  **Somewhat Likely to Purchase (Medium Probability)** โ†’ 0.4 to 0.7 range.</li>
<li>๐ŸŸข **Highly Likely to Purchase (High Probability)** โ†’ 0.7 to 1 range.</li>
</ul>
</li>
<li>The fuzzy logic function:
<pre style='background-color:#f4f4f4;padding:10px;border-radius:5px;'>
x = np.linspace(0, 1, 100)
y_yes = np.exp(-((x - 1) ** 2) / 0.1) # High likelihood curve
y_no = np.exp(-((x - 0) ** 2) / 0.1) # Low likelihood curve
</pre>
</li>
<li>We plotted these **fuzzy membership functions** in an interactive graph.</li>
</ul>
<h4 style='font-size: 18px;'>โœ… Why is this useful?</h4>
<p style='font-size: 16px;'>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**.</p>
<hr>
<h3 style='font-size: 22px;'>๐ŸŽฏ 3. Real-Time Learning Adjustments Based on New Data Inputs</h3>
<p style='font-size: 16px;'>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.</p>
<h4 style='font-size: 18px;'>๐Ÿ“Œ How We Tackled This?</h4>
<ul style='font-size: 16px;'>
<li>We used **Q-learning** to adjust purchase probabilities dynamically.</li>
<li>As new customer behavior data is fed in, the model **updates**:
<ul>
<li>New browsing behavior is incorporated into future purchase probabilities.</li>
<li>Previously seen purchase decisions **reinforce** the learning process.</li>
<li>Dynamic **exploration-exploitation tradeoff** helps improve accuracy.</li>
</ul>
</li>
<li>Example:
<pre style='background-color:#f4f4f4;padding:10px;border-radius:5px;'>
q_value = old_q_value + learning_rate * (reward + discount_factor * max_future_q - old_q_value)
</pre>
</li>
<li>Where:
<ul>
<li>๐Ÿ’ก **Reward** = Whether or not the customer made a purchase.</li>
<li>๐Ÿ“Š **Discount Factor** = Adjusts importance of future interactions.</li>
<li>โšก **Learning Rate** = Determines how quickly the model adapts.</li>
</ul>
</li>
</ul>
<h4 style='font-size: 18px;'>โœ… Why is this useful?</h4>
<p style='font-size: 16px;'>This ensures the model remains **adaptive** and doesnโ€™t rely solely on static historical data. As customer behavior evolves, so does the model.</p>
<hr>
<h3 style='font-size: 22px;'>๐Ÿš€ Summary</h3>
<p style='font-size: 16px;'>
We have implemented:
</p>
<ul style='font-size: 16px;'>
<li>โœ… **Bayesian Networks** for **probabilistic purchase decision modeling**.</li>
<li>โœ… **Fuzzy Logic** to **visualize membership functions and handle uncertainty**.</li>
<li>โœ… **Q-Learning (Reinforcement Learning)** to **dynamically update predictions**.</li>
</ul>
<p style='font-size: 16px;'>These techniques allow businesses to <b>predict purchases more accurately, provide better recommendations, and make real-time adjustments</b> to improve marketing strategies.</p>
""", unsafe_allow_html=True)