Communitygithub.com

umap-learn

UMAP-learn을 사용한 비선형 차원 축소, 2D/3D 임베딩, 클러스터링 전처리, 지도 및 반지도 UMAP, DensMAP, AlignedUMAP, 파라메트릭 UMAP 워크플로우를 제공합니다.

umap-learn란 무엇인가요?

UMAP(Uniform Manifold Approximation and Projection)은 시각화 및 일반적인 비선형 차원 축소를 위한 기법으로, 국소 및 전역 구조를 보존하며 빠르고 확장 가능한 임베딩을 제공합니다. 이 스킬은 지도 학습 및 클러스터링 전처리에도 활용할 수 있으며, t-SNE나 PCA의 대안으로 사용됩니다. UMAP은 scikit-learn의 API를 따르므로, `fit_transform` 메서드로 간단히 임베딩을 생성할 수 있고, `transform` 메서드로 새로운 데이터를 기존 임베딩 공간에 투영할 수 있습니다. 주요 매개변수로는 `n_neighbors`(국소 대 전역 구조 균형), `min_dist`(점들의 클러스터링 밀도), `n_components`(출력 차원), `metric`(거리 측정 방식)이 있으며, 이를 조정하여 다양한 목적(시각화, 클러스터링 전처리, 머신러닝 파이프라인)에 최적화할 수 있습니다. 또한, 지도 및 반지도 UMAP을 통해 레이블 정보를 임베딩에 반영할 수 있고, 파라메트릭 UMAP을 사용하면 신경망을 기반으로 한 효율적인 변환과 재구성(inverse transform)이 가능합니다. 이 스킬은 Python 3.9+ 환경에서 `umap-learn` 패키지로 설치할 수 있으며, Numba와 scikit-learn에 의존합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/umap-learn

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

umap-learn은(는) 무엇을 하나요?

개요

UMAP(Uniform Manifold Approximation and Projection)은 시각화 및 일반적인 비선형 차원 축소를 위한 기법입니다. 이 스킬을 사용하면 국소 및 전역 구조를 보존하는 빠르고 확장 가능한 임베딩, 지도 학습, 클러스터링 전처리를 수행할 수 있습니다.

빠른 시작

설치

현재 안정 버전: umap-learn 0.5.12 (2026년 4월 출시). Python 3.9+가 필요하며 scikit-learn>=1.6, numba, pynndescent, numpy, scipy에 의존합니다. 검증된 릴리스로 고정하세요:

uv pip install umap-learn==0.5.12

기본 사용법

UMAP은 scikit-learn 규칙을 따르며 t-SNE나 PCA의 드롭인 대체재로 사용할 수 있습니다.

import umap
from sklearn.preprocessing import StandardScaler

# 데이터 준비 (표준화는 필수입니다)
scaled_data = StandardScaler().fit_transform(data)

# 방법 1: 단일 단계 (fit 및 transform)
embedding = umap.UMAP().fit_transform(scaled_data)

# 방법 2: 분리 단계 (훈련된 모델 재사용용)
reducer = umap.UMAP(random_state=42)
reducer.fit(scaled_data)
embedding = reducer.embedding_  # 훈련된 임베딩에 접근

전처리 요구 사항: 전처리를 메트릭에 맞추세요. 숫자형 유클리드 스타일 메트릭의 경우 피팅 전에 특성을 스케일링하여 분산이 큰 열이 지배하지 않도록 하세요. 코사인, 이진, 사전 계산된 거리 또는 혼합 특성 워크플로우의 경우, 모든 열을 무조건 표준화하는 대신 메트릭에 맞는 전처리를 선택하세요.

일반적인 워크플로우

import umap
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler

# 1. 데이터 전처리
scaler = StandardScaler()
scaled_data = scaler.fit_transform(raw_data)

# 2. UMAP 생성 및 피팅
reducer = umap.UMAP(
    n_neighbors=15,
    min_dist=0.1,
    n_components=2,
    metric='euclidean',
    random_state=42
)
embedding = reducer.fit_transform(scaled_data)

# 3. 시각화
plt.scatter(embedding[:, 0], embedding[:, 1], c=labels, cmap='Spectral', s=5)
plt.colorbar()
plt.title('UMAP Embedding')
plt.show()

매개변수 튜닝 가이드

UMAP은 임베딩 동작을 제어하는 네 가지 주요 매개변수가 있습니다. 이를 이해하는 것이 효과적인 사용에 중요합니다.

n_neighbors (기본값: 15)

