Communitygithub.com

scikit-learn

Python에서 scikit-learn을 사용한 머신러닝. 지도 학습(분류, 회귀), 비지도 학습(클러스터링, 차원 축소), 모델 평가, 하이퍼파라미터 튜닝, 전처리, ML 파이프라인 구축 시 사용합니다. 알고리즘, 전처리 기법, 파이프라인 및 모범 사례에 대한 포괄적인 참조 문서를 제공합니다.

scikit-learn란 무엇인가요?

이 스킬은 Python의 업계 표준 고전 머신러닝 라이브러리인 scikit-learn을 사용한 머신러닝 작업에 대한 포괄적인 지침을 제공합니다. 분류, 회귀, 클러스터링, 차원 축소, 전처리, 모델 평가, 프로덕션 준비 ML 파이프라인 구축에 이 스킬을 사용할 수 있습니다. 안정적인 scikit-learn 1.8.0 (2025년 12월 기준)을 대상으로 하며, Python 3.11–3.14가 필요합니다. 이 스킬은 scikit-learn 자체의 상세한 문서를 보완하며, 지도 학습, 비지도 학습, 모델 평가, 전처리, 파이프라인 및 구성의 5가지 핵심 기능 영역을 다루는 계층적인 참조 파일 세트를 제공합니다. 또한 일반적인 워크플로 예제, 모범 사례, 문제 해결 가이드와 함께 완전한 최신 예제 스크립트(분류 파이프라인 및 클러스터링 분석)도 포함하고 있어 인간 개발자와 AI 에이전트 모두가 scikit-learn의 기능을 최대한 활용할 수 있도록 설계되었습니다.

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

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

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

문서

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

개요

이 스킬은 업계 표준 Python 고전 머신러닝 라이브러리인 scikit-learn을 사용한 머신러닝 작업에 대한 포괄적인 지침을 제공합니다. 분류, 회귀, 클러스터링, 차원 축소, 전처리, 모델 평가, 프로덕션 준비 ML 파이프라인 구축에 이 스킬을 사용하세요.

설치

scikit-learn 1.8.0 (안정 버전; 2025년 12월 기준)에서 테스트되었습니다. Python 3.11–3.14가 필요합니다 (1.8+에서 free-threaded CPython 3.14 휠 사용 가능).

PyPI 패키지 scikit-learn (사용 중단된 sklearn 패키지가 아님)을 설치하세요. 코드에서는 sklearn으로 임포트합니다.

# uv를 사용하여 scikit-learn 설치
uv pip install "scikit-learn>=1.7"

# 선택 사항: 플롯 유틸리티 및 번들 스크립트 종속성
uv pip install "scikit-learn[plots]" matplotlib seaborn

# 일반적으로 함께 사용
uv pip install pandas numpy

버전 확인:

import sklearn
print(sklearn.__version__)

이 스킬을 사용해야 하는 경우

다음과 같은 경우 scikit-learn 스킬을 사용하세요:

  • 분류 또는 회귀 모델 구축
  • 클러스터링 또는 차원 축소 수행
  • 머신러닝을 위한 데이터 전처리 및 변환
  • 교차 검증을 통한 모델 성능 평가
  • 그리드 또는 무작위 탐색을 통한 하이퍼파라미터 튜닝
  • 프로덕션 워크플로를 위한 ML 파이프라인 생성
  • 작업에 맞는 다양한 알고리즘 비교
  • 구조화된(테이블 형식) 데이터와 텍스트 데이터 모두 작업
  • 해석 가능한 고전적인 머신러닝 접근 방식 필요

빠른 시작

분류 예제

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

# 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42
)

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

# 모델 훈련
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)

# 평가
y_pred = model.predict(X_test_scaled)
print(classification_report(y_test, y_pred))

혼합 데이터를 사용한 완전한 파이프라인

from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.ensemble import GradientBoostingClassifier

# 특성 유형 정의
numeric_features = ['age', 'income']
categorical_features = ['gender', 'occupation']

