import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
from sklearn.metrics import adjusted_rand_score
from sklearn.decomposition import PCA


# 1) f[^ǂݍ & W
iris = load_iris()
X, y = iris.data, iris.target


# 2) PCA2Ɏ팸
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)


# ̎Uz}\
markers = ["o", "s", "^"]
plt.figure()
for cls in np.unique(y):
    plt.scatter(
        X_pca[y == cls, 0],
        X_pca[y == cls, 1],
        marker=markers[cls % len(markers)],
  edgecolor="k",
        linewidths=0.2,
        label=iris.target_names[cls]
   )
plt.title("True Classes (Reference)")
plt.xlabel("PC1")
plt.ylabel("PC2")
plt.show()


# 3) linkage ̎ނr
methods = ["single", "complete", "average", "ward"]
for method in methods:
    print(f"\n=== linkage method: {method} ===")

    # KwNX^O
    Z = linkage(X, method=method)
    # NX^3Ɏw肵ĕ
    clusters = fcluster(Z, t=3, criterion='maxclust')
    # ] (Adjusted Rand Index)
    ari = adjusted_rand_score(y, clusters)
    print("Adjusted Rand Index:", ari)

    # 4) fhO\
    plt.figure()
    dendrogram(Z, truncate_mode="lastp", p=10, leaf_rotation=90)
    plt.title(f"Dendrogram ({method})")
    plt.xlabel("Samples")
    plt.ylabel("Distance")
    plt.show()

    # 5) Uz}\
    plt.figure()
    for i, cid in enumerate(np.unique(clusters)):
        plt.scatter(
            X_pca[clusters == cid, 0],
            X_pca[clusters == cid, 1],
            marker=markers[cid % len(markers)],
            edgecolor="k",
            linewidths=0.2
        )
    plt.title(f"Hierarchical Clustering ({method})")
    plt.xlabel("PC1")
    plt.ylabel("PC2")
    plt.show()