1 import numpy as np 2 import matplotlib.pyplot as plt 3 from scipy.stats import gaussian_kde 4 from matplotlib.patches import Ellipse 5 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten 6 setup_style() 7 8 np.random.seed(42) 9 classes = ['Class A', 'Class B', 'Class C', 'Class D'] 10 n_per = 150 11 embeddings, labels = [], [] 12 for i, cls in enumerate(classes): 13 center = np.random.randn(2) * 4 14 pts = center + np.random.randn(n_per, 2) * 0.8 15 embeddings.append(pts) 16 labels.extend([cls] * n_per) 17 embeddings = np.vstack(embeddings) 18 19 fig, ax = plt.subplots(figsize=(7, 6)) 20 21 for i, cls in enumerate(classes): 22 mask = np.array(labels) == cls 23 pts = embeddings[mask] 24 25 # KDE contour background 26 xy = pts.T 27 kde = gaussian_kde(xy, bw_method=0.4) 28 xg = np.linspace(pts[:, 0].min() - 2, pts[:, 0].max() + 2, 80) 29 yg = np.linspace(pts[:, 1].min() - 2, pts[:, 1].max() + 2, 80) 30 Xg, Yg = np.meshgrid(xg, yg) 31 Z = kde(np.vstack([Xg.ravel(), Yg.ravel()])).reshape(Xg.shape) 32 ax.contourf(Xg, Yg, Z, levels=5, cmap=plt.cm.Blues if i == 0 else 33 plt.cm.Oranges if i == 1 else plt.cm.Greens if i == 2 else plt.cm.Purples, 34 alpha=0.15) 35 ax.contour(Xg, Yg, Z, levels=3, colors=PALETTE[i], alpha=0.3, linewidths=0.5) 36 37 # 95% confidence ellipse 38 cov = np.cov(pts.T) 39 eigenvalues, eigenvectors = np.linalg.eigh(cov) 40 angle = np.degrees(np.arctan2(eigenvectors[1, 1], eigenvectors[0, 1])) 41 width, height = 2 * np.sqrt(eigenvalues * 5.991) # chi2 95% 42 ellipse = Ellipse(xy=pts.mean(axis=0), width=width, height=height, angle=angle, 43 facecolor='none', edgecolor=PALETTE[i], linewidth=1.2, 44 linestyle='--', alpha=0.6) 45 ax.add_patch(ellipse) 46 47 # Scatter points 48 ax.scatter(pts[:, 0], pts[:, 1], s=10, alpha=0.45, color=PALETTE[i], 49 label=cls, edgecolor='none') 50 51 # Class center label in white box 52 cx, cy = pts.mean(axis=0) 53 ax.annotate(cls, xy=(cx, cy), fontsize=9, fontweight='bold', color=PALETTE[i], 54 ha='center', va='center', 55 bbox=dict(boxstyle='round,pad=0.4', facecolor='white', 56 edgecolor=PALETTE[i], alpha=0.9, linewidth=1)) 57 58 ax.set_xlabel('Dimension 1', fontsize=11) 59 ax.set_ylabel('Dimension 2', fontsize=11) 60 ax.legend(frameon=False, labelspacing=0.35, handlelength=1.6, fontsize=9, markerscale=3, loc='best') 61 ax.spines['top'].set_visible(False) 62 ax.spines['right'].set_visible(False) 63 ax.grid(alpha=0.15, linestyle='--') 64 fig.tight_layout() 65 save_fig(fig, 'figures/fig_tsne.pdf')