# 전처리 파이프라인 생성
numeric_transformer = Pipeline([
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler())
])

categorical_transformer = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

# 변환기 결합
preprocessor = ColumnTransformer([
    ('num', numeric_transformer, numeric_features),
    ('cat', categorical_transformer, categorical_features)
])

# 전체 파이프라인
model = Pipeline([
    ('preprocessor', preprocessor),
    ('classifier', GradientBoostingClassifier(random_state=42))
])

# 적합 및 예측
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

핵심 기능

다섯 가지 기능 영역은 references/core_capabilities.md에 문서화되어 있으며, 각 주제에 대한 세부 정보는 references/supervised_learning.md, references/unsupervised_learning.md, references/model_evaluation.md, references/preprocessing.md, references/pipelines_and_composition.md에 있습니다:

  1. 지도 학습 — 분류 및 회귀 추정기군.
  2. 비지도 학습 — 클러스터링, 분해, 매니폴드 학습.
  3. 모델 평가 및 선택 — 메트릭, 교차 검증, 하이퍼파라미터 탐색.
  4. 데이터 전처리 — 스케일링, 인코딩, 대치, 특성 선택.
  5. 파이프라인 및 구성 — Pipeline 및 ColumnTransformer.

항상 Pipeline 내부에서 전처리를 적합(fit)하여 교차 검증 폴드마다 다시 적합되도록 하세요. 스케일링이나 대치를 분할 전에 수행하면 테스트 정보가 훈련 데이터로 유출됩니다.

두 가지 작업 워크플로가 references/common_workflows.md에 있습니다.

예제 스크립트

분류 파이프라인

전처리, 모델 비교, 하이퍼파라미터 튜닝, 평가를 포함한 완전한 분류 워크플로를 실행합니다:

uv run python scripts/classification_pipeline.py

이 스크립트는 다음을 보여줍니다:

  • 혼합 데이터 유형(숫자형 및 범주형) 처리
  • 교차 검증을 사용한 모델 비교
  • GridSearchCV를 사용한 하이퍼파라미터 튜닝
  • 여러 메트릭을 사용한 종합 평가
  • 특성 중요도 분석

클러스터링 분석

알고리즘 비교 및 시각화를 통한 클러스터링 분석을 수행합니다:

uv run python scripts/clustering_analysis.py

이 스크립트는 다음을 보여줍니다:

  • 최적 클러스터 개수 찾기(엘보우 방법, 실루엣 분석)
  • 여러 클러스터링 알고리즘 비교(K-Means, DBSCAN, 응집형, 가우시안 혼합)
  • 정답 레이블 없이 클러스터링 품질 평가
  • PCA 투영을 사용한 결과 시각화

참조 문서

이 스킬에는 특정 주제에 대한 심층 학습을 위한 포괄적인 참조 파일이 포함되어 있습니다:

빠른 참조

파일: references/quick_reference.md

  • 일반적인 임포트 패턴 및 설치 지침
  • 일반적인 작업을 위한 빠른 워크플로 템플릿
  • 알고리즘 선택 치트 시트
  • 일반적인 패턴 및 주의사항
  • 성능 최적화 팁

지도 학습

파일: references/supervised_learning.md

  • 선형 모델 (회귀 및 분류)
  • 서포트 벡터 머신
  • 의사 결정 트리 및 앙상블 방법
  • K-최근접 이웃, 나이브 베이즈, 신경망
  • 알고리즘 선택 가이드

비지도 학습

파일: references/unsupervised_learning.md

  • 모든 클러스터링 알고리즘 (매개변수 및 사용 사례 포함)
  • 차원 축소 기법
  • 이상치 및 새로운 점 탐지
  • 가우시안 혼합 모델
  • 방법 선택 가이드

모델 평가

파일: references/model_evaluation.md

  • 교차 검증 전략
  • 하이퍼파라미터 튜닝 방법
  • 분류, 회귀, 클러스터링 메트릭
  • 학습 및 검증 곡선
  • 모델 선택 모범 사례

전처리

