OMG-01's picture
Update app.py
1805335 verified
Raw History Blame Contribute Delete
10.3 kB
import gradio as gr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D
# 別ファイルからRG-SCアルゴリズムのコアロジックをインポート
from rg_sc import run_rgsc
def process_and_cluster(file_obj, k_nn, max_k):
"""
アップロードされたCSVファイルを処理し、クラスタリングを実行し、
結果のファイルと、データの次元数に応じた最適なプロットを返すGradioのメイン関数。
"""
if file_obj is None:
raise gr.Error("No file uploaded. Please upload a CSV file.")
try:
# アップロードされたファイルをDataFrameとして読み込む
df = pd.read_csv(file_obj.name)
except Exception as e:
raise gr.Error(f"Failed to read the file: {e}")
# ---- カラム名の問題を解決するロジック ----
# DataFrameから数値型のカラムのみを自動で選択する。
df_numeric = df.select_dtypes(include=np.number)
if df_numeric.empty:
raise gr.Error("No numerical columns found in the CSV file. Please provide a file with at least two numerical columns.")
if df_numeric.shape[1] < 2:
raise gr.Error("Clustering visualization requires at least 2 numerical columns.")
print(f"Found {df_numeric.shape[1]} numerical columns for clustering: {list(df_numeric.columns)}")
# データをNumpy配列に変換し、標準化
X = df_numeric.values
X_scaled = StandardScaler().fit_transform(X)
# RG-SCアルゴリズムを実行
labels, _, estimated_k = run_rgsc(X_scaled, int(k_nn), int(max_k))
# ---- 結果のファイルを作成 ----
df_result = df.copy()
df_result['cluster_label'] = labels
result_csv_path = "/tmp/clustered_result.csv"
df_result.to_csv(result_csv_path, index=False)
# ---- 結果のプロットを作成 (次元数に応じて分岐) ----
n_features = X.shape[1]
fig = plt.figure(figsize=(9, 9))
# --- カラーマップとラベルの設定 ---
unique_labels = sorted(list(set(labels)))
n_clusters = len(unique_labels)
colors = cm.get_cmap('nipy_spectral', n_clusters) if n_clusters > 1 else cm.get_cmap('gray')
# --- プロットロジック ---
if n_features == 2:
# ** 2次元の場合: 2D散布図 **
ax = fig.add_subplot(111)
for k_idx, k in enumerate(unique_labels):
mask = (labels == k)
color_val = k_idx / (n_clusters - 1 if n_clusters > 1 else 1)
ax.scatter(X[mask, 0], X[mask, 1],
color=colors(color_val),
label=f'Cluster {k}', s=50, alpha=0.8, edgecolors='k')
ax.set_xlabel(df_numeric.columns[0])
ax.set_ylabel(df_numeric.columns[1])
ax.set_title(f"2D Clustering Result (k={estimated_k})", fontsize=16)
elif n_features == 3:
# ** 3次元の場合: 3D散布図 **
ax = fig.add_subplot(111, projection='3d')
for k_idx, k in enumerate(unique_labels):
mask = (labels == k)
color_val = k_idx / (n_clusters - 1 if n_clusters > 1 else 1)
ax.scatter(X[mask, 0], X[mask, 1], X[mask, 2],
color=colors(color_val),
label=f'Cluster {k}', s=50, alpha=0.8, edgecolors='k')
ax.set_xlabel(df_numeric.columns[0])
ax.set_ylabel(df_numeric.columns[1])
ax.set_zlabel(df_numeric.columns[2])
ax.set_title(f"3D Clustering Result (k={estimated_k})", fontsize=16)
ax.view_init(elev=20., azim=45) # 見やすい角度に調整
else: # n_features > 3
# ** 4次元以上の場合: PCAによる次元削減プロット **
ax = fig.add_subplot(111)
# PCAで2次元に削減
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
for k_idx, k in enumerate(unique_labels):
mask = (labels == k)
color_val = k_idx / (n_clusters - 1 if n_clusters > 1 else 1)
ax.scatter(X_pca[mask, 0], X_pca[mask, 1],
color=colors(color_val),
label=f'Cluster {k}', s=50, alpha=0.8, edgecolors='k')
explained_variance = pca.explained_variance_ratio_.sum() * 100
ax.set_xlabel("Principal Component 1")
ax.set_ylabel("Principal Component 2")
title = (f"PCA Visualization of {n_features}D Data (k={estimated_k})\n"
f"Explained Variance: {explained_variance:.2f}%")
ax.set_title(title, fontsize=14)
ax.grid(True)
if n_clusters > 0:
ax.legend()
plot_path = "/tmp/clustering_plot.png"
plt.savefig(plot_path)
plt.close(fig)
return result_csv_path, plot_path
# ---- Gradioインターフェースの構築 ----
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# RG-SC: Self-Tuning Robust Spectral Clustering")
# Tabインターフェースを作成
with gr.Tabs():
# --- メインのクラスタリング用タブ ---
with gr.TabItem("Clustering Tool"):
gr.Markdown(
"Upload a CSV file. The RG-SC algorithm will automatically detect all **numerical columns** "
"to perform clustering, estimate the optimal number of clusters, and group the data."
)
with gr.Row():
with gr.Column(scale=1):
file_input = gr.File(label="Upload CSV File")
with gr.Accordion("Advanced Settings (Optional)", open=False):
k_nn_slider = gr.Slider(5, 30, value=10, step=1, label="k-NN",
info="Number of neighbors for graph construction. Larger values consider more global structure.")
max_k_slider = gr.Slider(5, 15, value=10, step=1, label="Max Clusters",
info="The maximum number of clusters to search for.")
submit_button = gr.Button("Run Clustering", variant="primary")
with gr.Column(scale=2):
gr.Markdown("### Results")
plot_output = gr.Image(label="Clustering Result Plot")
file_output = gr.File(label="Download Labeled Data")
submit_button.click(
fn=process_and_cluster,
inputs=[file_input, k_nn_slider, max_k_slider],
outputs=[file_output, plot_output]
)
# サンプルファイルをリポジトリに含めることが前提
gr.Examples(
examples=[
"easy_unlabeled.csv",
"medium_unlabeled.csv",
"hard_unlabeled.csv"
],
inputs=[file_input],
label="Example Datasets (if uploaded to the Space)"
)
# --- アルゴリズム解説用のタブ ---
with gr.TabItem("Algorithm Explanation"):
gr.Markdown("""
## The RG-SC Algorithm: A Deep Dive
**RG-SC (Robust, Gamma, Spectral Clustering)** is a sophisticated unsupervised learning algorithm designed to uncover hidden structures in data, even in complex scenarios where traditional methods fail.
### Core Philosophy: "Connectivity over Proximity"
Unlike K-Means, which relies on distance to a center point, RG-SC is based on **Spectral Clustering**. It transforms the data into a **graph (network)**, where data points are nodes and the connections (edges) between them represent their "similarity" or "connectivity". This allows it to identify clusters of any shape, such as crescents or concentric circles.
---
### The 5 Key Steps
#### **Step 1: Intelligent Graph Construction**
- We build a **Mutual k-NN Graph**. An edge is created between point A and B only if both points consider each other a "close friend". This robust method filters out noise and weak connections, revealing the true skeleton of the data structure.
- It also features a **Self-Tuning Gamma**, which automatically adjusts the sensitivity of similarity calculations based on the data's density. This ensures high performance across different datasets without manual tuning.
#### **Step 2: Mathematical Representation (Graph Laplacian)**
- The graph's structure is converted into a special matrix called the **Normalized Graph Laplacian (`L`)**. This matrix mathematically encodes all the connectivity information of the graph.
#### **Step 3: Optimal k-Estimation via Eigen-analysis**
- We analyze the spectrum of the Laplacian matrix by performing **eigendecomposition**. The **eigenvalues** represent its "cleavability".
- The algorithm automatically finds the most natural number of clusters, `k`, by detecting the largest **eigengap**—a sharp jump in the sequence of sorted eigenvalues. This indicates the most stable point to partition the graph.
#### **Step 4: Transformation to a Simpler Space (Feature Space)**
- The `k` eigenvectors corresponding to the smallest eigenvalues are used as a new set of coordinate axes.
- The original data is projected into this new **feature space**. In this space, complex, intertwined clusters from the original space become simple, well-separated groups.
#### **Step 5: Final Classification**
- Now that the problem has been drastically simplified, a fast and simple algorithm like **K-Means** is applied to the transformed data in the feature space to assign the final cluster labels.
---
This multi-step process makes RG-SC a powerful and versatile tool, capable of handling complex shapes, non-uniform densities, and automatically determining the optimal number of clusters.
""")
# Gradioアプリケーションを起動するための定型句
if __name__ == "__main__":
demo.launch()