목적: 임베딩에서 국소 구조와 전역 구조의 균형을 맞춥니다.

작동 방식: UMAP이 매니폴드 구조를 학습할 때 조사하는 로컬 이웃의 크기를 제어합니다.

값에 따른 효과:

  • 낮은 값 (2-5): 세부적인 국소 정보를 강조하지만 데이터가 연결되지 않은 구성 요소로 조각날 수 있음
  • 중간 값 (15-20): 국소 구조와 전역 관계의 균형 잡힌 시각 (권장 시작점)
  • 높은 값 (50-200): 세부 정보를 희생하면서 광범위한 위상 구조를 우선시

권장 사항: 15부터 시작하여 결과에 따라 조정하세요. 더 전역적인 구조를 원하면 증가시키고, 더 국소적인 세부 정보를 원하면 감소시키세요.

min_dist (기본값: 0.1)

목적: 저차원 공간에서 점들이 얼마나 밀집되어 군집을 이루는지 제어합니다.

작동 방식: 출력 표현에서 점들이 서로 얼마나 가까이 위치할 수 있는지 최소 거리를 설정합니다.

값에 따른 효과:

  • 낮은 값 (0.0-0.1): 클러스터링에 유용한 뭉친 임베딩을 생성하며, 미세한 위상적 세부 정보를 드러냄
  • 높은 값 (0.5-0.99): 단단한 패킹을 방지하고 국소 구조보다 광범위한 위상 보존을 강조

권장 사항: 클러스터링 응용에는 0.0, 시각화에는 0.1-0.3, 느슨한 구조에는 0.5+를 사용하세요.

n_components (기본값: 2)

목적: 임베딩된 출력 공간의 차원을 결정합니다.

주요 기능: t-SNE와 달리 UMAP은 임베딩 차원에서 잘 확장되어 시각화 이상의 용도로 사용할 수 있습니다.

일반적인 용도:

  • 2-3 차원: 시각화
  • 5-10 차원: 클러스터링 전처리 (2D보다 밀도를 더 잘 보존)
  • 10-50 차원: 다운스트림 ML 모델을 위한 특성 엔지니어링

권장 사항: 시각화에는 2, 클러스터링에는 5-10, ML 파이프라인에는 더 높은 값을 사용하세요.

metric (기본값: 'euclidean')

목적: 입력 데이터 포인트 간의 거리 계산 방식을 지정합니다.

지원되는 메트릭:

  • Minkowski 변형: euclidean, manhattan, chebyshev
  • 공간 메트릭: canberra, braycurtis, haversine
  • 상관 메트릭: cosine, correlation (텍스트/문서 임베딩에 좋음)
  • 이진 데이터 메트릭: hamming, jaccard, dice, russellrao, kulsinski, rogerstanimoto, sokalmichener, sokalsneath, yule
  • 사용자 정의 메트릭: Numba를 통한 사용자 정의 거리 함수

권장 사항: 숫자형 데이터에는 euclidean, 텍스트/문서 벡터에는 cosine, 이진 데이터에는 hamming을 사용하세요.

매개변수 튜닝 예제

# 국소 구조를 강조한 시각화용
umap.UMAP(n_neighbors=15, min_dist=0.1, n_components=2, metric='euclidean')

# 클러스터링 전처리용
umap.UMAP(n_neighbors=30, min_dist=0.0, n_components=10, metric='euclidean')

# 문서 임베딩용
umap.UMAP(n_neighbors=15, min_dist=0.1, n_components=2, metric='cosine')

# 전역 구조 보존용
umap.UMAP(n_neighbors=100, min_dist=0.5, n_components=2, metric='euclidean')

지도 및 반지도 차원 축소

UMAP은 레이블 정보를 임베딩 과정에 통합하여 클래스 분리를 가능하게 하면서 내부 구조를 보존합니다.

지도 UMAP

피팅 시 y 매개변수에 대상 레이블을 전달하세요:

# 지도 차원 축소
embedding = umap.UMAP().fit_transform(data, y=labels)

주요 이점:

  • 깔끔하게 분리된 클래스 달성
  • 각 클래스 내부 구조 보존
  • 클래스 간 전역 관계 유지

반지도 UMAP

부분 레이블의 경우, scikit-learn 규칙에 따라 레이블이 없는 점을 -1로 표시하세요:

# 반지도 레이블 생성
semi_labels = labels.copy()
semi_labels[unlabeled_indices] = -1

# 부분 레이블로 피팅
embedding = umap.UMAP().fit_transform(data, y=semi_labels)

