likelihood 1.5.7__py3-none-any.whl → 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,810 @@
1
+ import random
2
+ import warnings
3
+ from typing import List
4
+
5
+ import matplotlib
6
+ import matplotlib.colors as mcolors
7
+ import matplotlib.pyplot as plt
8
+ import networkx as nx
9
+ import numpy as np
10
+ import pandas as pd
11
+ import tensorflow as tf
12
+ from IPython.display import HTML, display
13
+ from matplotlib import cm
14
+ from matplotlib.colors import Normalize
15
+ from pandas.core.frame import DataFrame
16
+ from pandas.plotting import radviz
17
+ from sklearn.manifold import TSNE
18
+ from tensorflow.keras.layers import InputLayer
19
+
20
+ from likelihood.models.deep._autoencoders import AutoClassifier, sampling
21
+
22
+
23
+ class GetInsights:
24
+ """
25
+ A class to analyze the output of a neural network model, including visualizations
26
+ of the weights, t-SNE representation, and feature statistics.
27
+
28
+ Parameters
29
+ ----------
30
+ model : `AutoClassifier`
31
+ The trained model to analyze.
32
+ inputs : `np.ndarray`
33
+ The input data for analysis.
34
+ """
35
+
36
+ def __init__(self, model: AutoClassifier, inputs: np.ndarray) -> None:
37
+ """
38
+ Initializes the GetInsights class.
39
+
40
+ Parameters
41
+ ----------
42
+ model : `AutoClassifier`
43
+ The trained model to analyze.
44
+ inputs : `np.ndarray`
45
+ The input data for analysis.
46
+ """
47
+ self.inputs = inputs
48
+ self.model = model
49
+
50
+ self.encoder_layer = (
51
+ self.model._encoder.layers[1]
52
+ if isinstance(self.model._encoder.layers[0], InputLayer)
53
+ else self.model._encoder.layers[0]
54
+ )
55
+ self.decoder_layer = (
56
+ self.model._decoder.layers[1]
57
+ if isinstance(self.model._decoder.layers[0], InputLayer)
58
+ else self.model._decoder.layers[0]
59
+ )
60
+
61
+ self.encoder_weights = self.encoder_layer.get_weights()[0]
62
+ self.decoder_weights = self.decoder_layer.get_weights()[0]
63
+
64
+ self.sorted_names = self._generate_sorted_color_names()
65
+
66
+ def _generate_sorted_color_names(self) -> list:
67
+ """
68
+ Generate sorted color names based on their HSV values.
69
+
70
+ Parameters
71
+ ----------
72
+ `None`
73
+
74
+ Returns
75
+ -------
76
+ `list` : Sorted color names.
77
+ """
78
+ colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
79
+ by_hsv = sorted(
80
+ (tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
81
+ for name, color in colors.items()
82
+ )
83
+ sorted_names = [name for hsv, name in by_hsv if hsv[1] > 0.4 and hsv[2] >= 0.4]
84
+ random.shuffle(sorted_names)
85
+ return sorted_names
86
+
87
+ def render_html_report(
88
+ self,
89
+ frac: float = 0.2,
90
+ top_k: int = 5,
91
+ threshold_factor: float = 1.0,
92
+ max_rows: int = 5,
93
+ **kwargs,
94
+ ) -> None:
95
+ """
96
+ Generate and display an embedded HTML report in a Jupyter Notebook cell.
97
+ """
98
+ display(HTML("<h2 style='margin-top:20px;'>📊 Predictor Analysis</h2>"))
99
+ display(
100
+ HTML(
101
+ "<p>This section visualizes how the model predicts the data. "
102
+ "You will see original inputs, reconstructed outputs, and analyses such as t-SNE "
103
+ "that reduce dimensionality to visualize latent space clustering.</p>"
104
+ )
105
+ )
106
+ stats_df = self.predictor_analyzer(frac=frac, **kwargs)
107
+
108
+ display(HTML("<h2 style='margin-top:30px;'>🔁 Encoder-Decoder Graph</h2>"))
109
+ display(
110
+ HTML(
111
+ "<p>This visualization displays the connections between layers in the encoder and decoder. "
112
+ "Edges with the strongest weights are highlighted to emphasize influential features "
113
+ "in the model's transformation.</p>"
114
+ )
115
+ )
116
+ if not self.model._encoder.name.startswith("vae"):
117
+ self.viz_encoder_decoder_graphs(threshold_factor=threshold_factor, top_k=top_k)
118
+
119
+ display(HTML("<h2 style='margin-top:30px;'>🧠 Classifier Layer Graphs</h2>"))
120
+ display(
121
+ HTML(
122
+ "<p>This visualization shows how features propagate through each dense layer in the classifier. "
123
+ "Only the strongest weighted connections are shown to highlight influential paths through the network.</p>"
124
+ )
125
+ )
126
+ self.viz_classifier_graphs(threshold_factor=threshold_factor, top_k=top_k)
127
+
128
+ display(HTML("<h2 style='margin-top:30px;'>📈 Statistical Summary</h2>"))
129
+ display(
130
+ HTML(
131
+ "<p>This table summarizes feature statistics grouped by predicted classes, "
132
+ "including means, standard deviations, and modes, providing insight into "
133
+ "feature distributions across different classes.</p>"
134
+ )
135
+ )
136
+
137
+ if max_rows is not None and max_rows > 0:
138
+ stats_to_display = stats_df.head(max_rows)
139
+ else:
140
+ stats_to_display = stats_df
141
+
142
+ display(
143
+ stats_to_display.style.set_table_attributes(
144
+ "style='display:inline;border-collapse:collapse;'"
145
+ )
146
+ .set_caption("Feature Summary per Class")
147
+ .set_properties(
148
+ **{
149
+ "border": "1px solid #ddd",
150
+ "padding": "8px",
151
+ "text-align": "center",
152
+ }
153
+ )
154
+ )
155
+
156
+ display(
157
+ HTML(
158
+ "<p style='color: gray; margin-top:30px;'>Report generated with "
159
+ "<code>GetInsights</code> class. For detailed customization, extend "
160
+ "<code>render_html_report</code>.</p>"
161
+ )
162
+ )
163
+
164
+ def viz_classifier_graphs(self, threshold_factor=1.0, top_k=5, save_path=None):
165
+ """
166
+ Visualize all Dense layers in self.model.classifier as a single directed graph,
167
+ connecting each Dense layer to the next.
168
+ """
169
+
170
+ def get_top_k_edges(weights, src_prefix, dst_prefix, k):
171
+ flat_weights = np.abs(weights.flatten())
172
+ indices = np.argpartition(flat_weights, -k)[-k:]
173
+ top_k_flat_indices = indices[np.argsort(-flat_weights[indices])]
174
+ top_k_edges = []
175
+
176
+ for flat_index in top_k_flat_indices:
177
+ i, j = np.unravel_index(flat_index, weights.shape)
178
+ top_k_edges.append((f"{src_prefix}_{i}", f"{dst_prefix}_{j}", weights[i, j]))
179
+ return top_k_edges
180
+
181
+ def add_dense_layer_edges(G, weights, layer_idx, threshold_factor, top_k):
182
+ src_prefix = f"L{layer_idx}"
183
+ dst_prefix = f"L{layer_idx + 1}"
184
+ input_nodes = [f"{src_prefix}_{i}" for i in range(weights.shape[0])]
185
+ output_nodes = [f"{dst_prefix}_{j}" for j in range(weights.shape[1])]
186
+
187
+ G.add_nodes_from(input_nodes + output_nodes)
188
+
189
+ abs_weights = np.abs(weights)
190
+ threshold = threshold_factor * np.mean(abs_weights)
191
+ top_k_edges = get_top_k_edges(weights, src_prefix, dst_prefix, top_k)
192
+ top_k_set = set((u, v) for u, v, _ in top_k_edges)
193
+
194
+ for i, src in enumerate(input_nodes):
195
+ for j, dst in enumerate(output_nodes):
196
+ w = weights[i, j]
197
+ if abs(w) > threshold:
198
+ G.add_edge(src, dst, weight=w, highlight=(src, dst) in top_k_set)
199
+
200
+ def compute_layout(G):
201
+ pos = {}
202
+ layer_nodes = {}
203
+
204
+ for node in G.nodes():
205
+ layer_idx = int(node.split("_")[0][1:])
206
+ layer_nodes.setdefault(layer_idx, []).append(node)
207
+
208
+ for layer_idx, nodes in sorted(layer_nodes.items()):
209
+ y_positions = np.linspace(1, -1, len(nodes))
210
+ for y, node in zip(y_positions, nodes):
211
+ pos[node] = (layer_idx * 2, y)
212
+
213
+ return pos
214
+
215
+ def draw_graph(G, pos, title, save_path=None):
216
+ weights = [abs(G[u][v]["weight"]) for u, v in G.edges()]
217
+ if not weights:
218
+ print("No edges to draw.")
219
+ return
220
+
221
+ norm = Normalize(vmin=min(weights), vmax=max(weights))
222
+ cmap = cm.get_cmap("coolwarm")
223
+
224
+ edge_colors = [cmap(norm(G[u][v]["weight"])) for u, v in G.edges()]
225
+ edge_widths = [1.0 + 2.0 * norm(abs(G[u][v]["weight"])) for u, v in G.edges()]
226
+
227
+ fig, ax = plt.subplots(figsize=(12, 8))
228
+
229
+ nx.draw(
230
+ G,
231
+ pos,
232
+ ax=ax,
233
+ with_labels=True,
234
+ node_color="lightgray",
235
+ node_size=1000,
236
+ font_size=8,
237
+ edge_color=edge_colors,
238
+ width=edge_widths,
239
+ arrows=True,
240
+ )
241
+
242
+ ax.set_title(title, fontsize=14)
243
+
244
+ sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
245
+ sm.set_array([])
246
+ plt.colorbar(sm, ax=ax, orientation="vertical", label="Edge Weight")
247
+
248
+ plt.tight_layout()
249
+ if save_path:
250
+ plt.savefig(save_path)
251
+ plt.show()
252
+
253
+ dense_layers = [
254
+ layer
255
+ for layer in self.model._classifier.layers
256
+ if isinstance(layer, tf.keras.layers.Dense)
257
+ ]
258
+
259
+ if len(dense_layers) < 1:
260
+ print("No Dense layers found in classifier.")
261
+ return
262
+
263
+ G = nx.DiGraph()
264
+ for idx, layer in enumerate(dense_layers):
265
+ weights = layer.get_weights()[0]
266
+ add_dense_layer_edges(G, weights, idx, threshold_factor, top_k)
267
+
268
+ pos = compute_layout(G)
269
+ draw_graph(G, pos, "Classifier Dense Layers Graph", save_path)
270
+
271
+ def viz_encoder_decoder_graphs(self, threshold_factor=1.0, top_k=5, save_path=None):
272
+ """
273
+ Visualize Dense layers in self.model.encoder and self.model.decoder as directed graphs.
274
+ """
275
+
276
+ def get_top_k_edges(weights, labels_src, labels_dst_prefix, k):
277
+ flat_weights = np.abs(weights.flatten())
278
+ indices = np.argpartition(flat_weights, -k)[-k:]
279
+ top_k_flat_indices = indices[np.argsort(-flat_weights[indices])]
280
+ top_k_edges = []
281
+ for flat_index in top_k_flat_indices:
282
+ i, j = np.unravel_index(flat_index, weights.shape)
283
+ src_label = labels_src[i] if isinstance(labels_src, list) else f"{labels_src}_{i}"
284
+ dst_label = f"{labels_dst_prefix}_{j}"
285
+ top_k_edges.append((src_label, dst_label, weights[i, j]))
286
+ return top_k_edges
287
+
288
+ def add_layer_to_graph(
289
+ G, weights, labels_src, labels_dst_prefix, x_offset, top_k_set, threshold
290
+ ):
291
+ output_nodes = [f"{labels_dst_prefix}_{j}" for j in range(weights.shape[1])]
292
+
293
+ for node in labels_src + output_nodes:
294
+ if node not in G:
295
+ G.add_node(node, x=x_offset if node in labels_src else x_offset + 1)
296
+
297
+ for i, src in enumerate(labels_src):
298
+ for j, dst in enumerate(output_nodes):
299
+ w = weights[i, j]
300
+ if abs(w) > threshold:
301
+ G.add_edge(src, dst, weight=w, highlight=(src, dst) in top_k_set)
302
+ return output_nodes
303
+
304
+ def layout_graph(G):
305
+ pos = {}
306
+ layers = {}
307
+ for node, data in G.nodes(data=True):
308
+ x = data["x"]
309
+ layers.setdefault(x, []).append(node)
310
+
311
+ for x in sorted(layers):
312
+ nodes = layers[x]
313
+ y_positions = np.linspace(1, -1, len(nodes))
314
+ for y, node in zip(y_positions, nodes):
315
+ pos[node] = (x, y)
316
+ return pos
317
+
318
+ def draw_graph(G, title, ax):
319
+ weights = [abs(G[u][v]["weight"]) for u, v in G.edges()]
320
+ if not weights:
321
+ return
322
+
323
+ norm = Normalize(vmin=min(weights), vmax=max(weights))
324
+ cmap = cm.get_cmap("coolwarm")
325
+
326
+ edge_colors = [cmap(norm(G[u][v]["weight"])) for u, v in G.edges()]
327
+ edge_widths = [1.0 + 2.0 * norm(abs(G[u][v]["weight"])) for u, v in G.edges()]
328
+
329
+ pos = layout_graph(G)
330
+ nx.draw(
331
+ G,
332
+ pos,
333
+ ax=ax,
334
+ with_labels=True,
335
+ node_color="lightgray",
336
+ node_size=1000,
337
+ font_size=8,
338
+ edge_color=edge_colors,
339
+ width=edge_widths,
340
+ arrows=True,
341
+ )
342
+
343
+ ax.set_title(title, fontsize=12)
344
+ sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
345
+ sm.set_array([])
346
+ plt.colorbar(sm, ax=ax, orientation="vertical", label="Edge Weight")
347
+
348
+ def build_graph(layers, label_prefix, input_labels=None):
349
+ G = nx.DiGraph()
350
+ x_offset = 0
351
+ prev_labels = input_labels or [
352
+ f"{label_prefix}0_{i}" for i in range(layers[0].get_weights()[0].shape[0])
353
+ ]
354
+
355
+ for idx, layer in enumerate(layers):
356
+ weights = layer.get_weights()[0]
357
+ label = f"{label_prefix}{idx+1}"
358
+ threshold = threshold_factor * np.mean(np.abs(weights))
359
+ top_k_edges = get_top_k_edges(weights, prev_labels, label, top_k)
360
+ top_k_set = set((src, dst) for src, dst, _ in top_k_edges)
361
+
362
+ prev_labels = add_layer_to_graph(
363
+ G, weights, prev_labels, label, x_offset, top_k_set, threshold
364
+ )
365
+ x_offset += 2
366
+
367
+ return G
368
+
369
+ encoder_layers = [
370
+ l for l in self.model._encoder.layers if isinstance(l, tf.keras.layers.Dense)
371
+ ]
372
+ decoder_layers = [
373
+ l for l in self.model._decoder.layers if isinstance(l, tf.keras.layers.Dense)
374
+ ]
375
+
376
+ if not encoder_layers and not decoder_layers:
377
+ print("No Dense layers found in encoder or decoder.")
378
+ return
379
+
380
+ n_graphs = int(bool(encoder_layers)) + int(bool(decoder_layers))
381
+ fig, axes = plt.subplots(1, n_graphs, figsize=(7 * n_graphs, 6), squeeze=False)
382
+
383
+ col = 0
384
+ if encoder_layers:
385
+ input_labels = (
386
+ self.y_labels
387
+ if self.y_labels
388
+ and len(self.y_labels) == encoder_layers[0].get_weights()[0].shape[0]
389
+ else None
390
+ )
391
+ encoder_graph = build_graph(encoder_layers, "E", input_labels)
392
+ draw_graph(encoder_graph, "Encoder", axes[0][col])
393
+ col += 1
394
+
395
+ if decoder_layers:
396
+ decoder_graph = build_graph(decoder_layers, "D")
397
+ draw_graph(decoder_graph, "Decoder", axes[0][col])
398
+
399
+ fig.suptitle("Encoder & Decoder Dense Layer Graphs", fontsize=15)
400
+ plt.tight_layout(rect=[0, 0, 1, 0.95])
401
+
402
+ if save_path:
403
+ plt.savefig(save_path)
404
+ plt.show()
405
+
406
+ if encoder_layers:
407
+ weights = encoder_layers[0].get_weights()[0]
408
+ importances = np.abs(weights).mean(axis=1)
409
+ sorted_idx = np.argsort(-importances)
410
+ xticks = [
411
+ (
412
+ self.y_labels[i]
413
+ if self.y_labels and len(self.y_labels) == weights.shape[0]
414
+ else f"Input_{i}"
415
+ )
416
+ for i in sorted_idx
417
+ ]
418
+
419
+ plt.figure(figsize=(10, 4))
420
+ plt.bar(range(len(importances)), importances[sorted_idx], color="skyblue")
421
+ plt.xticks(range(len(importances)), xticks, rotation=45, ha="right")
422
+ plt.title("Feature Importances (Encoder Input Layer)", fontsize=13)
423
+ plt.ylabel("Mean |Weight|")
424
+ plt.tight_layout()
425
+ plt.show()
426
+
427
+ def predictor_analyzer(
428
+ self,
429
+ frac: float = None,
430
+ cmap: str = "viridis",
431
+ aspect: str = "auto",
432
+ highlight: bool = True,
433
+ **kwargs,
434
+ ) -> None:
435
+ """
436
+ Analyze the model's predictions and visualize data.
437
+
438
+ Parameters
439
+ ----------
440
+ frac : `float`, optional
441
+ Fraction of data to use for analysis (default is `None`).
442
+ cmap : `str`, optional
443
+ The colormap for visualization (default is `"viridis"`).
444
+ aspect : `str`, optional
445
+ Aspect ratio for the visualization (default is `"auto"`).
446
+ highlight : `bool`, optional
447
+ Whether to highlight the maximum weights (default is `True`).
448
+ **kwargs : `dict`, optional
449
+ Additional keyword arguments for customization.
450
+
451
+ Returns
452
+ -------
453
+ `DataFrame` : The statistical summary of the input data.
454
+ """
455
+ self._viz_weights(cmap=cmap, aspect=aspect, highlight=highlight, **kwargs)
456
+ inputs = self.inputs.copy()
457
+ inputs = self._prepare_inputs(inputs, frac)
458
+ self.y_labels = kwargs.get("y_labels", None)
459
+ encoded, reconstructed = self._encode_decode(inputs)
460
+ self._visualize_data(inputs, reconstructed, cmap, aspect)
461
+ self._prepare_data_for_analysis(inputs, reconstructed, encoded, self.y_labels)
462
+
463
+ try:
464
+ self._get_tsne_repr(inputs, frac)
465
+ self._viz_tsne_repr(c=self.classification)
466
+
467
+ self._viz_radviz(self.data, "class", "Radviz Visualization of Latent Space")
468
+ self._viz_radviz(self.data_input, "class", "Radviz Visualization of Input Data")
469
+ except ValueError:
470
+ warnings.warn(
471
+ "Some functions or processes will not be executed for regression problems.",
472
+ UserWarning,
473
+ )
474
+
475
+ return self._statistics(self.data_input)
476
+
477
+ def _prepare_inputs(self, inputs: np.ndarray, frac: float) -> np.ndarray:
478
+ """
479
+ Prepare the input data, possibly selecting a fraction of it.
480
+
481
+ Parameters
482
+ ----------
483
+ inputs : `np.ndarray`
484
+ The input data.
485
+ frac : `float`
486
+ Fraction of data to use.
487
+
488
+ Returns
489
+ -------
490
+ `np.ndarray` : The prepared input data.
491
+ """
492
+ if frac:
493
+ n = int(frac * self.inputs.shape[0])
494
+ indexes = np.random.choice(np.arange(inputs.shape[0]), n, replace=False)
495
+ inputs = inputs[indexes]
496
+ inputs[np.isnan(inputs)] = 0.0
497
+ return inputs
498
+
499
+ def _encode_decode(self, inputs: np.ndarray) -> tuple:
500
+ """
501
+ Perform encoding and decoding on the input data.
502
+
503
+ Parameters
504
+ ----------
505
+ inputs : `np.ndarray`
506
+ The input data.
507
+
508
+ Returns
509
+ -------
510
+ `tuple` : The encoded and reconstructed data.
511
+ """
512
+ try:
513
+ mean, log_var = self.model._encoder(inputs)
514
+ encoded = sampling(mean, log_var)
515
+ except:
516
+ encoded = self.model._encoder(inputs)
517
+ reconstructed = self.model._decoder(encoded)
518
+ return encoded, reconstructed
519
+
520
+ def _visualize_data(
521
+ self, inputs: np.ndarray, reconstructed: np.ndarray, cmap: str, aspect: str
522
+ ) -> None:
523
+ """
524
+ Visualize the original data and the reconstructed data.
525
+
526
+ Parameters
527
+ ----------
528
+ inputs : `np.ndarray`
529
+ The input data.
530
+ reconstructed : `np.ndarray`
531
+ The reconstructed data.
532
+ cmap : `str`
533
+ The colormap for visualization.
534
+ aspect : `str`
535
+ Aspect ratio for the visualization.
536
+
537
+ Returns
538
+ -------
539
+ `None`
540
+ """
541
+ ax = plt.subplot(1, 2, 1)
542
+ plt.imshow(inputs, cmap=cmap, aspect=aspect)
543
+ plt.colorbar()
544
+ plt.title("Original Data")
545
+
546
+ plt.subplot(1, 2, 2, sharex=ax, sharey=ax)
547
+ plt.imshow(reconstructed, cmap=cmap, aspect=aspect)
548
+ plt.colorbar()
549
+ plt.title("Decoder Layer Reconstruction")
550
+ plt.show()
551
+
552
+ def _prepare_data_for_analysis(
553
+ self,
554
+ inputs: np.ndarray,
555
+ reconstructed: np.ndarray,
556
+ encoded: np.ndarray,
557
+ y_labels: List[str],
558
+ ) -> None:
559
+ """
560
+ Prepare data for statistical analysis.
561
+
562
+ Parameters
563
+ ----------
564
+ inputs : `np.ndarray`
565
+ The input data.
566
+ reconstructed : `np.ndarray`
567
+ The reconstructed data.
568
+ encoded : `np.ndarray`
569
+ The encoded data.
570
+ y_labels : `List[str]`
571
+ The labels of features.
572
+
573
+ Returns
574
+ -------
575
+ `None`
576
+ """
577
+ self.classification = (
578
+ self.model._classifier(tf.concat([reconstructed, encoded], axis=1))
579
+ .numpy()
580
+ .argmax(axis=1)
581
+ )
582
+
583
+ self.data = pd.DataFrame(encoded, columns=[f"Feature {i}" for i in range(encoded.shape[1])])
584
+ self.data_input = pd.DataFrame(
585
+ inputs,
586
+ columns=(
587
+ [f"Feature {i}" for i in range(inputs.shape[1])] if y_labels is None else y_labels
588
+ ),
589
+ )
590
+
591
+ self.data["class"] = self.classification
592
+ self.data_input["class"] = self.classification
593
+
594
+ def _get_tsne_repr(self, inputs: np.ndarray = None, frac: float = None) -> None:
595
+ """
596
+ Perform t-SNE dimensionality reduction on the input data.
597
+
598
+ Parameters
599
+ ----------
600
+ inputs : `np.ndarray`
601
+ The input data.
602
+ frac : `float`
603
+ Fraction of data to use.
604
+
605
+ Returns
606
+ -------
607
+ `None`
608
+ """
609
+ if inputs is None:
610
+ inputs = self.inputs.copy()
611
+ if frac:
612
+ n = int(frac * self.inputs.shape[0])
613
+ indexes = np.random.choice(np.arange(inputs.shape[0]), n, replace=False)
614
+ inputs = inputs[indexes]
615
+ inputs[np.isnan(inputs)] = 0.0
616
+ self.latent_representations = inputs @ self.encoder_weights
617
+
618
+ tsne = TSNE(n_components=2)
619
+ self.reduced_data_tsne = tsne.fit_transform(self.latent_representations)
620
+
621
+ def _viz_tsne_repr(self, **kwargs) -> None:
622
+ """
623
+ Visualize the t-SNE representation of the latent space.
624
+
625
+ Parameters
626
+ ----------
627
+ **kwargs : `dict`
628
+ Additional keyword arguments for customization.
629
+
630
+ Returns
631
+ -------
632
+ `None`
633
+ """
634
+ c = kwargs.get("c", None)
635
+ self.colors = (
636
+ kwargs.get("colors", self.sorted_names[: len(np.unique(c))]) if c is not None else None
637
+ )
638
+
639
+ plt.scatter(
640
+ self.reduced_data_tsne[:, 0],
641
+ self.reduced_data_tsne[:, 1],
642
+ cmap=matplotlib.colors.ListedColormap(self.colors) if c is not None else None,
643
+ c=c,
644
+ )
645
+
646
+ if c is not None:
647
+ cb = plt.colorbar()
648
+ loc = np.arange(0, max(c), max(c) / float(len(self.colors)))
649
+ cb.set_ticks(loc)
650
+ cb.set_ticklabels(np.unique(c))
651
+
652
+ plt.title("t-SNE Visualization of Latent Space")
653
+ plt.xlabel("t-SNE 1")
654
+ plt.ylabel("t-SNE 2")
655
+ plt.show()
656
+
657
+ def _viz_radviz(self, data: pd.DataFrame, color_column: str, title: str) -> None:
658
+ """
659
+ Visualize the data using RadViz.
660
+
661
+ Parameters
662
+ ----------
663
+ data : `pd.DataFrame`
664
+ The data to visualize.
665
+ color_column : `str`
666
+ The column to use for coloring.
667
+ title : `str`
668
+ The title of the plot.
669
+
670
+ Returns
671
+ -------
672
+ `None`
673
+ """
674
+ data_normalized = data.copy(deep=True)
675
+ data_normalized.iloc[:, :-1] = (
676
+ 2.0
677
+ * (data_normalized.iloc[:, :-1] - data_normalized.iloc[:, :-1].min())
678
+ / (data_normalized.iloc[:, :-1].max() - data_normalized.iloc[:, :-1].min())
679
+ - 1
680
+ )
681
+ data_normalized.dropna(axis=1, inplace=True)
682
+ radviz(data_normalized, color_column, color=self.colors)
683
+ plt.title(title)
684
+ plt.show()
685
+
686
+ def _viz_weights(
687
+ self, cmap: str = "viridis", aspect: str = "auto", highlight: bool = True, **kwargs
688
+ ) -> None:
689
+ """
690
+ Visualize the encoder layer weights of the model.
691
+
692
+ Parameters
693
+ ----------
694
+ cmap : `str`, optional
695
+ The colormap for visualization (default is `"viridis"`).
696
+ aspect : `str`, optional
697
+ Aspect ratio for the visualization (default is `"auto"`).
698
+ highlight : `bool`, optional
699
+ Whether to highlight the maximum weights (default is `True`).
700
+ **kwargs : `dict`, optional
701
+ Additional keyword arguments for customization.
702
+
703
+ Returns
704
+ -------
705
+ `None`
706
+ """
707
+ title = kwargs.get("title", "Encoder Layer Weights (Dense Layer)")
708
+ y_labels = kwargs.get("y_labels", None)
709
+ cmap_highlight = kwargs.get("cmap_highlight", "Pastel1")
710
+ highlight_mask = np.zeros_like(self.encoder_weights, dtype=bool)
711
+
712
+ plt.imshow(self.encoder_weights, cmap=cmap, aspect=aspect)
713
+ plt.colorbar()
714
+ plt.title(title)
715
+ if y_labels is not None:
716
+ plt.yticks(ticks=np.arange(self.encoder_weights.shape[0]), labels=y_labels)
717
+ if highlight:
718
+ for i, j in enumerate(self.encoder_weights.argmax(axis=1)):
719
+ highlight_mask[i, j] = True
720
+ plt.imshow(
721
+ np.ma.masked_where(~highlight_mask, self.encoder_weights),
722
+ cmap=cmap_highlight,
723
+ alpha=0.5,
724
+ aspect=aspect,
725
+ )
726
+ plt.show()
727
+
728
+ def _statistics(self, data_input: DataFrame) -> DataFrame:
729
+ """
730
+ Compute statistical summaries of the input data.
731
+
732
+ Parameters
733
+ ----------
734
+ data_input : `DataFrame`
735
+ The data to compute statistics for.
736
+
737
+ Returns
738
+ -------
739
+ `DataFrame` : The statistical summary of the input data.
740
+ """
741
+ data = data_input.copy(deep=True)
742
+
743
+ if not pd.api.types.is_string_dtype(data["class"]):
744
+ data["class"] = data["class"].astype(str)
745
+
746
+ data.ffill(inplace=True)
747
+ grouped_data = data.groupby("class")
748
+
749
+ numerical_stats = grouped_data.agg(["mean", "min", "max", "std", "median"])
750
+ numerical_stats.columns = ["_".join(col).strip() for col in numerical_stats.columns.values]
751
+
752
+ def get_mode(x):
753
+ mode_series = x.mode()
754
+ return mode_series.iloc[0] if not mode_series.empty else None
755
+
756
+ mode_stats = grouped_data.apply(get_mode, include_groups=False)
757
+ mode_stats.columns = [f"{col}_mode" for col in mode_stats.columns]
758
+ combined_stats = pd.concat([numerical_stats, mode_stats], axis=1)
759
+
760
+ return combined_stats.T
761
+
762
+
763
+ ########################################################################################
764
+
765
+ if __name__ == "__main__":
766
+ # Example usage
767
+ import pandas as pd
768
+ from sklearn.datasets import load_iris
769
+ from sklearn.preprocessing import OneHotEncoder
770
+
771
+ # Load the dataset
772
+ iris = load_iris()
773
+
774
+ # Convert to a DataFrame for easy exploration
775
+ iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
776
+ iris_df["species"] = iris.target
777
+
778
+ X = iris_df.drop(columns="species")
779
+ y_labels = X.columns
780
+ X = X.values
781
+ y = iris_df["species"].values
782
+
783
+ X = np.asarray(X).astype(np.float32)
784
+
785
+ encoder = OneHotEncoder()
786
+ y = encoder.fit_transform(y.reshape(-1, 1)).toarray()
787
+ y = np.asarray(y).astype(np.float32)
788
+
789
+ model = AutoClassifier(
790
+ input_shape_parm=X.shape[1],
791
+ num_classes=3,
792
+ units=27,
793
+ activation="tanh",
794
+ num_layers=2,
795
+ dropout=0.2,
796
+ )
797
+ model.compile(
798
+ optimizer="adam",
799
+ loss=tf.keras.losses.CategoricalCrossentropy(),
800
+ metrics=[tf.keras.metrics.F1Score(threshold=0.5)],
801
+ )
802
+ model.fit(X, y, epochs=50, validation_split=0.2)
803
+
804
+ insights = GetInsights(model, X)
805
+ summary = insights.predictor_analyzer(frac=1.0, y_labels=y_labels)
806
+ insights._get_tsne_repr()
807
+ insights._viz_tsne_repr()
808
+ insights._viz_tsne_repr(c=iris_df["species"])
809
+ insights._viz_weights()
810
+ print(summary)