mgbam commited on
Commit
58f2491
·
verified ·
1 Parent(s): 18347b1

Create profiling.py

Browse files
Files changed (1) hide show
  1. modules/profiling.py +98 -0
modules/profiling.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modules/profiling.py
2
+
3
+ # -*- coding: utf-8 -*-
4
+ #
5
+ # PROJECT: CognitiveEDA v5.7 - The QuantumLeap Intelligence Platform
6
+ #
7
+ # DESCRIPTION: A dedicated module for profiling and characterizing customer
8
+ # segments identified through clustering.
9
+
10
+ import pandas as pd
11
+ import plotly.express as px
12
+ import plotly.graph_objects as go
13
+ import logging
14
+
15
+ def profile_clusters(df: pd.DataFrame, cluster_labels: pd.Series, numeric_cols: list, cat_cols: list) -> tuple:
16
+ """
17
+ Analyzes and profiles clusters to create meaningful business personas.
18
+
19
+ This function groups the data by cluster and calculates key statistics
20
+ for numeric and categorical features to describe each segment. It then
21
+ visualizes these differences.
22
+
23
+ Args:
24
+ df (pd.DataFrame): The feature-engineered DataFrame.
25
+ cluster_labels (pd.Series): The series of cluster labels from the K-Means model.
26
+ numeric_cols (list): List of numeric columns to profile (e.g., ['Total_Revenue']).
27
+ cat_cols (list): List of categorical columns to profile (e.g., ['City', 'Product']).
28
+
29
+ Returns:
30
+ A tuple containing:
31
+ - A markdown string with the detailed profile of each cluster.
32
+ - A Plotly Figure visualizing the differences between clusters.
33
+ """
34
+ # Ensure the dataframe used for profiling has the same index as the labels
35
+ profile_df = df.loc[cluster_labels.index].copy()
36
+ profile_df['Cluster'] = cluster_labels
37
+
38
+ if profile_df.empty:
39
+ return "No data available to profile clusters.", go.Figure()
40
+
41
+ logging.info(f"Profiling {profile_df['Cluster'].nunique()} clusters...")
42
+
43
+ # --- Generate Markdown Report ---
44
+ report_md = "### Cluster Persona Analysis\n\n"
45
+
46
+ # Analyze numeric features by cluster
47
+ numeric_profile = profile_df.groupby('Cluster')[numeric_cols].mean().round(2)
48
+
49
+ # Analyze categorical features by cluster (get the most frequent value - mode)
50
+ cat_profile_list = []
51
+ for col in cat_cols:
52
+ # This lambda is more robust for cases where a mode might not exist
53
+ mode_series = profile_df.groupby('Cluster')[col].apply(lambda x: x.mode()[0] if not x.mode().empty else "N/A")
54
+ mode_df = mode_series.to_frame()
55
+ cat_profile_list.append(mode_df)
56
+
57
+ full_profile = pd.concat([numeric_profile] + cat_profile_list, axis=1)
58
+
59
+ for cluster_id in sorted(profile_df['Cluster'].unique()):
60
+ # Try to name the persona by the dominant city, fall back to a generic name
61
+ try:
62
+ persona_name = full_profile.loc[cluster_id, 'City']
63
+ except KeyError:
64
+ persona_name = f"Segment {cluster_id}"
65
+
66
+ report_md += f"#### Cluster {cluster_id}: The '{persona_name}' Persona\n"
67
+
68
+ # Numeric Summary
69
+ for col in numeric_cols:
70
+ val = full_profile.loc[cluster_id, col]
71
+ report_md += f"- **Avg. {col.replace('_', ' ')}:** `{val:,.2f}`\n"
72
+
73
+ # Categorical Summary
74
+ for col in cat_cols:
75
+ val = full_profile.loc[cluster_id, col]
76
+ report_md += f"- **Dominant {col.replace('_', ' ')}:** `{val}`\n"
77
+ report_md += "\n"
78
+
79
+ # --- Generate Visualization ---
80
+ # We'll visualize the average 'Total_Revenue' by 'City' for each cluster
81
+ # This directly tests our hypothesis that 'City' is the dominant feature.
82
+ try:
83
+ vis_df = profile_df.groupby(['Cluster', 'City'])['Total_Revenue'].mean().reset_index()
84
+
85
+ fig = px.bar(
86
+ vis_df,
87
+ x='Cluster',
88
+ y='Total_Revenue',
89
+ color='City',
90
+ barmode='group',
91
+ title='<b>Cluster Profile: Avg. Total Revenue by Dominant City</b>',
92
+ labels={'Total_Revenue': 'Average Total Revenue ($)', 'Cluster': 'Customer Segment'}
93
+ )
94
+ except Exception as e:
95
+ logging.error(f"Could not generate profile visualization: {e}")
96
+ fig = go.Figure().update_layout(title="Could not generate profile visualization.")
97
+
98
+ return report_md, fig