사용 시기: 레이블링 비용이 비싸거나 사용 가능한 레이블보다 더 많은 데이터가 있을 때.

클러스터링을 위한 UMAP

UMAP은 HDBSCAN과 같은 밀도 기반 클러스터링 알고리즘을 위한 효과적인 전처리 역할을 하며 차원의 저주를 극복합니다.

클러스터링을 위한 모범 사례

핵심 원칙: 시각화와 다른 방식으로 클러스터링을 위해 UMAP을 구성하세요.

권장 매개변수:

  • n_neighbors: ~30으로 증가 (기본값 15는 너무 국소적이어서 인위적인 세분화된 클러스터를 생성할 수 있음)
  • min_dist: 0.0으로 설정 (클러스터 내 점들을 밀집시켜 더 명확한 경계를 생성)
  • n_components: 5-10 차원 사용 (성능을 유지하면서 2D 대비 밀도 보존 향상)

클러스터링 워크플로우

밀도 기반 클러스터링을 위해 HDBSCAN을 별도로 설치하세요:

uv pip install hdbscan
import umap
import hdbscan
from sklearn.preprocessing import StandardScaler

# 1. 데이터 전처리
scaled_data = StandardScaler().fit_transform(data)

# 2. 클러스터링 최적화 매개변수로 UMAP
reducer = umap.UMAP(
    n_neighbors=30,
    min_dist=0.0,
    n_components=10,  # 더 나은 밀도 보존을 위해 2보다 높게
    metric='euclidean',
    random_state=42
)
embedding = reducer.fit_transform(scaled_data)

# 3. HDBSCAN 클러스터링 적용
clusterer = hdbscan.HDBSCAN(
    min_cluster_size=15,
    min_samples=5,
    metric='euclidean'
)
labels = clusterer.fit_predict(embedding)

# 4. 평가
from sklearn.metrics import adjusted_rand_score
score = adjusted_rand_score(true_labels, labels)
print(f"Adjusted Rand Score: {score:.3f}")
print(f"클러스터 수: {len(set(labels)) - (1 if -1 in labels else 0)}")
print(f"노이즈 점: {sum(labels == -1)}")

클러스터링 후 시각화

# 시각화를 위한 2D 임베딩 생성 (클러스터링과 분리)
vis_reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, n_components=2, random_state=42)
vis_embedding = vis_reducer.fit_transform(scaled_data)

# 클러스터 레이블로 플롯
import matplotlib.pyplot as plt
plt.scatter(vis_embedding[:, 0], vis_embedding[:, 1], c=labels, cmap='Spectral', s=5)
plt.colorbar()
plt.title('UMAP Visualization with HDBSCAN Clusters')
plt.show()

중요 주의 사항: UMAP은 밀도를 완전히 보존하지 않으며 인위적인 클러스터 분할을 생성할 수 있습니다. 항상 결과 클러스터를 검증하고 탐색하세요.

새 데이터 변환

UMAP은 transform() 메서드를 통해 새 데이터의 전처리를 가능하게 하여, 훈련된 모델이 보지 못한 데이터를 학습된 임베딩 공간에 투영할 수 있도록 합니다.

기본 변환 사용법

# 훈련 데이터에 피팅
trans = umap.UMAP(n_neighbors=15, random_state=42).fit(X_train)

# 테스트 데이터 변환
test_embedding = trans.transform(X_test)

머신러닝 파이프라인과 통합

from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import umap

# 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2)

# 전처리
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# UMAP 훈련
reducer = umap.UMAP(n_components=10, random_state=42)
X_train_embedded = reducer.fit_transform(X_train_scaled)
X_test_embedded = reducer.transform(X_test_scaled)

# 임베딩에 분류기 훈련
clf = SVC()
clf.fit(X_train_embedded, y_train)
accuracy = clf.score(X_test_embedded, y_test)
print(f"테스트 정확도: {accuracy:.3f}")

중요 고려 사항

데이터 일관성: transform 메서드는 고차원 공간의 전체 분포가 훈련 데이터와 테스트 데이터 간에 일관적이라고 가정합니다. 이 가정이 실패할 경우 Parametric UMAP 사용을 고려하세요.

성능: 변환 작업은 효율적이지만(보통 1초 미만), 초기 호출은 Numba JIT 컴파일로 인해 느릴 수 있습니다.

Scikit-learn 호환성: UMAP은 표준 sklearn 규칙을 따르며 파이프라인에서 작동합니다. 최근 0.5.x 릴리스에서는 특성 이름 지원과 현재 scikit-learn 검증 API와의 호환성도 개선되었습니다:

