ds-utils-unsupervised
Unsupervised clustering analysis, optimal cluster count selection, and 2D scatter plots (PCA, t-SNE, UMAP). Use for elbow loss curves, silhouette score sweeps…
от idanmoradarthas★ 37 звёзд на GitHub
Установить ds-utils-unsupervised в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
ds-utils-unsupervised
Tools for choosing cluster count, diagnosing clustering quality using silhouette, cardinality and magnitude analysis, and visualizing cluster assignments in 2D scatter plots.
Purpose
ds_utils.unsupervised provides diagnostics for centroid-based clustering (specifically scikit-learn KMeans) and 2D scatter visualization of clustering results. It helps data scientists determine the optimal number of clusters $k$ via custom distance loss sweeps and silhouette score sweeps, validate cluster separation with per-sample silhouette coefficients, evaluate cluster compactness and stability using cardinality (number of points) and magnitude (total distance to centroid), and visualize cluster assignments via PCA, t-SNE, or UMAP reduction in matplotlib or Plotly.
- When to use: Selecting $k$ with the elbow method, validating separation with a silhouette plot, verifying that clusters are balanced and compact, spotting anomalous or diffuse clusters, and creating 2D scatter plots of clustering results.
- When NOT to use: For supervised classification/regression metrics (use ds-utils-metrics), PCA explained variance (use ds-utils-preprocess), or using the 2D reduction coordinates as clustering input (they are for display only).
Prerequisites
- Python 3.11 or higher.
- data-science-utils package installed (pip install data-science-utils).
- Core dependencies: numpy, pandas, scikit-learn, scipy, matplotlib, plotly.
- Optional: umap-learn for UMAP reduction (pip install data-science-utils[umap]).
Instructions
Task-to-Approach Map
| Clustering Diagnostic Task | Function | Required Inputs | Output |
|---|---|---|---|
| Determine optimal cluster count ($k$) | plot_loss_vs_cluster_number |
X, k_min, k_max, distance_function |
Matplotlib Axes |
| Compare average silhouette scores across $k$ | plot_silhouette_score_vs_cluster_number |
X, optional k_range |
Matplotlib Axes |
| Validate separation and spot misassigned samples | plot_silhouette_analysis |
X, labels |
Matplotlib Axes |
| Check balance / points per cluster | plot_cluster_cardinality |
labels_ |
Matplotlib Axes |
| Measure compactness per cluster | plot_cluster_magnitude |
X, labels_, cluster_centers_, distance_func |
Matplotlib Axes |
| Identify anomalous or diffuse clusters | plot_magnitude_vs_cardinality |
X, labels_, cluster_centers_, distance_func |
Matplotlib Axes |
| Visualize clusters in 2D (matplotlib) | plot_clusters |
X, cluster_labels, optional cluster_centers |
Matplotlib Axes |
| Visualize clusters in 2D (Plotly) | plot_clusters_plotly |
X, cluster_labels, optional cluster_centers |
Plotly Figure |
Full signatures, parameter options, and common mistakes are documented in references/api_reference.md.
End-to-End Clustering Workflow
Follow this sequence to go from unscaled features to a validated clustering model:
Unlabeled Data Matrix
│
Prepare Features
(missing values & StandardScaler)
│
▼
Sweep k and Evaluate Diagnostics
(plot_loss_vs_cluster_number,
plot_silhouette_score_vs_cluster_number,
plot_silhouette_analysis)
│
▼
Fit Final KMeans(n_clusters=k)
│
┌───────────────┴───────────────┐
▼ ▼
Check Balance Check Compactness
(plot_cluster_cardinality) (plot_cluster_magnitude)
│ │
└───────────────┬───────────────┘
▼
Diagnose Cluster Consistency
(plot_magnitude_vs_cardinality)
│
▼
Visualize Cluster Assignments
(plot_clusters / plot_clusters_plotly)
│
▼
Interpret Cluster Profiles
(groupby mean on original features)
Inputs you need
The steps below assume:
- An input DataFrame
Xcontaining numeric feature columns without target labels. - A decision on feature selection: which columns belong in the clustering feature space.
import pandas as pd
# Load your unlabeled feature matrix (replace with your data)
df = pd.read_csv("your_dataset")
X = df.select_dtypes("number") # select numeric clustering features
Step 1: Prepare features
Question: what is the scale spread across features, are there missing values, and how should features be standardized?
from sklearn.preprocessing import StandardScaler
# Check missingness and scale disparities
print("Missingness ratio per feature:\n", X.isna().mean())
print("Scale spread (mean and std):\n", X.describe().loc"mean", "std")
# Impute or drop missing values, then standardize
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/api_reference.md
FAQ
Что делает скилл ds-utils-unsupervised?
Unsupervised clustering analysis, optimal cluster count selection, and 2D scatter plots (PCA, t-SNE, UMAP). Use for elbow loss curves, silhouette score sweeps over k, silhouette plots, cluster cardinality, centroid magnitude, and cluster assignments. Do NOT use for supervised classification metrics or text binarization.
Как установить скилл ds-utils-unsupervised?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ds-utils-unsupervised запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
AnthropicCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
discernment-nudge
AnthropicAfter you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
data-consolidate
AnthropicJoins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
inspection-to-capa
AnthropicRuns the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…