text_html_output_1.png
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot

from sklearn import cluster, mixture, metrics     # For clustering

import matplotlib.pyplot as plt                   # For graphics

import pandas as pd                               # Dataframe manipulation

import plotly.graph_objs as go

whr_data = pd.read_csv('../input/2017.csv', header=0)

whr_data_for_clus = whr_data.iloc[:, 5:]

n_clusters = 2
bandwidth = 0.1
eps = 0.3
damping = 0.9
preference = -200
metric = 'euclidean'
cluster_dist = {'Technique': ['K-means', 'Mean Shift', 'Mini Batch K-Means', 'Spectral', 'DBSCAN', 'Affinity Propagation', 'Birch', 'Gaussian Mixture Modeling'], 'FunctionName': ['Kmeans_Technique', 'MeanShift_Technique', 'MiniKmean_Technique', 'Spectral_Technique', 'Dbscan_Technique', 'AffProp_Technique', 'Birch_Technique', 'Gmm_Technique']}
cluster_df = pd.DataFrame(cluster_dist)
def Kmeans_Technique(ds):
    """
    Ref: http://scikit-learn.org/stable/modules/clustering.html#k-means   
    """
    km = cluster.KMeans(n_clusters=n_clusters)
    return km.fit_predict(ds)
def MeanShift_Technique(ds):
    """
    Ref: http://scikit-learn.org/stable/modules/clustering.html#mean-shift
    """
    ms = cluster.MeanShift(bandwidth=bandwidth)
    return ms.fit_predict(ds)
def MiniKmean_Technique(ds):
    """
    Ref: http://scikit-learn.org/stable/modules/clustering.html#mini-batch-k-means
    """
    mkm = cluster.MiniBatchKMeans(n_clusters=n_clusters)
    return mkm.fit_predict(ds)
def Spectral_Technique(ds):
    """
    Ref: http://scikit-learn.org/stable/modules/clustering.html#spectral-clustering
    """
    spectral = cluster.SpectralClustering(n_clusters=n_clusters)
    return spectral.fit_predict(ds)
def Dbscan_Technique(ds):
    """
    Ref: http://scikit-learn.org/stable/modules/clustering.html#dbscan
    """
    dbscan = cluster.DBSCAN(eps=eps)
    return dbscan.fit_predict(ds)
def AffProp_Technique(ds):
    """
    Ref: http://scikit-learn.org/stable/modules/clustering.html#affinity-propagation
    """
    ap = cluster.AffinityPropagation(damping=damping, preference=preference)
    return ap.fit_predict(ds)
def Birch_Technique(ds):
    """
    Ref: http://scikit-learn.org/stable/modules/clustering.html#birch
    """
    birch = cluster.Birch(n_clusters=n_clusters)
    return birch.fit_predict(ds)
def Gmm_Technique(ds):
    """
    Ref: http://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html#sklearn.mixture.GaussianMixture
    """
    gmm = mixture.GaussianMixture(n_components=n_clusters, covariance_type='full')
    gmm.fit(ds)
    return gmm.predict(ds)
def GetSilhouetteCoeff(ds, result):
    """
    Ref: http://scikit-learn.org/stable/modules/clustering.html#silhouette-coefficient
    Input - 
        - ds - The dataset for which the clustering was done
        - result - The labels after the clustering
    """
    return metrics.silhouette_score(ds, result, metric=metric)
def GetMethodName_Temp(method):
    m = str(method)
    m = m[1:m.index('\n')]
    return m.strip()

for t in cluster_df.Technique:
    method = cluster_df[cluster_df.Technique == t].FunctionName
    m = GetMethodName_Temp(method)
    result = locals()[m](whr_data_for_clus)
    whr_data[t] = pd.DataFrame(result)
    if t != 'Affinity Propagation':
        cluster_df.loc[cluster_df.Technique == t, 'Silhouette.Coeff'] = GetSilhouetteCoeff(whr_data_for_clus, result)
cluster_df.loc[cluster_df.Technique == 'Affinity Propagation', 'SilCoeff'] = 0

whr_data.iloc[:, [0, 12, 13, 14, 15, 16, 17, 18, 19]]

cluster_df.iloc[:, [1, 2]]

rows = 4    # No of rows for the plot
cols = 2    # No of columns for the plot

cdf = cluster_df['Technique']

# 4 X 2 plot
fig,ax = plt.subplots(rows,cols, figsize=(15, 10)) 
x = 0
y = 0
for i in cdf:
   ax[x,y].scatter(whr_data.iloc[:, 6], whr_data.iloc[:, 5],  c=whr_data.iloc[:, 12+(x*y)])
   # Set the title for each of the plot
   ax[x,y].set_title(i + " Cluster Result")
    
   y = y + 1
   if y == cols:
       x = x + 1
       y = 0

plt.subplots_adjust(bottom=-0.5, top=1.5)
plt.show()
x = 0
y = 0

data = dict(type='choropleth', locations=whr_data['Country'], locationmode='country names', z=whr_data['Happiness.Score'], text=whr_data['Country'], colorbar={'title': 'Happiness Score'})
layout = dict(title='Global Happiness Score', geo=dict(showframe=False, projection={'type': 'Mercator'}))
choromap3 = go.Figure(data=[data], layout=layout)

data = dict(type='choropleth', locations=whr_data['Country'], locationmode='country names', z=whr_data['K-means'], text=whr_data['Country'], colorbar={'title': 'Cluster Group'})
layout = dict(title='K-Means Clustering Visualization', geo=dict(showframe=False, projection={'type': 'Mercator'}))
choromap3 = go.Figure(data=[data], layout=layout)
iplot(choromap3)