from sklearn.pipeline import Pipeline

pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('umap', umap.UMAP(n_components=10)),
    ('classifier', SVC())
])

pipeline.fit(X_train, y_train)
predictions = pipeline.predict(X_test)
feature_names = pipeline.named_steps['umap'].get_feature_names_out()

고급 기능

파라메트릭 UMAP

파라메트릭 UMAP은 직접적인 임베딩 최적화를 학습된 신경망 매핑 함수로 대체합니다.

표준 UMAP과의 주요 차이점:

  • TensorFlow/Keras를 사용하여 인코더 네트워크를 훈련
  • 새 데이터의 효율적인 변환 가능
  • 디코더 네트워크를 통한 재구성 지원 (역변환)
  • 사용자 정의 아키텍처 허용 (이미지용 CNN, 시퀀스용 RNN)

설치:

uv pip install "umap-learn[parametric-umap]==0.5.12"
# TensorFlow 기반 Parametric UMAP 추가 기능을 설치합니다.

기본 사용법:

from umap.parametric_umap import ParametricUMAP

# 기본 아키텍처 (3층 100 뉴런 완전 연결 네트워크)
embedder = ParametricUMAP()
embedding = embedder.fit_transform(data)

# 새 데이터 효율적으로 변환
new_embedding = embedder.transform(new_data)

사용자 정의 아키텍처:

import tensorflow as tf

# 사용자 정의 인코더 정의
encoder = tf.keras.Sequential([
    tf.keras.layers.InputLayer(shape=(input_dim,)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(2)  # 출력 차원
])

embedder = ParametricUMAP(encoder=encoder, dims=(input_dim,))
embedding = embedder.fit_transform(data)

지속성: 일반 pickle 대신 내장된 Keras 인식 메서드로 Parametric UMAP을 저장하세요:

embedder.save("parametric_umap_model", exclude_raw_data=True)

from umap.parametric_umap import load_ParametricUMAP
loaded = load_ParametricUMAP("parametric_umap_model")
new_embedding = loaded.transform(new_data)

최근 0.5.12 수정 사항에는 Parametric UMAP 재훈련 안정성 개선과 메트릭-그래디언트 수정이 포함되어 있으므로 신경망 워크플로우에는 고정된 현재 릴리스를 선호하세요.

파라메트릭 UMAP을 사용해야 할 때:

  • 훈련 후 새 데이터의 효율적인 변환이 필요할 때
  • 재구성 기능(역변환)이 필요할 때
  • UMAP과 오토인코더를 결합하려 할 때
  • 특수 아키텍처의 이점을 얻는 복잡한 데이터 유형(이미지, 시퀀스)을 작업할 때

역변환

역변환을 사용하면 저차원 임베딩에서 고차원 데이터를 재구성할 수 있습니다.

기본 사용법:

reducer = umap.UMAP()
embedding = reducer.fit_transform(data)

# 임베딩 좌표에서 고차원 데이터 재구성
reconstructed = reducer.inverse_transform(embedding)

중요한 제한 사항:

  • 계산 비용이 많이 드는 연산
  • 임베딩의 볼록 껍질 외부에서는 제대로 작동하지 않음
  • 클러스터 사이의 간격이 있는 영역에서는 정확도가 떨어짐

예: 임베딩 공간 탐색:

import numpy as np

# 임베딩 공간에 그리드 점 생성
x = np.linspace(embedding[:, 0].min(), embedding[:, 0].max(), 10)
y = np.linspace(embedding[:, 1].min(), embedding[:, 1].max(), 10)
xx, yy = np.meshgrid(x, y)
grid_points = np.c_[xx.ravel(), yy.ravel()]

# 그리드에서 샘플 재구성
reconstructed_samples = reducer.inverse_transform(grid_points)

AlignedUMAP

공유 좌표계가 필요한 시간적 또는 관련 데이터 세트(시계열 실험, 배치)의 경우, umap.AlignedUMAP().fit(datasets, relations=relations)을 사용하세요. 여기서 relations는 연속적인 데이터 세트 간의 샘플 인덱스를 매핑하며 의미 있는 정렬을 위해 필요합니다. 매개변수, 메서드 및 작업 예제는 references/api_reference.md의 "AlignedUMAP Class" 및 "Usage Examples"에 있습니다.

재현성

재현 가능한 결과를 보장하려면 항상 random_state 매개변수를 설정하세요:

reduc

...

[번역을 위해 잘림]

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

관련 스킬