DIVYANSHI SINGH commited on
Commit
8cf0205
·
1 Parent(s): 6469f7e

Stability Fix: Cached PCA and containerized charts to eliminate flickering

Browse files
Files changed (1) hide show
  1. app.py +64 -42
app.py CHANGED
@@ -95,6 +95,15 @@ def load_model():
95
  data_dict = joblib.load(SCALED_DATA_PATH)
96
  return model, data_dict
97
 
 
 
 
 
 
 
 
 
 
98
  def main():
99
  # Load Data & Model
100
  df, df_raw = load_data()
@@ -134,55 +143,68 @@ def main():
134
  st.markdown("---")
135
 
136
  # Visualization Row 1: Distribution & PCA
137
- v1, v2 = st.columns(2)
 
138
 
139
- with v1:
140
- st.subheader("Customer Distribution by Segment")
141
- fig, ax = plt.subplots(figsize=(8, 6))
142
- df['Segment'].value_counts().plot(kind='pie', autopct='%1.1f%%', colors=sns.color_palette('viridis'), ax=ax)
143
- ax.set_ylabel("")
144
- st.pyplot(fig)
 
 
 
 
 
 
145
 
146
- with v2:
147
- st.subheader("2D Segment Projection (PCA)")
148
- # Recompute PCA for selected data
149
- X_scaled = data_dict['rfm_scaled']
150
- pca = PCA(n_components=2)
151
- X_pca = pca.fit_transform(X_scaled)
152
- pca_df = pd.DataFrame(X_pca, columns=['PCA1', 'PCA2'], index=X_scaled.index)
153
- pca_df['Segment'] = df['Segment']
154
-
155
- fig, ax = plt.subplots(figsize=(8, 6))
156
- sns.scatterplot(x='PCA1', y='PCA2', hue='Segment', data=pca_df, palette='viridis', alpha=0.7, ax=ax)
157
- st.pyplot(fig)
 
 
 
 
 
158
 
159
  st.markdown("---")
160
  # --- Advanced Forecasting Section ---
161
  st.subheader("📉 Advanced Forecasting & Growth Metrics")
162
- t1, t2 = st.columns(2)
163
-
164
- with t1:
165
- st.write("**Monthly Revenue Trends**")
166
- if df_raw is not None:
167
- # Aggregate by Month
168
- df_raw['Month'] = df_raw['InvoiceDate'].dt.to_period('M').astype(str)
169
- df_raw['Revenue'] = df_raw['Quantity'] * df_raw['Price']
170
- monthly_rev = df_raw.groupby('Month')['Revenue'].sum().reset_index()
171
-
172
- fig, ax = plt.subplots(figsize=(10, 5))
173
- sns.lineplot(x='Month', y='Revenue', data=monthly_rev, marker='o', color='#60a5fa', ax=ax)
174
- plt.xticks(rotation=45)
175
- plt.grid(True, linestyle='--', alpha=0.6)
176
- st.pyplot(fig)
177
- else: st.info("Raw data not available for time-series.")
 
178
 
179
- with t2:
180
- st.write("**Revenue Contribution by Segment (Pareto)**")
181
- seg_rev = df.groupby('Segment')['Monetary'].sum().sort_values(ascending=False).reset_index()
182
- fig, ax = plt.subplots(figsize=(10, 5))
183
- sns.barplot(x='Segment', y='Monetary', data=seg_rev, palette='viridis', ax=ax)
184
- plt.ylabel("Total Revenue (GBP)")
185
- st.pyplot(fig)
186
 
187
  st.markdown("---")
188
 
 
95
  data_dict = joblib.load(SCALED_DATA_PATH)
96
  return model, data_dict
97
 
98
+ @st.cache_data
99
+ def get_pca_data(scaled_data, labels):
100
+ """Cache the PCA computation to prevent UI flicker on re-runs."""
101
+ pca = PCA(n_components=2)
102
+ X_pca = pca.fit_transform(scaled_data)
103
+ pca_df = pd.DataFrame(X_pca, columns=['PCA1', 'PCA2'], index=scaled_data.index)
104
+ pca_df['Segment'] = labels
105
+ return pca_df
106
+
107
  def main():
108
  # Load Data & Model
109
  df, df_raw = load_data()
 
143
  st.markdown("---")
144
 
145
  # Visualization Row 1: Distribution & PCA
146
+ with st.container():
147
+ v1, v2 = st.columns(2)
148
 
149
+ with v1:
150
+ st.subheader("Customer Distribution")
151
+ fig1, ax1 = plt.subplots(figsize=(7, 5))
152
+ df['Segment'].value_counts().plot(
153
+ kind='pie',
154
+ autopct='%1.1f%%',
155
+ colors=sns.color_palette('viridis'),
156
+ ax=ax1,
157
+ textprops={'color':"w"}
158
+ )
159
+ ax1.set_ylabel("")
160
+ st.pyplot(fig1, use_container_width=True)
161
 
162
+ with v2:
163
+ st.subheader("2D Segment Projection (PCA)")
164
+ # Use cached PCA data
165
+ pca_df = get_pca_data(data_dict['rfm_scaled'], df['Segment'])
166
+
167
+ fig2, ax2 = plt.subplots(figsize=(7, 5))
168
+ sns.scatterplot(
169
+ x='PCA1', y='PCA2',
170
+ hue='Segment',
171
+ data=pca_df,
172
+ palette='viridis',
173
+ alpha=0.6,
174
+ ax=ax2,
175
+ edgecolor='none'
176
+ )
177
+ ax2.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
178
+ st.pyplot(fig2, use_container_width=True)
179
 
180
  st.markdown("---")
181
  # --- Advanced Forecasting Section ---
182
  st.subheader("📉 Advanced Forecasting & Growth Metrics")
183
+ with st.container():
184
+ t1, t2 = st.columns(2)
185
+
186
+ with t1:
187
+ st.write("**Monthly Revenue Trends**")
188
+ if df_raw is not None:
189
+ # Aggregate by Month
190
+ df_raw['Month'] = df_raw['InvoiceDate'].dt.to_period('M').astype(str)
191
+ df_raw['Revenue'] = df_raw['Quantity'] * df_raw['Price']
192
+ monthly_rev = df_raw.groupby('Month')['Revenue'].sum().reset_index()
193
+
194
+ fig3, ax3 = plt.subplots(figsize=(10, 5))
195
+ sns.lineplot(x='Month', y='Revenue', data=monthly_rev, marker='o', color='#60a5fa', ax=ax3)
196
+ plt.xticks(rotation=45)
197
+ ax3.grid(True, linestyle='--', alpha=0.3)
198
+ st.pyplot(fig3, use_container_width=True)
199
+ else: st.info("Raw data not available for time-series.")
200
 
201
+ with t2:
202
+ st.write("**Revenue Contribution (Pareto)**")
203
+ seg_rev = df.groupby('Segment')['Monetary'].sum().sort_values(ascending=False).reset_index()
204
+ fig4, ax4 = plt.subplots(figsize=(10, 5))
205
+ sns.barplot(x='Segment', y='Monetary', data=seg_rev, palette='viridis', ax=ax4)
206
+ ax4.set_ylabel("Total Revenue (GBP)")
207
+ st.pyplot(fig4, use_container_width=True)
208
 
209
  st.markdown("---")
210