mcpField
C
clustering-analyzer

clustering-analyzer

github.com/dkyazzentwatwaデータ・データベース12462 回インストール29 週間前に更新
リポジトリ

clustering-analyzer について

clustering-analyzerは、表形式データをクラスタリングするPythonツールとコマンドラインプログラムです。K-Means、DBSCAN、階層的手法に対応し、評価、可視化、ラベル付きデータの出力で、グループや潜在的な異常の分析を支援します。

主な機能

  1. 01K-Means、DBSCAN、階層的クラスタリング
  2. 02エルボー法によるクラスタ数の探索
  3. 03シルエットスコアによる評価
  4. 04クラスタ図、樹形図、エルボー曲線の作成
  5. 05ラベルとクラスタ概要の出力
  6. 06欠損値の補完と特徴量のスケーリング

活用シーン

  1. 01顧客データのセグメント化
  2. 02取引データの潜在的な異常の検出
  3. 03文書間の関係の分析
  4. 04可視化によるクラスタ結果の比較

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/dkyazzentwatwa/chatgpt-skills --skill clustering-analyzer

インストール後、Claude Code で/clustering-analyzerを入力して読み込まれたか確認します。

同梱ファイルscripts/clustering_analyzer.pyscripts/requirements.txt

詳細

クラスタリングアナライザー

複数のアルゴリズムを使用してデータを分析・クラスタリングし、可視化と評価を行います。

特徴

  • K-Means:エルボー法による分割ベースのクラスタリング
  • DBSCAN:任意の形状に対応する密度ベースのクラスタリング
  • 階層型:デンドログラムを使用した凝集型クラスタリング
  • 評価:シルエットスコア、クラスター統計
  • 可視化:2D/3D プロット、デンドログラム、エルボー曲線
  • エクスポート:ラベル付きデータ、クラスターの概要

クイックスタート

from clustering_analyzer import ClusteringAnalyzer

analyzer = ClusteringAnalyzer()
analyzer.load_csv("customers.csv")

# K-Means clustering
result = analyzer.kmeans(n_clusters=3)
print(f"Silhouette Score: {result['silhouette_score']:.3f}")

# Visualize
analyzer.plot_clusters("clusters.png")

CLI の使用方法

# K-Means clustering
python clustering_analyzer.py --input data.csv --method kmeans --clusters 3

# Find optimal clusters (elbow method)
python clustering_analyzer.py --input data.csv --method kmeans --find-optimal

# DBSCAN clustering
python clustering_analyzer.py --input data.csv --method dbscan --eps 0.5 --min-samples 5

# Hierarchical clustering
python clustering_analyzer.py --input data.csv --method hierarchical --clusters 4

# Generate plots
python clustering_analyzer.py --input data.csv --method kmeans --clusters 3 --plot clusters.png

# Export labeled data
python clustering_analyzer.py --input data.csv --method kmeans --clusters 3 --output labeled.csv

# Select specific columns
python clustering_analyzer.py --input data.csv --columns age,income,spending --method kmeans --clusters 3

API リファレンス

ClusteringAnalyzer クラス
class ClusteringAnalyzer:
    def __init__(self)

    # Data loading
    def load_csv(self, filepath: str, columns: list = None) -> 'ClusteringAnalyzer'
    def load_dataframe(self, df: pd.DataFrame, columns: list = None) -> 'ClusteringAnalyzer'

    # Clustering methods
    def kmeans(self, n_clusters: int, **kwargs) -> dict
    def dbscan(self, eps: float = 0.5, min_samples: int = 5) -> dict
    def hierarchical(self, n_clusters: int, linkage: str = "ward") -> dict

    # Optimal clusters
    def find_optimal_clusters(self, max_k: int = 10) -> dict
    def elbow_plot(self, output: str, max_k: int = 10) -> str

    # Evaluation
    def silhouette_score(self) -> float
    def cluster_statistics(self) -> dict

    # Visualization
    def plot_clusters(self, output: str, dimensions: list = None) -> str
    def plot_dendrogram(self, output: str) -> str
    def plot_silhouette(self, output: str) -> str

    # Export
    def get_labels(self) -> list
    def to_dataframe(self) -> pd.DataFrame
    def save_labeled(self, output: str) -> str

クラスタリング手法

K-Means

グループ数が既知で、球状のクラスターに最適です。

result = analyzer.kmeans(n_clusters=3)

# Returns:
{
    "labels": [0, 1, 2, 0, ...],
    "n_clusters": 3,
    "silhouette_score": 0.65,
    "inertia": 1234.56,
    "cluster_sizes": {0: 150, 1: 200, 2: 100},
    "centroids": [[...], [...], [...]]
}
DBSCAN

任意の形状のクラスターに最適です。

result = analyzer.dbscan(eps=0.5, min_samples=5)