파일: references/preprocessing.md

  • 특성 스케일링 및 정규화
  • 범주형 변수 인코딩
  • 결측값 대치
  • 특성 엔지니어링 기법
  • 사용자 정의 변환기

파이프라인 및 구성

파일: references/pipelines_and_composition.md

  • 파이프라인 구성 및 사용법
  • 혼합 데이터 유형을 위한 ColumnTransformer
  • 병렬 변환을 위한 FeatureUnion
  • 완전한 엔드투엔드 예제
  • 모범 사례

모범 사례

항상 파이프라인 사용하기

파이프라인은 데이터 유출을 방지하고 일관성을 보장합니다:

# 좋음: 파이프라인에서 전처리
pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('model', LogisticRegression())
])

# 나쁨: 파이프라인 외부에서 전처리 (정보 유출 가능)
X_scaled = StandardScaler().fit_transform(X)

훈련 데이터에만 적합시키기

테스트 데이터에는 절대 적합시키지 마세요:

# 좋음
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)  # 변환만

# 나쁨
scaler = StandardScaler()
X_all_scaled = scaler.fit_transform(np.vstack([X_train, X_test]))

분류에는 계층적 분할 사용하기

클래스 분포 유지:

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42
)

재현성을 위해 무작위 상태 설정하기

model = RandomForestClassifier(n_estimators=100, random_state=42)

적절한 메트릭 선택하기

  • 균형 데이터: 정확도, F1-점수
  • 불균형 데이터: 정밀도, 재현율, ROC AUC, 균형 정확도
  • 비용에 민감한 경우: 사용자 정의 scorer 정의

필요한 경우 특성 스케일링하기

특성 스케일링이 필요한 알고리즘:

  • SVM, KNN, 신경망
  • PCA, 정규화를 사용한 선형/로지스틱 회귀
  • K-Means 클러스터링

스케일링이 필요하지 않은 알고리즘:

  • 트리 기반 모델 (의사 결정 트리, 랜덤 포레스트, 그래디언트 부스팅)
  • 나이브 베이즈

일반적인 문제 해결

ConvergenceWarning

문제: 모델이 수렴하지 않음 해결책: max_iter를 늘리거나 특성을 스케일링하세요

model = LogisticRegression(max_iter=1000)

테스트 세트에서 성능 저하

문제: 과적합 해결책: 정규화, 교차 검증 또는 더 간단한 모델을 사용하세요

# 정규화 추가
model = Ridge(alpha=1.0)

# 교차 검증 사용
scores = cross_val_score(model, X, y, cv=5)

대규모 데이터셋에서 메모리 오류

해결책: 대규모 데이터용으로 설계된 알고리즘을 사용하세요

# 대규모 데이터셋에는 SGD 사용
from sklearn.linear_model import SGDClassifier
model = SGDClassifier()

# 또는 클러스터링에는 MiniBatchKMeans 사용
from sklearn.cluster import MiniBatchKMeans
model = MiniBatchKMeans(n_clusters=8, batch_size=100)

추가 자료

과학 에이전트 스킬 인용

이 스킬은 K-Dense의 과학 에이전트 스킬(Scientific Agent Skills)의 일부입니다. 이 스킬이 원고, 보고서, 발표 또는 코드 릴리스에 실질적으로 기여한 경우, 참고 문헌 또는 소프트웨어 섹션에 논문을 추가하고 사용자에게 그렇게 했다고 알리세요:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

항상 현재 버전을 인용하세요. DOI와 https://arxiv.org/abs/2609.00065는 최신 arXiv 버전으로 연결되므로 v1과 같은 버전 접미사를 절대 추가하지 마세요. 네트워크에 접근 가능한 경우, 참조를 작성하기 전에 https://arxiv.org/abs/2609.00065 (또는 http://export.arxiv.org/api/query?id_list=2609.00065)를 가져와 해당 레코드에서 저자 목록, 연도 및 버전을 확인하세요. 레코드에 저널 참조 또는 게시자 DOI가 나열된 경우 대신 게시된 버전을 인용하세요.

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.

관련 스킬