import warnings
import numpy as np
from scipy.sparse.csgraph import connected_components
from sklearn.base import clone
from sklearn.decomposition import PCA
from sklearn.manifold import Isomap
from sklearn.neighbors import KNeighborsClassifier, kneighbors_graph
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from common import load_iris, SEED

warnings.filterwarnings("ignore")
X, y = load_iris()

knn = KNeighborsClassifier(n_neighbors=5)
models = [
    ("original 4D", knn),
    ("PCA 2D (fit inside each fold)", make_pipeline(PCA(n_components=2), knn)),
    ("Isomap 2D (fit inside each fold)", make_pipeline(Isomap(n_neighbors=3, n_components=2), knn)),
]

# Seed 572, fold by fold: the embedding is fit on the training fold only,
# then the test fold is transformed with that fitted embedding.
print("seed %d, 5 folds, embedding fit on the training fold only" % SEED)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)
for name, model in models:
    accs = []
    for tr, te in cv.split(X, y):
        m = clone(model).fit(X[tr], y[tr])
        accs.append(m.score(X[te], y[te]))
    print("  %-34s folds %s  mean %.4f" % (name, np.round(accs, 4), np.mean(accs)))
print()

# How connected is the 3-NN graph on each training fold?
print("connected components of the 3-NN graph on each training fold (seed %d):" % SEED)
for tr, te in cv.split(X, y):
    G = kneighbors_graph(X[tr], n_neighbors=3, mode="connectivity")
    n_comp, lab = connected_components(G, directed=False)
    print("  training size %d: %d components, sizes %s" % (len(tr), n_comp, np.bincount(lab)))
print()

# Same comparison over 50 different split seeds
seeds = list(range(50))
res = {}
for name, model in models:
    res[name] = np.array([
        cross_val_score(model, X, y,
                        cv=StratifiedKFold(5, shuffle=True, random_state=s)).mean()
        for s in seeds])
print("mean 5-fold CV accuracy over 50 split seeds, embedding fit inside each fold")
print("%-34s %8s %8s %8s %8s" % ("", "mean", "std", "min", "max"))
for name, _ in models:
    a = res[name]
    print("%-34s %8.4f %8.4f %8.4f %8.4f" % (name, a.mean(), a.std(), a.min(), a.max()))
p = res["PCA 2D (fit inside each fold)"]
i = res["Isomap 2D (fit inside each fold)"]
print()
print("seeds where PCA beats Isomap: %d of %d, tie: %d of %d" % (
    int(np.sum(p > i)), len(seeds), int(np.sum(p == i)), len(seeds)))