# Returns:
{
    "labels": [0, 0, 1, -1, ...],  # -1 = noise
    "n_clusters": 3,
    "n_noise": 15,
    "silhouette_score": 0.58,
    "cluster_sizes": {0: 150, 1: 200, 2: 100}
}
階層型(凝集型)

クラスターの階層構造を把握するのに最適です。

result = analyzer.hierarchical(n_clusters=4, linkage="ward")

# Returns:
{
    "labels": [0, 1, 2, 3, ...],
    "n_clusters": 4,
    "silhouette_score": 0.62,
    "cluster_sizes": {0: 100, 1: 150, 2: 120, 3: 80}
}

最適なクラスター数の特定

エルボー法
optimal = analyzer.find_optimal_clusters(max_k=10)

# Returns:
{
    "optimal_k": 4,
    "inertias": [1000, 800, 500, 300, 280, ...],
    "silhouettes": [0.5, 0.55, 0.6, 0.65, 0.63, ...]
}
エルボープロット
analyzer.elbow_plot("elbow.png", max_k=10)

慣性とクラスター数の関係を示すプロットを生成します。

クラスター統計

stats = analyzer.cluster_statistics()

# Returns:
{
    "n_clusters": 3,
    "cluster_sizes": {0: 150, 1: 200, 2: 100},
    "cluster_means": {
        0: {"age": 25.5, "income": 45000, ...},
        1: {"age": 45.2, "income": 75000, ...},
        2: {"age": 35.1, "income": 55000, ...}
    },
    "cluster_std": {
        0: {"age": 5.2, "income": 8000, ...},
        ...
    },
    "overall_silhouette": 0.65
}

可視化

クラスタープロット
# 2D plot (uses first 2 features or PCA)
analyzer.plot_clusters("clusters_2d.png")

# Specify dimensions
analyzer.plot_clusters("clusters.png", dimensions=["age", "income"])
デンドログラム
# For hierarchical clustering
analyzer.hierarchical(n_clusters=4)
analyzer.plot_dendrogram("dendrogram.png")
シルエットプロット
analyzer.plot_silhouette("silhouette.png")

各サンプルのシルエット係数を表示します。

結果のエクスポート

ラベルの取得
labels = analyzer.get_labels()
# [0, 1, 2, 0, 1, ...]
ラベル付きデータの保存
analyzer.save_labeled("labeled_data.csv")
# Original data + cluster_label column
DataFrame 全体の取得
df = analyzer.to_dataframe()
# DataFrame with cluster_label column

ワークフローの例

顧客セグメンテーション
analyzer = ClusteringAnalyzer()
analyzer.load_csv("customers.csv", columns=["age", "income", "spending_score"])

# Find optimal number of segments
optimal = analyzer.find_optimal_clusters(max_k=8)
print(f"Optimal segments: {optimal['optimal_k']}")

# Cluster with optimal k
result = analyzer.kmeans(n_clusters=optimal['optimal_k'])

# Get segment characteristics
stats = analyzer.cluster_statistics()
for cluster_id, means in stats["cluster_means"].items():
    print(f"\nSegment {cluster_id}:")
    for feature, value in means.items():
        print(f"  {feature}: {value:.2f}")

# Save segmented data
analyzer.save_labeled("customer_segments.csv")
DBSCAN による異常検知
analyzer = ClusteringAnalyzer()
analyzer.load_csv("transactions.csv", columns=["amount", "frequency"])

# DBSCAN identifies noise points as potential anomalies
result = analyzer.dbscan(eps=0.3, min_samples=10)

print(f"Found {result['n_noise']} potential anomalies")

# Get anomalous records
df = analyzer.to_dataframe()
anomalies = df[df["cluster_label"] == -1]
ドキュメントのクラスタリング
# After TF-IDF transformation
analyzer = ClusteringAnalyzer()
analyzer.load_dataframe(tfidf_matrix)

# Hierarchical clustering to see document relationships
result = analyzer.hierarchical(n_clusters=5)
analyzer.plot_dendrogram("doc_dendrogram.png")

データの前処理

アナライザーは以下を自動的に行います。

  • 欠損値の処理(補完)
  • 特徴量のスケーリング(標準化)
  • 可視化のための次元削減(PCA)

カスタム前処理を行う場合:

from sklearn.preprocessing import StandardScaler

# Preprocess manually
df = pd.read_csv("data.csv")
scaler = StandardScaler()
df_scaled = pd.DataFrame(scaler.fit_transform(df), columns=df.columns)

# Load preprocessed data
analyzer.load_dataframe(df_scaled)

依存関係

  • scikit-learn>=1.3.0
  • pandas>=2.0.0
  • numpy>=1.24.0
  • matplotlib>=3.7.0
  • scipy>=1.10.0

コメント