t-SNE ও UMAP
এই পাঠে যা শিখবেন
- t-SNE-এর core idea — probability distribution preservation
- UMAP-এর fuzzy topological framework
- Hyperparameter — perplexity, n_neighbors কী করে
- কখন কোনটা — t-SNE বনাম UMAP বনাম PCA
- MNIST-এ visualization, embedding visualization in NLP
১ · PCA-এর সীমাবদ্ধতা থেকে শুরু
PCA linear projection — high-D space-কে straight hyperplane দিয়ে কাটে। কিন্তু বাস্তব data প্রায়ই non-linear manifold-এ থাকে। যেমন — Swiss roll, sphere, S-curve। PCA এই shapes flatten করতে গিয়ে — local neighborhood ভেঙে ফেলে।
MNIST handwritten digit (২৮×২৮ = ৭৮৪-D) — PCA-তে ২-D plot করুন। সব digit একে অপরের ওপর overlap। PCA-এর কোনো clue নেই কোন digit-এর ছবি। কিন্তু — t-SNE বা UMAP-এ একই data plot করলে — প্রতিটি digit তার নিজস্ব cluster-এ আলাদা।
Real-world high-D data সাধারণত একটি অনেক ছোট non-linear manifold-এ বাস করে। ৭৮৪-D MNIST আসলে ৫-১০-D manifold-এ। ১৫০K-D natural image হয়তো ১০০-D manifold-এ। এই hidden manifold শিখাই non-linear dim-reduction-এর কাজ।
২ · t-SNE — probability distribution matching
t-SNE (van der Maaten-Hinton, ২০০৮) idea — high-D-এ point-জোড়ার "neighbor" সম্ভাবনা low-D-এ preserve।
High-D-এ similarity:
$$p_{j|i} = \frac{\exp(-\|\mathbf{x}_i - \mathbf{x}_j\|^2 / 2\sigma_i^2)}{\sum_{k \neq i} \exp(-\|\mathbf{x}_i - \mathbf{x}_k\|^2 / 2\sigma_i^2)}$$
Gaussian kernel — $\sigma_i$ adaptive (perplexity দিয়ে নির্ধারিত)।
Low-D-এ similarity: Student's $t$-distribution (heavier tail):
$$q_{ij} = \frac{(1 + \|\mathbf{y}_i - \mathbf{y}_j\|^2)^{-1}}{\sum_{k \neq l} (1 + \|\mathbf{y}_k - \mathbf{y}_l\|^2)^{-1}}$$
Objective — KL divergence minimize:
$$\text{KL}(P || Q) = \sum_{i \neq j} p_{ij} \log \frac{p_{ij}}{q_{ij}}$$
Gradient descent — low-D point $\mathbf{y}_i$ এ update। Heavy-tail $t$-distribution "crowding problem" সমাধান করে — far points push, near points pull।
৩ · Perplexity — t-SNE-এর key hyperparameter
Perplexity ≈ effective neighbor count। ছোট perplexity (৫) = local detail, বড় (৫০) = broader structure। $\sigma_i$ এমনভাবে set যাতে — entropy of $p_{j|i}$ = $\log(\text{perplexity})$।
- Default: ৩০।
- ছোট data — কম perplexity।
- বড় data — বেশি।
- একই data ভিন্ন perplexity → ভিন্ন plot। সাধারণত ৫, ৩০, ১০০ — তিনটি try।
৪ · UMAP — modern successor
UMAP (McInnes-Healy-Melville, ২০১৮) — Riemannian geometry, fuzzy topological set theory ভিত্তিক। Practical-এ —
- প্রতিটি point-এর $k$-nearest neighbor graph।
- Fuzzy similarity — high-D-এ symmetric।
- Low-D-এ similar fuzzy structure preserve — cross-entropy minimize।
- Stochastic gradient descent — fast।
Hyperparameter:
n_neighbors— ১৫ (default)। ছোট = local detail, বড় = global।min_dist— ০.১ (default)। ছোট = tight cluster, বড় = spread out।n_components— output dim (২ visualization)।
৫ · t-SNE বনাম UMAP — কোথায় কোনটা
- Speed: UMAP ১০× দ্রুত। ১ লাখ point t-SNE ঘণ্টা, UMAP মিনিট।
- Global structure: UMAP-এ better preservation। t-SNE শুধু local।
- Reproducibility: UMAP-এর result perplexity-এর মত sensitive না।
- Out-of-sample: UMAP পরে নতুন point project করতে পারে। t-SNE non-parametric — পারে না।
- Embedding distance: দু'টিতেই plot-এর দূরত্ব literal নয় — শুধু grouping।
Practical rule: UMAP default — সবচেয়ে use case-এ ভাল। t-SNE শুধু — যদি UMAP-এ result অস্পষ্ট, বা academic comparison।
৬ · sklearn-এ t-SNE — MNIST visualization
import numpy as np
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
digits = load_digits() # 8x8 = 64-D, 10 classes
X, y = digits.data, digits.target
# t-SNE — সাধারণত PCA দিয়ে preprocess (50-D) তারপর t-SNE (slow)
X_50 = PCA(n_components=50).fit_transform(X)
tsne = TSNE(n_components=2, perplexity=30,
init="pca", random_state=0, n_iter=1000)
X_2 = tsne.fit_transform(X_50)
print(f"Original shape: {X.shape}")
print(f"After PCA→t-SNE: {X_2.shape}")
print(f"Cluster center per digit (first 3):")
for d in range(3):
center = X_2[y == d].mean(axis=0)
print(f" digit {d}: ({center[0]:.1f}, {center[1]:.1f})")
৭ · UMAP usage
# pip install umap-learn
import umap
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1,
n_components=2, random_state=0)
X_u = reducer.fit_transform(X)
print(f"UMAP shape: {X_u.shape}")
# নতুন point-এ project — t-SNE-এ impossible, UMAP-এ সহজ
new_point = np.random.rand(1, 64) * 16
new_proj = reducer.transform(new_point)
print(f"New point in UMAP space: {new_proj.round(2)}")
transform() — নতুন point একই learned manifold-এ project। Production-এ এটাই critical — t-SNE প্রতিবার পুরো dataset-এ refit করতে হয়।
৮ · Visualization-এর সাবধানতা
সাধারণ ভুল:
- "Cluster A বড়, B ছোট — A বেশি diverse" — ভুল।
- "A ও B কাছে, A ও C দূর — A বেশি similar to B" — সাধারণত ভুল।
- "Cluster shape elongated — feature gradient" — over-interpretation।
৯ · প্রয়োগ ক্ষেত্র
- NLP: word embedding (Word2Vec, BERT) ২-D-এ visualization।
- Single-cell genomics: ১০K cell type clustering — UMAP standard।
- Image dataset exploration: CNN feature ২-D-এ — class structure check।
- Customer segmentation: dense feature space exploration।
- Anomaly detection: outlier-গুলো দূরে দেখায়।
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১ t-SNE plot-এ দূরত্ব meaningful নয় — তবু এটা সবচেয়ে viral ML visualization কেন? Trade-off কী?
চমৎকার paradox। Misleading কিন্তু useful — কেন coexist?
t-SNE-এর viral appeal:
- Beautiful — natural cluster separation।
- Intuitive — "এই গ্রুপ আলাদা" instant।
- High-D ML model debug-এর strongest tool।
- Twitter/blog-এ visually striking।
Misleading aspects:
- Distance: 2D-এর Euclidean distance high-D-এর reflection নয়।
- Cluster size: dense original cluster small in plot, sparse → big — counter-intuitive।
- Position: "A is between B and C" — usually meaningless।
- Stability: different seed → different plot।
কী বিশ্বস্ত:
- Cluster membership — points groupings।
- Outlier identification।
- Class separability presence/absence।
কী বিশ্বস্ত নয়:
- Inter-cluster distance — ratio।
- Cluster shape — circular vs elongated।
- Density — visual density।
- Hierarchy — "B between A and C"।
Common misuses:
- Paper claim — "model X-এর representation more separable than Y" — without quantitative check।
- "Cluster ১ closer to cluster ২ than ৩" — over-interpretation।
- Cluster naming based on plot position।
Best practices:
- Multiple perplexity (5, 30, 50) — সব similar হলে confidence।
- Multiple seed — agreement check।
- Quantitative metric — silhouette in original space, not plot।
- Both PCA + t-SNE/UMAP — global + local view।
- Caveat caption — "for visualization only, distances not meaningful"।
Trade-off summary:
- Faithful representation — impossible in 2D for high-D।
- Useful approximation — t-SNE/UMAP।
- Trust local — distrust global।
মূল উপলব্ধি: t-SNE/UMAP — exploratory, not confirmatory। Insight generate করো, conclusion draw করো না। Statistical test always in original space।
প্র ০২
UMAP-এর n_neighbors ও min_dist — কীভাবে বদলায় visualization? Tuning কীভাবে করেন?
UMAP-এর dual hyperparameter — geometry-র two control knob।
n_neighbors — local vs global balance:
- Small (২-১০): মাত্র কাছের neighbor। Local detail emphasize। Cluster fragmented হতে পারে।
- Default (১৫): moderate — most data-এ ভাল।
- Large (৫০-২০০): broader neighborhood। Global structure preserve।
- "কত local-হয়ে দেখব" — এর উত্তর।
min_dist — cluster compactness:
- Small (০.০-০.১): tight cluster, separated points overlap allowed।
- Default (০.১): moderate compactness।
- Large (০.৫-১.০): spread, cluster blur।
- "plot-এর density কেমন" — এর উত্তর।
Combined effect grid:
- Low n, low min: tight local clusters, fragmented।
- Low n, high min: spread out local cluster।
- High n, low min: tight global cluster।
- High n, high min: spread global structure।
Tuning workflow:
- Default চালান।
- Cluster fragmented = n_neighbors বাড়ান।
- Cluster overlapping = n_neighbors কমান।
- Plot dense indistinguishable = min_dist বাড়ান।
- Plot too spread = min_dist কমান।
Domain examples:
- Single-cell genomics: n_neighbors ১৫-৫০, min_dist ০.১। Cell type-গুলো cluster, transition state visible।
- NLP word embedding: n_neighbors ৩০-১০০, min_dist ০.১। Concept-গুলো cluster।
- Image features: n_neighbors ১৫, min_dist ০.০। Tight class cluster।
- Time series: n_neighbors ১০-২০, min_dist ০.৩। Trajectory smooth।
Other hyperparameters:
metric— distance function। Cosine for embedding, euclidean for tabular।spread— combined with min_dist, cluster spread control।n_epochs— training iteration। বড় = stable।set_op_mix_ratio— fuzzy set union/intersection।
Stability verify:
- একই hyperparameter ভিন্ন seed → similar plot?
- Hyperparameter range-এ smooth interpolation?
- Robust = trust।
মূল উপলব্ধি: UMAP hyperparameter-এ artistic — multiple settings explore। "Best plot" subjective; multiple complementary।
প্র ০৩ BERT embedding (৭৬৮-D) UMAP দিয়ে visualize করছেন। Semantic structure বের আসবে কি? Caveats?
NLP-এর সবচেয়ে জনপ্রিয় visualization — BERT/sentence-transformer + UMAP।
Pipeline:
- Sentence — sentence-transformer embedding (৭৬৮-D)।
- Cosine similarity meaningful — UMAP metric="cosine"।
- UMAP → 2-D।
- Color by topic/domain।
কী দেখা যাবে:
- Topic cluster — sports, politics, science আলাদা।
- Sentiment gradient — positive vs negative।
- Language family — Bangla, Hindi, Urdu একসাথে।
- Style cluster — formal, casual, technical।
- Outlier — strange/spam।
BERT-specific caveats:
- Anisotropy: BERT embedding non-uniform — narrow cone in space। UMAP-এর pre-processing দরকার।
- CLS token vs mean pooling: different embedding strategies → different visualization।
- Layer choice: last layer task-specific, middle layer more general।
- Fine-tuned model: task-specific structure visible — but biased।
Bangla NLP specific:
- Multilingual BERT (mBERT) — Bangla support OK but suboptimal।
- Bangla-BERT (Sagor Sarker) — fine-tuned।
- BanglaBERT (CSEBUETNLP) — domain-specific।
- UMAP plot-এ Bangla cluster English/Hindi-এর কাছে — common Devanagari heritage influence।
Concrete use case:
- Bangla news article classification — UMAP plot-এ category cluster।
- Misclassified article — boundary-এ visible।
- New domain detection — outlier islands।
Caveats:
- 2-D 768-D-এর tiny shadow — অনেক information lost।
- Cluster look clean, but quantitative metric (silhouette) weaker।
- Sample size — ১০K+ ভাল visualization, ১০০ misleading।
- Color choice critical — too many class color-চক্র চক্ষুপীড়ক।
Beyond UMAP:
- Topic modeling: BERTopic — UMAP + HDBSCAN + class TF-IDF।
- Interactive: TensorFlow Embedding Projector।
- Hierarchical: multi-scale UMAP — broad + detail view।
মূল উপলব্ধি: BERT + UMAP — Bangla NLP-এর classroom demo standard। Real product analysis-এ এই visualization debugging gold।
প্র ০৪ একটি Bangladesh fintech কোম্পানি ১০ মিলিয়ন user-এর behavior visualize করতে চায়। UMAP scale-এ কিভাবে?
Production scale UMAP — bKash, Nagad, Rocket-এর real challenge।
Scale challenge:
- 10M user × 100 feature = 10⁹ values।
- Default UMAP — memory blow up, slow।
- Memory: ~8 GB raw, ~80 GB intermediate।
(১) Sample first:
- 1M random sample → UMAP fit।
- 9M-এ
transform()apply। - Trade-off: rare segment under-represented।
- Stratified sampling — preserve distribution।
(২) PCA → UMAP:
- 100-D → 50-D PCA (fast, deterministic)।
- 50-D → UMAP 2-D।
- 5× speedup, signal mostly retained।
- Standard pipeline।
(৩) GPU UMAP:
- cuML (RAPIDS) — sklearn-API GPU।
- 10-50× speedup typical।
- 10M sample possible on single A100।
(৪) PaCMAP/TriMAP:
- UMAP-এর alternative — better global preservation।
- Some scale better।
- Newer (২০২১+), less mature।
(৫) Approximate UMAP:
- Subsampled k-NN graph।
- Lower precision arithmetic।
- Speedup 2-5×।
(৬) Aggregation strategy:
- 10M user → 10K cluster centroid (K-Means)।
- Centroid-এ UMAP।
- Visualization — cluster level, not individual।
Production pipeline:
- Daily ETL — feature extraction।
- Weekly UMAP refit — 1M stratified sample।
- Daily transform — full 10M।
- Cluster on UMAP space (HDBSCAN)।
- Persona generation — cluster-wise mean feature।
- Dashboard — interactive plot, drill-down।
Visualization challenge:
- 10M scatter — overplotting।
- Hexbin density plot।
- Datashader (Bokeh) — server-side rendering।
- WebGL canvas (deck.gl)।
Use cases:
- Persona discovery — marketing campaign target।
- Fraud cluster — anomaly users।
- Churn prediction — cluster transition tracking।
- Product feature segmentation — usage pattern।
Privacy:
- Aggregated only — no individual identifiable।
- Differential privacy noise add।
- Internal use, no public sharing।
Bangladesh-specific:
- Festival pattern — Eid, puja shopping।
- Geographic clusters — Dhaka, port city, rural।
- Income tier transition — UMAP timeline visualize।
- Weather-driven behavior — flood, rain।
মূল উপলব্ধি: 10M scale UMAP — sample + GPU + smart pipeline। Visualization purpose specific — exploration, not exhaustive। Bangladesh fintech-এ UMAP-driven persona — competitive advantage।
অনুশীলন
-
হিসাব করুন: t-SNE-এ perplexity ৫ ও ৫০ দিয়ে একই data-এ চালালে কী আশা করেন? কেন?
- Perplexity 5: ছোট neighborhood — local detail। Sub-cluster visible।
- Perplexity 50: বড় neighborhood — broader structure। Sub-cluster merge।
- Same global cluster pattern usually retained, but granularity ভিন্ন।
- Both views complementary — choose based on insight goal।
-
sklearn-এ চেষ্টা: Iris dataset (4D, 3 class) — PCA, t-SNE, UMAP-এ visualize compare।
from sklearn.datasets import load_iris from sklearn.decomposition import PCA from sklearn.manifold import TSNE iris = load_iris() X, y = iris.data, iris.target X_pca = PCA(n_components=2).fit_transform(X) X_tsne = TSNE(n_components=2, perplexity=15, random_state=0).fit_transform(X) # UMAP needs umap-learn install print("PCA shape:", X_pca.shape) print("t-SNE shape:", X_tsne.shape) # Iris small — সব similar pattern (setosa আলাদা, versicolor-virginica overlap) -
ভাবুন: Bangladesh-এ ১ লক্ষ news article ক্যাটেগরি explore করতে UMAP। কোন embedding model? pipeline?
- Embedding: sagorsarker/bangla-bert-base (Bangla-pretrained)।
- Mean pooling: sentence representation।
- Preprocessing: Bangla tokenization, normalization।
- Pipeline: 768-D embedding → PCA 50-D → UMAP 2-D।
- UMAP: metric=cosine, n_neighbors=30, min_dist=0.1।
- Cluster: HDBSCAN-এ 10-50 topic cluster।
- Naming: per-cluster top TF-IDF word — "politics", "cricket"।
- Visualization: Bokeh interactive — hover-এ article preview।
- Use: editorial coverage analysis, trend detection।
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ৩৬ · Bayesian Networks পরবর্তী পাঠ Probabilistic graphical model — উত্তর: causation।
- পাঠ ৩৪ · PCA আগের পাঠ Linear precursor — বুঝে নিলেই t-SNE/UMAP-এর value।
- পাঠ ৩৩ · DBSCAN এই পাঠের সাথে সম্পর্কিত UMAP + HDBSCAN — modern unsupervised pipeline।
- সব AI Courses ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps।