towardsinnovationlab commited on
Commit
1f4229e
·
verified ·
1 Parent(s): 1a3d435

Upload CGMM_Trial_1.py

Browse files
Files changed (1) hide show
  1. CGMM_Trial_1.py +969 -0
CGMM_Trial_1.py ADDED
@@ -0,0 +1,969 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import random
4
+ import numpy as np
5
+ import pandas as pd
6
+ import matplotlib.pyplot as plt
7
+ import matplotlib.image as mpimg
8
+ import seaborn as sns
9
+ from matplotlib.pyplot import subplots
10
+ from sklearn.model_selection import train_test_split
11
+ from sklearn.model_selection import KFold
12
+ from sklearn.metrics import mean_poisson_deviance, mean_gamma_deviance, make_scorer
13
+ from scipy.stats import ks_2samp
14
+ from sklearn.decomposition import PCA
15
+ from sklearn.preprocessing import StandardScaler
16
+ from mpl_toolkits.mplot3d import Axes3D
17
+ import umap
18
+ from sklearn.linear_model import TweedieRegressor
19
+ import shap
20
+ from sklearn.mixture import GaussianMixture
21
+ from joblib import dump
22
+ from joblib import load
23
+ import streamlit as st
24
+
25
+ import warnings
26
+ warnings.filterwarnings('ignore')
27
+
28
+
29
+ DEFAULT_RANDOM_SEED = 0
30
+ random.seed(DEFAULT_RANDOM_SEED)
31
+ os.environ['PYTHONHASHSEED'] = str(DEFAULT_RANDOM_SEED)
32
+ np.random.seed(DEFAULT_RANDOM_SEED)
33
+
34
+ st.title("Conditional Gaussian Mixture Model: Synthetic Data Generation Analysis")
35
+
36
+
37
+ def compare_real_vs_synthetic(real_df, synthetic_df, columns=None, kind='hist', bins=30, figsize=(15, 10)):
38
+ if columns is None:
39
+ columns = [col for col in real_df.columns if real_df[col].dtype != 'object']
40
+
41
+ n_cols = 2
42
+ n_rows = (len(columns) + 1) // n_cols
43
+
44
+ fig= plt.figure(figsize=figsize)
45
+
46
+ for idx, col in enumerate(columns, 1):
47
+ plt.subplot(n_rows, n_cols, idx)
48
+
49
+ if kind == 'hist':
50
+ sns.histplot(real_df[col], color='blue', label='Real', kde=False, stat='density', bins=bins, alpha=0.6)
51
+ sns.histplot(synthetic_df[col], color='red', label='Synthetic', kde=False, stat='density', bins=bins, alpha=0.6)
52
+
53
+ elif kind == 'kde':
54
+ sns.kdeplot(real_df[col], color='blue', label='Real')
55
+ sns.kdeplot(synthetic_df[col], color='red', label='Synthetic')
56
+
57
+ elif kind == 'box':
58
+ sns.boxplot(data=[real_df[col], synthetic_df[col]], palette=['blue', 'red'])
59
+ plt.xticks([0, 1], ['Real', 'Synthetic'])
60
+
61
+ else:
62
+ raise ValueError("Unsupported plot kind. Choose from 'hist', 'kde', or 'box'.")
63
+
64
+ plt.title(f"Comparison for '{col}'")
65
+ plt.legend()
66
+
67
+ plt.tight_layout()
68
+ st.pyplot(fig)
69
+
70
+
71
+ def run_glm_frequency_analysis(
72
+ X_train, X_test, model=None, clip_exposure=False, random_state=0, label="Model", var=None):
73
+ np.random.seed(0)
74
+
75
+ if clip_exposure:
76
+ X_train = X_train.copy()
77
+ X_train['Exposure'] = np.where(X_train['Exposure'] > 1, 1, X_train['Exposure'])
78
+
79
+ mask_tr = X_train['Exposure'] > 0
80
+ mask_te = X_test['Exposure'] > 0
81
+ X_train_f = X_train[mask_tr].copy()
82
+ X_test_f = X_test[mask_te].copy()
83
+
84
+ y_train = X_train_f['ClaimNb']
85
+ y_test = X_test_f['ClaimNb']
86
+ exposure_train = X_train_f['Exposure']
87
+ exposure_test = X_test_f['Exposure']
88
+
89
+ X_train_ = X_train_f.drop(['Exposure', 'ClaimNb', 'ClaimAmount'], axis=1, errors='ignore')
90
+ X_test_ = X_test_f.drop(['Exposure', 'ClaimNb', 'ClaimAmount'], axis=1, errors='ignore')
91
+
92
+ if model is None:
93
+ model = TweedieRegressor(power=1, link='log')
94
+
95
+ cv = KFold(n_splits=5)
96
+ mpd_scores = []
97
+
98
+ for fold_idx, (train_idx, val_idx) in enumerate(cv.split(X_train_)):
99
+ X_tr, X_val = X_train_.iloc[train_idx], X_train_.iloc[val_idx]
100
+ y_tr, y_val = y_train.iloc[train_idx], y_train.iloc[val_idx]
101
+ w_tr, w_val = exposure_train.iloc[train_idx], exposure_train.iloc[val_idx]
102
+
103
+ model.fit(X_tr, y_tr / w_tr, sample_weight=w_tr)
104
+ y_pred = model.predict(X_val)
105
+
106
+ score = mean_poisson_deviance(y_val / w_val, y_pred)
107
+ mpd_scores.append(score)
108
+
109
+ model.fit(X_train_, y_train / exposure_train, sample_weight=exposure_train)
110
+
111
+ pred_train = model.predict(X_train_)
112
+ pred_test = model.predict(X_test_)
113
+
114
+ mpd_train = mean_poisson_deviance(y_train / exposure_train, pred_train)
115
+ mpd_test = mean_poisson_deviance(y_test / exposure_test, pred_test)
116
+
117
+ st.write(f"Train Poisson {var} Deviance: {mpd_train:.4f}")
118
+ st.write(f"Test Poisson {var} Deviance: {mpd_test:.4f}")
119
+
120
+ return model, {
121
+ "cv_scores": mpd_scores,
122
+ "mpd_train": mpd_train,
123
+ "mpd_test": mpd_test,
124
+ "train_predictions": pred_train,
125
+ "test_predictions": pred_test
126
+ }
127
+
128
+
129
+ def run_glm_cost_analysis(X_train, X_test, is_sampled=False, verbose=True, var=None):
130
+ np.random.seed(0)
131
+
132
+ if is_sampled:
133
+ X_train = X_train.copy()
134
+ X_train['Exposure'] = np.where(X_train['Exposure'] > 1, 1, X_train['Exposure'])
135
+
136
+ X_train_co = X_train.copy()
137
+ X_test_co = X_test.copy()
138
+
139
+ X_train_co['Acost'] = np.where(X_train_co['ClaimNb'] != 0,
140
+ X_train_co['ClaimAmount'] / X_train_co['ClaimNb'], 0)
141
+ X_test_co['Acost'] = np.where(X_test_co['ClaimNb'] != 0,
142
+ X_test_co['ClaimAmount'] / X_test_co['ClaimNb'], 0)
143
+
144
+ X_train_cost = X_train_co[X_train_co['ClaimAmount'] != 0].copy()
145
+ X_test_cost = X_test_co[X_test_co['ClaimAmount'] != 0].copy()
146
+
147
+ y_train = X_train_cost['Acost']
148
+ claim_tr = X_train_cost['ClaimNb']
149
+ y_test = X_test_cost['Acost']
150
+ claim_te = X_test_cost['ClaimNb']
151
+
152
+ drop_cols = ['Acost', 'Exposure', 'ClaimAmount', 'ClaimNb']
153
+ X_train_ = X_train_cost.drop(columns=drop_cols)
154
+ X_test_ = X_test_cost.drop(columns=drop_cols)
155
+
156
+ glm_cl = TweedieRegressor(power=2, link='log')
157
+
158
+ cv = KFold(n_splits=5, shuffle=True, random_state=0)
159
+ mgd_scores = []
160
+
161
+ for fold_idx, (train_idx, val_idx) in enumerate(cv.split(X_train_)):
162
+ X_tr, X_val = X_train_.iloc[train_idx], X_train_.iloc[val_idx]
163
+ y_tr, y_val = y_train.iloc[train_idx], y_train.iloc[val_idx]
164
+ w_tr, w_val = claim_tr.iloc[train_idx], claim_tr.iloc[val_idx]
165
+
166
+ glm_cl.fit(X_tr, y_tr, sample_weight=w_tr)
167
+ y_pred_val = glm_cl.predict(X_val)
168
+ score = mean_gamma_deviance(y_val, y_pred_val)
169
+ mgd_scores.append(score)
170
+
171
+ glm_cl.fit(X_train_, y_train, sample_weight=claim_tr)
172
+
173
+ y_pred_train = glm_cl.predict(X_train_)
174
+ y_pred_test = glm_cl.predict(X_test_)
175
+
176
+ mgd_train = mean_gamma_deviance(y_train, y_pred_train)
177
+ mgd_test = mean_gamma_deviance(y_test, y_pred_test)
178
+
179
+ if verbose:
180
+ st.write(f"Train Gamma {var} Deviance: {mgd_train:.4f}")
181
+ st.write(f"Test Gamma {var} Deviance: {mgd_test:.4f}")
182
+
183
+ return {
184
+ "cv_scores": mgd_scores,
185
+ 'mgd_train': mgd_train,
186
+ 'mgd_test': mgd_test,
187
+ 'y_pred_train': y_pred_train,
188
+ 'y_pred_test': y_pred_test
189
+ }
190
+
191
+
192
+ def plot_glm_shap_importance(
193
+ X_train, X_test, y_train, sample_weight,
194
+ power: int, title: str, max_display: int = 10, figsize: tuple = (5, 5), seed: int = 0):
195
+
196
+ np.random.seed(seed)
197
+
198
+ model = TweedieRegressor(power=power, link='log')
199
+ model.fit(X_train, y_train, sample_weight=sample_weight)
200
+
201
+ masker = shap.maskers.Independent(X_train)
202
+ explainer = shap.LinearExplainer(model, masker=masker)
203
+ shap_values = explainer.shap_values(X_test)
204
+
205
+ plt.figure(figsize=figsize)
206
+ shap.summary_plot(
207
+ shap_values, features=X_test,
208
+ feature_names=X_test.columns,
209
+ plot_type='bar',
210
+ max_display=max_display,
211
+ show=False
212
+ )
213
+ plt.title(title, fontsize=12)
214
+ plt.tight_layout()
215
+ fig = plt.gcf()
216
+ st.pyplot(fig)
217
+
218
+
219
+ # ### Upload datasets
220
+
221
+ #-------------------
222
+ # DATASETS
223
+ #-------------------
224
+ df1=pd.read_csv('../dataset/ausprivauto0405.csv')
225
+ df2=pd.read_csv('../dataset/swmotorcycle.csv')
226
+ df1_synthetic=pd.read_csv('../dataset/synthetic_data_CGMM/80/d1_cgmm_80_encod.csv')
227
+ df1_synthetic = df1_synthetic.drop(columns=["Unnamed: 0"])
228
+ df2_synthetic=pd.read_csv('../dataset/synthetic_data_CGMM/80/d2_cgmm_80_encod.csv')
229
+ df2_synthetic = df2_synthetic.drop(columns=["Unnamed: 0"])
230
+
231
+
232
+
233
+ # ### dataset 1 and data handling
234
+
235
+ st.header('Dataset 1: ausprivauto0405')
236
+
237
+ df1_duplicated_rows=df1[df1.duplicated()]
238
+ df1=df1.drop_duplicates()
239
+ df1_duplicated_col=df1.columns[df1.columns.duplicated()]
240
+
241
+
242
+ # ### Encoding
243
+
244
+ df1_encod=df1.copy()
245
+ # VehAge
246
+ VehAge_group = {'old cars':'1','young cars':'2','oldest cars':'3','youngest cars':'4'}
247
+ df1_encod['VehAge'] = df1_encod['VehAge'].map(VehAge_group)
248
+ df1_encod['VehAge']= df1_encod['VehAge'].astype(int)
249
+ # DrivAge
250
+ DrivAge_group = {'young people':'1','older work. people':'2','oldest people':'3','working people':'4','old people':'5','youngest people':'6'}
251
+ df1_encod['DrivAge'] = df1_encod['DrivAge'].map(DrivAge_group)
252
+ df1_encod['DrivAge']= df1_encod['DrivAge'].astype(int)
253
+ # VehBody
254
+ VehBody_group = {'Hatchback':'1','Utility':'2','Station wagon':'3','Hardtop':'4','Panel van':'5','Sedan':'6','Truck':'7',\
255
+ 'Coupe':'8', 'Minibus':'9', 'Motorized caravan':'10', 'Bus':'11', 'Convertible':'12','Roadster':'13'}
256
+ df1_encod['VehBody'] = df1_encod['VehBody'].map(VehBody_group)
257
+ df1_encod['VehBody']= df1_encod['VehBody'].astype(int)
258
+ # Gender
259
+ Gender_group = {'Female':'0','Male':'1'}
260
+ df1_encod['Gender'] = df1_encod['Gender'].map(Gender_group)
261
+ df1_encod['Gender']= df1_encod['Gender'].astype(int)
262
+
263
+
264
+
265
+
266
+ # ### Split dataset
267
+ # Split the dataset into train/test split
268
+ X_train, X_test = train_test_split(df1_encod, test_size=0.2, random_state=0)
269
+ st.markdown(f"**Train shape:** {X_train.shape} \n**Test shape:** {X_test.shape}")
270
+
271
+
272
+ # ### Use Generate Samples Dataframe
273
+ new_samples_df=df1_synthetic.copy()
274
+
275
+ # Check consistency
276
+ st.subheader(f"Check consistency")
277
+ # Find inconsistencies
278
+ inconsistent_records = new_samples_df[
279
+ ~(((new_samples_df["ClaimNb"] == 0) & (new_samples_df["ClaimOcc"] == 0) & (new_samples_df["ClaimAmount"] == 0)) |
280
+ ((new_samples_df["ClaimNb"] > 0) & (new_samples_df["ClaimOcc"] > 0) & (new_samples_df["ClaimAmount"] > 0)))
281
+ ]
282
+
283
+ st.write(f"Number of inconsistent records on synthetic data: {len(inconsistent_records)}")
284
+ st.write(inconsistent_records.head())
285
+ st.write('Helps assess basic data fidelity by checking structural or logical violations.')
286
+
287
+
288
+ # ### Visual Comparison
289
+
290
+ # Compare selected variables using histograms
291
+ st.subheader(f"Univariate distribution comparison: real vs synthetic")
292
+ st.write('Shows how well each individual feature is mimicked by the synthetic data.')
293
+
294
+ compare_real_vs_synthetic(
295
+ real_df=X_train,
296
+ synthetic_df=df1_synthetic,
297
+ columns=['Exposure','VehBody','VehValue','ClaimOcc','ClaimNb', 'ClaimAmount', 'DrivAge', 'VehAge','Gender'],
298
+ kind='hist'
299
+ )
300
+
301
+
302
+ st.subheader(f"Correlation matrix comparison: real vs synthetic")
303
+ st.write('Evaluates preservation of feature-to-feature relationships.')
304
+
305
+ # Compute correlation matrices
306
+ corr_matrix_X_train = X_train.corr()
307
+ corr_matrix_new_samples = new_samples_df.corr()
308
+
309
+ fig=plt.figure(figsize=(30,15))
310
+
311
+ plt.subplot(1, 2, 1)
312
+ sns.heatmap(corr_matrix_X_train, square=True, annot=True, cmap='coolwarm', fmt='.2f',annot_kws={"size": 15})
313
+ plt.title('Correlation Heatmap of X_train', size=15)
314
+ plt.yticks(rotation=0,fontsize=15)
315
+ plt.xticks(rotation=90,fontsize=15)
316
+
317
+ plt.subplot(1, 2, 2)
318
+ sns.heatmap(corr_matrix_new_samples, square=True, annot=True, cmap='coolwarm', fmt='.2f',annot_kws={"size": 15})
319
+ plt.title('Correlation Heatmap of New Samples', size=15)
320
+ plt.yticks(rotation=0,fontsize=15)
321
+ plt.xticks(rotation=90,fontsize=15)
322
+ plt.tight_layout()
323
+ st.pyplot(fig)
324
+
325
+ # ### Statistical Analysis
326
+ # Kolmogorov-Smirnov test
327
+ st.subheader("Kolmogorov–Smirnov Test Results")
328
+ st.write('Quantifies the statistical distance between real and synthetic distributions.')
329
+
330
+ results = []
331
+
332
+ for column in X_train.columns:
333
+ original = X_train[column].values
334
+ generated = new_samples_df[column].values
335
+ statistic, p_value = ks_2samp(original, generated)
336
+
337
+ results.append({
338
+ "Feature": column,
339
+ "KS Statistic": statistic,
340
+ "P-value": p_value
341
+ })
342
+
343
+ results_df = pd.DataFrame(results)
344
+
345
+ def color_pval(val):
346
+ color = "red" if val < 0.05 else "green"
347
+ return f"color: {color};"
348
+
349
+ styled_df = results_df.style.applymap(color_pval, subset=["P-value"]) \
350
+ .format({"KS Statistic": "{:.4f}", "P-value": "{:.4f}"})
351
+
352
+ st.markdown("""
353
+ **Legend:**
354
+ - <span style='color:green;'>Green P-value</span>: distributions are **similar** (p ≥ 0.05)
355
+ - <span style='color:red;'>Red P-value</span>: distributions are **significantly different** (p < 0.05)
356
+ """, unsafe_allow_html=True)
357
+ st.dataframe(styled_df)
358
+
359
+
360
+ # ### PCA Analysis
361
+
362
+ st.subheader('PCA comparison')
363
+ st.write('Assesses similarity in global variance structure and major latent components.')
364
+ # Load the saved models
365
+ scaler = load('../dataset/synthetic_data_CGMM/80/scaler_pca_model_d1_cgmm_80.pkl')
366
+ pca = load('../dataset/synthetic_data_CGMM/80/pca_model_d1_cgmm_80.pkl')
367
+
368
+ def pca_visual_comparison_3d_with_saved_model(real_df, synthetic_df, scaler, pca, title_suffix=""):
369
+ assert set(real_df.columns) == set(synthetic_df.columns), "Datasets must have the same columns."
370
+
371
+ combined_df = pd.concat([real_df, synthetic_df])
372
+
373
+ combined_scaled = scaler.transform(combined_df)
374
+
375
+ pca_result = pca.transform(combined_scaled)
376
+
377
+ n_real = len(real_df)
378
+ real_pca = pca_result[:n_real]
379
+ synth_pca = pca_result[n_real:]
380
+
381
+ fig = plt.figure(figsize=(10, 8))
382
+ ax = fig.add_subplot(111, projection='3d')
383
+
384
+ ax.scatter(real_pca[:, 0], real_pca[:, 1], real_pca[:, 2],
385
+ c='blue', label='Real', s=40, alpha=0.6, edgecolor='k')
386
+
387
+ ax.scatter(synth_pca[:, 0], synth_pca[:, 1], synth_pca[:, 2],
388
+ c='red', label='Synthetic', s=40, alpha=0.6, edgecolor='k')
389
+
390
+ ax.set_title(f"3D PCA: Real vs. Synthetic {title_suffix}", fontsize=12, weight='bold')
391
+ ax.set_xlabel("PC1")
392
+ ax.set_ylabel("PC2")
393
+ ax.set_zlabel("PC3")
394
+
395
+ ax.grid(False)
396
+ ax.legend()
397
+ plt.tight_layout()
398
+ st.pyplot(fig)
399
+
400
+
401
+ pca_visual_comparison_3d_with_saved_model(X_train, df1_synthetic, scaler, pca)
402
+
403
+
404
+ # ### UMAP Analysis
405
+
406
+ st.subheader('UMAP comparison')
407
+ st.write('Examines nonlinear manifold structure and clustering behavior.')
408
+ img = mpimg.imread('../dataset/synthetic_data_CGMM/80/umap_d1_80.png')
409
+ fig=plt.figure(figsize=(10, 8))
410
+ plt.imshow(img)
411
+ plt.axis('off')
412
+ st.pyplot(fig)
413
+
414
+
415
+ # ### GLM Frequency Analysis
416
+ st.subheader('Frequency GLM Analysis')
417
+ st.write('Tests how well synthetic data preserves predictive relationships for claim frequency.')
418
+ results_frequency_1 = run_glm_frequency_analysis(X_train, X_test, label="Baseline", var='Real')
419
+ results_frequency_2 = run_glm_frequency_analysis(new_samples_df, X_test, clip_exposure=True, label="Synthetic Clipped",var= 'Synthetic')
420
+
421
+
422
+ # ### GLM Cost Analysis
423
+ st.subheader('Severity GLM Analysis')
424
+ st.write('Evaluates whether severity-related predictors behave similarly on real and synthetic data.')
425
+ results_cost_1 = run_glm_cost_analysis(X_train, X_test,var='Real')
426
+ results_cost_2 = run_glm_cost_analysis(new_samples_df, X_test, is_sampled=True,var='Synthetic')
427
+
428
+
429
+ # ### Feature Importance Analysis
430
+ # --- SHAP Feature Importance for Frequency ---
431
+ st.subheader('SHAP Feature Importance for Frequency Model')
432
+ st.write('Shows whether drivers of frequency predictions remain consistent across datasets.')
433
+ X_train_freq = X_train.drop(['Exposure', 'ClaimNb', 'ClaimAmount'], axis=1, errors='ignore')
434
+ y_train_freq = X_train['ClaimNb']
435
+ sample_weight_freq = X_train['Exposure']
436
+ X_test_freq = X_test.drop(['Exposure', 'ClaimNb', 'ClaimAmount'], axis=1, errors='ignore')
437
+ mask_train_freq = sample_weight_freq > 0
438
+ X_train_freq_filtered = X_train_freq[mask_train_freq]
439
+ y_train_freq_filtered = y_train_freq[mask_train_freq]
440
+ sample_weight_freq_filtered = sample_weight_freq[mask_train_freq]
441
+ mask_test_freq = X_test['Exposure'] > 0
442
+ X_test_freq_filtered = X_test_freq[mask_test_freq]
443
+
444
+ plot_glm_shap_importance(
445
+ X_train=X_train_freq_filtered,
446
+ X_test=X_test_freq_filtered,
447
+ y_train=y_train_freq_filtered / sample_weight_freq_filtered,
448
+ sample_weight=sample_weight_freq_filtered,
449
+ power=1,
450
+ title="SHAP Feature Importance for Frequency Model (Real Data)",
451
+ max_display=10
452
+ )
453
+
454
+ # --- SHAP Feature Importance for Frequency (Synthetic Data) ---
455
+ X_train_freq_synth = new_samples_df.drop(['Exposure', 'ClaimNb', 'ClaimAmount'], axis=1, errors='ignore')
456
+ y_train_freq_synth = new_samples_df['ClaimNb']
457
+ sample_weight_freq_synth = new_samples_df['Exposure']
458
+ X_test_freq = X_test.drop(['Exposure', 'ClaimNb', 'ClaimAmount'], axis=1, errors='ignore')
459
+ mask_train_freq_synth = sample_weight_freq_synth > 0
460
+ X_train_freq_synth_filtered = X_train_freq_synth[mask_train_freq_synth]
461
+ y_train_freq_synth_filtered = y_train_freq_synth[mask_train_freq_synth]
462
+ sample_weight_freq_synth_filtered = sample_weight_freq_synth[mask_train_freq_synth]
463
+ mask_test_freq = X_test['Exposure'] > 0
464
+ X_test_freq_filtered = X_test_freq[mask_test_freq]
465
+
466
+ plot_glm_shap_importance(
467
+ X_train=X_train_freq_synth_filtered,
468
+ X_test=X_test_freq_filtered,
469
+ y_train=y_train_freq_synth_filtered / sample_weight_freq_synth_filtered,
470
+ sample_weight=sample_weight_freq_synth_filtered,
471
+ power=1,
472
+ title="SHAP Feature Importance for Frequency Model (Synthetic Data)",
473
+ max_display=10
474
+ )
475
+
476
+ # --- SHAP Feature Importance for Severity ---
477
+ st.subheader('SHAP Feature Importance for Severity Model')
478
+ st.write('Assesses stability of model explanations for severity outcomes.')
479
+ X_train_cost_prep = X_train[X_train['ClaimAmount'] != 0].copy()
480
+ X_test_cost_prep = X_test[X_test['ClaimAmount'] != 0].copy()
481
+
482
+ X_train_sev = X_train_cost_prep.drop(columns=['Acost', 'Exposure', 'ClaimAmount', 'ClaimNb'], errors='ignore')
483
+ y_train_sev = X_train_cost_prep['ClaimAmount'] / X_train_cost_prep['ClaimNb']
484
+ sample_weight_sev = X_train_cost_prep['ClaimNb']
485
+ X_test_sev = X_test_cost_prep.drop(columns=['Acost', 'Exposure', 'ClaimAmount', 'ClaimNb'], errors='ignore')
486
+
487
+ plot_glm_shap_importance(
488
+ X_train=X_train_sev,
489
+ X_test=X_test_sev,
490
+ y_train=y_train_sev,
491
+ sample_weight=sample_weight_sev,
492
+ power=2,
493
+ title="SHAP Feature Importance for Severity Model (Real Data)",
494
+ max_display=10
495
+ )
496
+
497
+
498
+ # --- SHAP Feature Importance for Severity (Synthetic Data) ---
499
+ X_train_cost_prep_synth = new_samples_df[new_samples_df['ClaimAmount'] != 0].copy()
500
+ X_test_cost_prep_synth = X_test[X_test['ClaimAmount'] != 0].copy() # Keep using real test data for explanation
501
+ X_train_sev_synth = X_train_cost_prep_synth.drop(columns=['Acost', 'Exposure', 'ClaimAmount', 'ClaimNb'], errors='ignore')
502
+ y_train_sev_synth = X_train_cost_prep_synth['ClaimAmount'] / X_train_cost_prep_synth['ClaimNb']
503
+ sample_weight_sev_synth = X_train_cost_prep_synth['ClaimNb'] # Number of claims is the weight for severity
504
+ X_test_sev_synth = X_test_cost_prep_synth.drop(columns=['Acost', 'Exposure', 'ClaimAmount', 'ClaimNb'], errors='ignore')
505
+
506
+
507
+ plot_glm_shap_importance(
508
+ X_train=X_train_sev_synth,
509
+ X_test=X_test_sev_synth,
510
+ y_train=y_train_sev_synth,
511
+ sample_weight=sample_weight_sev_synth,
512
+ power=2,
513
+ title="SHAP Feature Importance for Severity Model (Synthetic Data)",
514
+ max_display=10
515
+ )
516
+
517
+
518
+ # ### dataset 2 and data handling
519
+ st.header('Dataset 2: swmotorcycle')
520
+
521
+ df2_duplicated_rows=df2[df2.duplicated()]
522
+ df2=df2.drop_duplicates()
523
+ df2_duplicated_col=df2.columns[df2.columns.duplicated()]
524
+
525
+
526
+ # add ClaimOcc feature
527
+ df_2 = df2.copy()
528
+ df_2['ClaimOcc'] = np.where(df_2['ClaimNb'] > 0, 1, 0)
529
+ # Feature transformation
530
+ df_2['Exposure'] = df_2['Exposure'].clip(upper=1)
531
+ df_2['VehAge'] = df_2['VehAge'].clip(upper=20)
532
+
533
+
534
+ # ### Encoding
535
+ df2_encod=df_2.copy()
536
+ # RiskClass
537
+ RiskClass_group = {'EV ratio 13-15':'1','EV ratio 20-24':'2','EV ratio 9-12':'3','EV ratio <5':'4','EV ratio 6-8':'5',\
538
+ 'EV ratio 16-19':'6','EV ratio >25':'7'}
539
+ df2_encod['RiskClass'] = df2_encod['RiskClass'].map(RiskClass_group)
540
+ df2_encod['RiskClass']= df2_encod['RiskClass'].astype(int)
541
+ # BonusClass
542
+ BonusClass_group = {'BM1':'1','BM2':'2','BM3':'3','BM4':'4','BM5':'5','BM6':'6','BM7':'7'}
543
+ df2_encod['BonusClass'] = df2_encod['BonusClass'].map(BonusClass_group)
544
+ df2_encod['BonusClass']= df2_encod['BonusClass'].astype(int)
545
+ # Area
546
+ Area_group = {"Central parts of Sweden's three largest cities":'1','Lesser towns except Gotland; Northern towns':'2',\
547
+ 'Small towns; countryside except Gotland; Northern towns':'3','Suburbs; middle-sized cities':'4',\
548
+ 'Northern countryside':'5','Northern towns':'6',"Gotland (Sweden's largest island)":'7'}
549
+ df2_encod['Area'] = df2_encod['Area'].map(Area_group)
550
+ df2_encod['Area']= df2_encod['Area'].astype(int)
551
+ # Gender
552
+ Gender_group = {'Female':'0','Male':'1'}
553
+ df2_encod['Gender'] = df2_encod['Gender'].map(Gender_group)
554
+ df2_encod['Gender']= df2_encod['Gender'].astype(int)
555
+
556
+
557
+
558
+
559
+ # ### Split dataset
560
+ # Split the dataset into train/test split
561
+ X_train, X_test = train_test_split(df2_encod, test_size=0.2, random_state=0)
562
+ st.markdown(f"**Train shape:** {X_train.shape} \n**Test shape:** {X_test.shape}")
563
+
564
+
565
+ # ### Use Generate Samples Dataframe
566
+ new_samples_df=df2_synthetic.copy()
567
+
568
+ # Check consistency
569
+ st.subheader(f"Check consistency")
570
+ # Find inconsistencies
571
+ inconsistent_records = new_samples_df[
572
+ ~(((new_samples_df["ClaimNb"] == 0) & (new_samples_df["ClaimOcc"] == 0) & (new_samples_df["ClaimAmount"] == 0)) |
573
+ ((new_samples_df["ClaimNb"] > 0) & (new_samples_df["ClaimOcc"] > 0) & (new_samples_df["ClaimAmount"] > 0)))
574
+ ]
575
+
576
+ st.write(f"Number of inconsistent records on synthetic data: {len(inconsistent_records)}")
577
+ st.write(inconsistent_records.head()) # Show a few inconsistent rows
578
+ st.write('Helps assess basic data fidelity by checking structural or logical violations.')
579
+
580
+
581
+ # ### Visual Comparison
582
+ st.subheader('Univariate distribution comparison: real vs synthetic')
583
+ st.write('Shows how well each individual feature is mimicked by the synthetic data.')
584
+
585
+ # Compare selected variables using histograms
586
+ compare_real_vs_synthetic(
587
+ real_df=X_train,
588
+ synthetic_df=df2_synthetic,
589
+ columns=['Exposure','VehAge','ClaimOcc','ClaimNb', 'ClaimAmount', 'RiskClass', 'Area','BonusClass','Gender'],
590
+ kind='hist'
591
+ )
592
+
593
+ st.subheader('Correlation matrix comparison: real vs synthetic')
594
+ st.write('Evaluates preservation of feature-to-feature relationships.')
595
+
596
+ # Compute correlation matrices
597
+ corr_matrix_X_train = X_train.corr()
598
+ corr_matrix_new_samples = new_samples_df.corr()
599
+
600
+ fig=plt.figure(figsize=(30,15))
601
+
602
+ plt.subplot(1, 2, 1)
603
+ sns.heatmap(corr_matrix_X_train, square=True, annot=True, cmap='coolwarm', fmt='.2f',annot_kws={"size": 15})
604
+ plt.title('Correlation Heatmap of X_train', size=15)
605
+ plt.yticks(rotation=0,fontsize=15)
606
+ plt.xticks(rotation=90,fontsize=15)
607
+
608
+ plt.subplot(1, 2, 2)
609
+ sns.heatmap(corr_matrix_new_samples, square=True, annot=True, cmap='coolwarm', fmt='.2f',annot_kws={"size": 15})
610
+ plt.title('Correlation Heatmap of New Samples', size=15)
611
+ plt.yticks(rotation=0,fontsize=15)
612
+ plt.xticks(rotation=90,fontsize=15)
613
+ plt.tight_layout()
614
+ st.pyplot(fig)
615
+
616
+
617
+ # ### Statistical Analysis
618
+ # Kolmogorov-Smirnov test
619
+ st.subheader('Kolmogorov–Smirnov Test Results')
620
+ st.write('Quantifies the statistical distance between real and synthetic distributions.')
621
+
622
+
623
+ results = []
624
+
625
+ for column in X_train.columns:
626
+ original = X_train[column].values
627
+ generated = new_samples_df[column].values
628
+ statistic, p_value = ks_2samp(original, generated)
629
+
630
+ results.append({
631
+ "Feature": column,
632
+ "KS Statistic": statistic,
633
+ "P-value": p_value
634
+ })
635
+
636
+ results_df = pd.DataFrame(results)
637
+
638
+ def color_pval(val):
639
+ color = "red" if val < 0.05 else "green"
640
+ return f"color: {color};"
641
+
642
+ styled_df = results_df.style.applymap(color_pval, subset=["P-value"]) \
643
+ .format({"KS Statistic": "{:.4f}", "P-value": "{:.4f}"})
644
+
645
+ st.markdown("""
646
+ **Legend:**
647
+ - <span style='color:green;'>Green P-value</span>: distributions are **similar** (p ≥ 0.05)
648
+ - <span style='color:red;'>Red P-value</span>: distributions are **significantly different** (p < 0.05)
649
+ """, unsafe_allow_html=True)
650
+ st.dataframe(styled_df)
651
+
652
+
653
+ # ### PCA Analysis
654
+ st.subheader('PCA comparison')
655
+ st.write('Assesses similarity in global variance structure and major latent components.')
656
+ # Load the saved models
657
+ scaler = load('../dataset/synthetic_data_CGMM/80/scaler_pca_model_d2_cgmm_80.pkl')
658
+ pca = load('../dataset/synthetic_data_CGMM/80/pca_model_d2_cgmm_80.pkl')
659
+
660
+ def pca_visual_comparison_3d_with_saved_model(real_df, synthetic_df, scaler, pca, title_suffix=""):
661
+ assert set(real_df.columns) == set(synthetic_df.columns), "Datasets must have the same columns."
662
+
663
+ combined_df = pd.concat([real_df, synthetic_df])
664
+ combined_scaled = scaler.transform(combined_df)
665
+ pca_result = pca.transform(combined_scaled)
666
+ n_real = len(real_df)
667
+ real_pca = pca_result[:n_real]
668
+ synth_pca = pca_result[n_real:]
669
+ fig = plt.figure(figsize=(10, 8))
670
+ ax = fig.add_subplot(111, projection='3d')
671
+ ax.scatter(real_pca[:, 0], real_pca[:, 1], real_pca[:, 2],
672
+ c='blue', label='Real', s=40, alpha=0.6, edgecolor='k')
673
+
674
+ ax.scatter(synth_pca[:, 0], synth_pca[:, 1], synth_pca[:, 2],
675
+ c='red', label='Synthetic', s=40, alpha=0.6, edgecolor='k')
676
+
677
+ ax.set_title(f"3D PCA: Real vs. Synthetic {title_suffix}", fontsize=12, weight='bold')
678
+ ax.set_xlabel("PC1")
679
+ ax.set_ylabel("PC2")
680
+ ax.set_zlabel("PC3")
681
+
682
+ ax.grid(False)
683
+ ax.legend()
684
+ plt.tight_layout()
685
+ st.pyplot(fig)
686
+
687
+ pca_visual_comparison_3d_with_saved_model(X_train, df2_synthetic, scaler, pca)
688
+
689
+
690
+ # ### UMAP Analysis
691
+ st.subheader('UMAP comparison')
692
+ st.write('Examines nonlinear manifold structure and clustering behavior.')
693
+ img = mpimg.imread('../dataset/synthetic_data_CGMM/80/umap_d2_80.png')
694
+ fig=plt.figure(figsize=(10, 8))
695
+ plt.imshow(img)
696
+ plt.axis('off')
697
+ st.pyplot(fig)
698
+
699
+
700
+ # ### GLM Frequency Analysis
701
+ st.subheader('Frequency GLM Analysis')
702
+ st.write('Tests how well synthetic data preserves predictive relationships for claim frequency.')
703
+ results_frequency_3 = run_glm_frequency_analysis(X_train, X_test, label="Baseline", var='Real')
704
+ results_frequency_4 = run_glm_frequency_analysis(new_samples_df, X_test, clip_exposure=True, label="Synthetic Clipped", var='Synthetic')
705
+
706
+
707
+ # ### GLM Cost Analysis
708
+ st.subheader('Severity GLM Analysis')
709
+ st.write('Evaluates whether severity-related predictors behave similarly on real and synthetic data.')
710
+ results_cost_3 = run_glm_cost_analysis(X_train, X_test, var='Real')
711
+ results_cost_4 = run_glm_cost_analysis(new_samples_df, X_test, is_sampled=True, var= 'Synthetic')
712
+
713
+
714
+ # ### Feature Importance Analysis
715
+
716
+ # --- SHAP Feature Importance for Frequency ---
717
+ st.subheader('SHAP Feature Importance for Frequency Model')
718
+ st.write('Shows whether drivers of frequency predictions remain consistent across datasets.')
719
+ X_train_freq = X_train.drop(['Exposure', 'ClaimNb', 'ClaimAmount'], axis=1, errors='ignore')
720
+ y_train_freq = X_train['ClaimNb']
721
+ sample_weight_freq = X_train['Exposure']
722
+ X_test_freq = X_test.drop(['Exposure', 'ClaimNb', 'ClaimAmount'], axis=1, errors='ignore')
723
+ mask_train_freq = sample_weight_freq > 0
724
+ X_train_freq_filtered = X_train_freq[mask_train_freq]
725
+ y_train_freq_filtered = y_train_freq[mask_train_freq]
726
+ sample_weight_freq_filtered = sample_weight_freq[mask_train_freq]
727
+ mask_test_freq = X_test['Exposure'] > 0
728
+ X_test_freq_filtered = X_test_freq[mask_test_freq]
729
+
730
+ plot_glm_shap_importance(
731
+ X_train=X_train_freq_filtered,
732
+ X_test=X_test_freq_filtered,
733
+ y_train=y_train_freq_filtered / sample_weight_freq_filtered,
734
+ sample_weight=sample_weight_freq_filtered,
735
+ power=1,
736
+ title="SHAP Feature Importance for Frequency Model (Real Data)",
737
+ max_display=10
738
+ )
739
+
740
+ # --- SHAP Feature Importance for Frequency (Synthetic Data) ---
741
+ X_train_freq_synth = new_samples_df.drop(['Exposure', 'ClaimNb', 'ClaimAmount'], axis=1, errors='ignore')
742
+ y_train_freq_synth = new_samples_df['ClaimNb']
743
+ sample_weight_freq_synth = new_samples_df['Exposure']
744
+ X_test_freq = X_test.drop(['Exposure', 'ClaimNb', 'ClaimAmount'], axis=1, errors='ignore')
745
+ mask_train_freq_synth = sample_weight_freq_synth > 0
746
+ X_train_freq_synth_filtered = X_train_freq_synth[mask_train_freq_synth]
747
+ y_train_freq_synth_filtered = y_train_freq_synth[mask_train_freq_synth]
748
+ sample_weight_freq_synth_filtered = sample_weight_freq_synth[mask_train_freq_synth]
749
+ mask_test_freq = X_test['Exposure'] > 0
750
+ X_test_freq_filtered = X_test_freq[mask_test_freq]
751
+
752
+ plot_glm_shap_importance(
753
+ X_train=X_train_freq_synth_filtered,
754
+ X_test=X_test_freq_filtered,
755
+ y_train=y_train_freq_synth_filtered / sample_weight_freq_synth_filtered,
756
+ sample_weight=sample_weight_freq_synth_filtered,
757
+ power=1,
758
+ title="SHAP Feature Importance for Frequency Model (Synthetic Data)",
759
+ max_display=10
760
+ )
761
+
762
+ # --- SHAP Feature Importance for Severity ---
763
+ st.subheader('SHAP Feature Importance for Severity Model')
764
+ st.write('Assesses stability of model explanations for severity outcomes')
765
+ X_train_cost_prep = X_train[X_train['ClaimAmount'] != 0].copy()
766
+ X_test_cost_prep = X_test[X_test['ClaimAmount'] != 0].copy()
767
+
768
+ X_train_sev = X_train_cost_prep.drop(columns=['Acost', 'Exposure', 'ClaimAmount', 'ClaimNb'], errors='ignore')
769
+ y_train_sev = X_train_cost_prep['ClaimAmount'] / X_train_cost_prep['ClaimNb']
770
+ sample_weight_sev = X_train_cost_prep['ClaimNb']
771
+ X_test_sev = X_test_cost_prep.drop(columns=['Acost', 'Exposure', 'ClaimAmount', 'ClaimNb'], errors='ignore')
772
+
773
+ plot_glm_shap_importance(
774
+ X_train=X_train_sev,
775
+ X_test=X_test_sev,
776
+ y_train=y_train_sev,
777
+ sample_weight=sample_weight_sev,
778
+ power=2,
779
+ title="SHAP Feature Importance for Severity Model (Real Data)",
780
+ max_display=10
781
+ )
782
+
783
+ # --- SHAP Feature Importance for Severity (Synthetic Data) ---
784
+ X_train_cost_prep_synth = new_samples_df[new_samples_df['ClaimAmount'] != 0].copy()
785
+ X_test_cost_prep_synth = X_test[X_test['ClaimAmount'] != 0].copy() # Keep using real test data for explanation
786
+ X_train_sev_synth = X_train_cost_prep_synth.drop(columns=['Acost', 'Exposure', 'ClaimAmount', 'ClaimNb'], errors='ignore')
787
+ y_train_sev_synth = X_train_cost_prep_synth['ClaimAmount'] / X_train_cost_prep_synth['ClaimNb']
788
+ sample_weight_sev_synth = X_train_cost_prep_synth['ClaimNb'] # Number of claims is the weight for severity
789
+ X_test_sev_synth = X_test_cost_prep_synth.drop(columns=['Acost', 'Exposure', 'ClaimAmount', 'ClaimNb'], errors='ignore')
790
+
791
+ plot_glm_shap_importance(
792
+ X_train=X_train_sev_synth,
793
+ X_test=X_test_sev_synth,
794
+ y_train=y_train_sev_synth,
795
+ sample_weight=sample_weight_sev_synth,
796
+ power=2,
797
+ title="SHAP Feature Importance for Severity Model (Synthetic Data)",
798
+ max_display=10
799
+ )
800
+
801
+
802
+ # ### Results
803
+ st.subheader('Overall results')
804
+ # The dictionary dataset 1
805
+ metrics_dict_1 = results_frequency_1[1]
806
+ mpd_train_1 = metrics_dict_1['mpd_train']
807
+ mpd_test_1 = metrics_dict_1['mpd_test']
808
+
809
+
810
+ # The dictionary synthetic dataset 1
811
+ metrics_dict_2 = results_frequency_2[1]
812
+ mpd_train_2 = metrics_dict_2['mpd_train']
813
+ mpd_test_2 = metrics_dict_2['mpd_test']
814
+
815
+
816
+
817
+ # The dictionary dataset 2
818
+ metrics_dict_3 = results_frequency_3[1]
819
+ mpd_train_3 = metrics_dict_3['mpd_train']
820
+ mpd_test_3 = metrics_dict_3['mpd_test']
821
+
822
+
823
+
824
+ # The dictionary synthetic dataset 2
825
+ metrics_dict_4 = results_frequency_4[1]
826
+ mpd_train_4 = metrics_dict_4['mpd_train']
827
+ mpd_test_4 = metrics_dict_4['mpd_test']
828
+
829
+
830
+
831
+ # The dictionary dataset 1
832
+ mgd_train_1 = results_cost_1['mgd_train']
833
+ mgd_test_1 = results_cost_1['mgd_test']
834
+
835
+
836
+
837
+ # The dictionary synthetic dataset 1
838
+ mgd_train_2 = results_cost_2['mgd_train']
839
+ mgd_test_2 = results_cost_2['mgd_test']
840
+
841
+
842
+
843
+ # The dictionary dataset 2
844
+ mgd_train_3 = results_cost_3['mgd_train']
845
+ mgd_test_3 = results_cost_3['mgd_test']
846
+
847
+
848
+
849
+ # The dictionary synthetic dataset 2
850
+ mgd_train_4 = results_cost_4['mgd_train']
851
+ mgd_test_4 = results_cost_4['mgd_test']
852
+
853
+
854
+
855
+ # Create the DataFrame
856
+ results_df1 = {
857
+ 'mpd_train': mpd_train_1,
858
+ 'mpd_test': mpd_test_1,
859
+ 'mgd_train': mgd_train_1,
860
+ 'mgd_test': mgd_test_1,
861
+ }
862
+ results_df2 = {
863
+ 'mpd_train': mpd_train_2,
864
+ 'mpd_test': mpd_test_2,
865
+ 'mgd_train': mgd_train_2,
866
+ 'mgd_test': mgd_test_2,
867
+ }
868
+ results_df3 = {
869
+ 'mpd_train': mpd_train_3,
870
+ 'mpd_test': mpd_test_3,
871
+ 'mgd_train': mgd_train_3,
872
+ 'mgd_test': mgd_test_3,
873
+ }
874
+ results_df4 = {
875
+ 'mpd_train': mpd_train_4,
876
+ 'mpd_test': mpd_test_4,
877
+ 'mgd_train': mgd_train_4,
878
+ 'mgd_test': mgd_test_4,
879
+ }
880
+ d1=pd.DataFrame(results_df1, index=['dataset 1'])
881
+ d2=pd.DataFrame(results_df2, index=['synthetic dataset 1'])
882
+ d3=pd.DataFrame(results_df3, index=['dataset 2'])
883
+ d4=pd.DataFrame(results_df4, index=['synthetic dataset 2'])
884
+ df_tot= pd.concat([d1,d2,d3,d4])
885
+ st.dataframe(df_tot)
886
+ st.write('These results demonstrate excellent synthetic data quality: \
887
+ the mean poisson deviance (mpd) and mean gamma deviance (mgd) metrics are \
888
+ nearly identical between real and synthetic datasets for both dataset 1 and dataset 2. \
889
+ This suggests the synthetic data accurately preserves the statistical properties and \
890
+ predictive complexity of the original data')
891
+
892
+
893
+ # barplot comparison
894
+ fig, ax = plt.subplots(figsize=(9, 5))
895
+ df_tot.plot(kind='bar', ax=ax)
896
+ ax.set_title('Comparison of MPD and MGD Metrics')
897
+ ax.set_ylabel('Value')
898
+ ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
899
+ ax.legend(title='Metric')
900
+ for container in ax.containers:
901
+ labels = ax.bar_label(container, fmt='%.2f', label_type='edge', padding=2)
902
+ for label in labels:
903
+ label.set_fontsize(8)
904
+
905
+ plt.tight_layout()
906
+ st.pyplot(fig)
907
+ st.write('This visualization confirms the strong fidelity of the synthetic data. \
908
+ The first synthetic dataset pefroms little better on frequency')
909
+
910
+
911
+ # MPD: Train vs Test Comparison
912
+ fig, axes = plt.subplots(1, 2, figsize=(15, 6))
913
+
914
+ # --- MPD Comparison ---
915
+ mpd_data = df_tot[['mpd_train', 'mpd_test']]
916
+ mpd_data.plot(kind='bar', ax=axes[0], color=['#2ecc71', '#e74c3c'])
917
+
918
+ axes[0].set_title('Mean Poisson Deviance: Train vs Test', fontsize=16, fontweight='bold')
919
+ axes[0].set_ylabel('MPD Value', fontsize=14)
920
+ axes[0].set_xlabel('Dataset', fontsize=14)
921
+ axes[0].legend(['Train', 'Test'], fontsize=10)
922
+
923
+ # Larger tick labels
924
+ axes[0].tick_params(axis='x', labelsize=12, rotation=45)
925
+ axes[0].tick_params(axis='y', labelsize=12)
926
+
927
+ axes[0].grid(axis='y', alpha=0.3)
928
+ for container in axes[0].containers:
929
+ axes[0].bar_label(container, fmt='%.3f', fontsize=15)
930
+
931
+ # --- MGD Comparison ---
932
+ mgd_data = df_tot[['mgd_train', 'mgd_test']]
933
+ mgd_data.plot(kind='bar', ax=axes[1], color=['#3498db', '#f39c12'])
934
+
935
+ axes[1].set_title('Mean Gamma Deviance: Train vs Test', fontsize=16, fontweight='bold')
936
+ axes[1].set_ylabel('MGD Value', fontsize=14)
937
+ axes[1].set_xlabel('Dataset', fontsize=14)
938
+ axes[1].legend(['Train', 'Test'], fontsize=10)
939
+
940
+ # Larger tick labels
941
+ axes[1].tick_params(axis='x', labelsize=12, rotation=45)
942
+ axes[1].tick_params(axis='y', labelsize=12)
943
+
944
+ axes[1].grid(axis='y', alpha=0.3)
945
+ for container in axes[1].containers:
946
+ axes[1].bar_label(container, fmt='%.3f', fontsize=15)
947
+
948
+ plt.tight_layout()
949
+ st.pyplot(fig)
950
+ st.write('This comparison reveals excellent synthetic data quality with minimal \
951
+ train-test gaps. The synthetic generation process maintains distributional properties, \
952
+ and also model generalization characteristics.')
953
+
954
+ # Create a heatmap
955
+ fig, ax = plt.subplots(figsize=(10, 6))
956
+
957
+ sns.heatmap(df_tot, annot=True, fmt='.3f', cmap='RdYlGn_r',
958
+ linewidths=0.5, ax=ax, cbar_kws={'label': 'Deviance Value'})
959
+ ax.set_title('Performance Heatmap: All Metrics Across Datasets', fontsize=15, fontweight='bold', pad=20)
960
+ ax.set_xlabel('Metrics')
961
+ ax.set_ylabel('Datasets')
962
+
963
+ plt.tight_layout()
964
+ st.pyplot(fig)
965
+ st.write('The heatmap with the near-identical color patterns between real and synthetic versions \
966
+ of each dataset confirm excellent replication fidelity. Dataset 2 shows dramatically \
967
+ lower MPD values (green, ~0.28-0.44) compared to dataset 1 (orange-red, ~1.43-1.75), while MGD \
968
+ values remain similarly high across both, suggesting dataset 2 represents a different \
969
+ modeling challenge that the synthetic generation process successfully preserves.')