import numpy as np
import shogun as sg
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')

num = 200
d1 = np.concatenate((np.random.randn(1,num),10.*np.random.randn(1,num)),0)
d2 = np.concatenate((np.random.randn(1,num),10.*np.random.randn(1,num)),0)+np.array([[10.],[0.]])
d3 = np.concatenate((np.random.randn(1,num),10.*np.random.randn(1,num)),0)+np.array([[0.],[100.]])
d4 = np.concatenate((np.random.randn(1,num),10.*np.random.randn(1,num)),0)+np.array([[10.],[100.]])

rectangle = np.concatenate((d1,d2,d3,d4),1)
totalPoints = 800 

"""
Explanation: Clustering with KMeans in Shogun Machine Learning Toolbox
Notebook by Parijat Mazumdar (GitHub ID: <a href='https://github.com/mazumdarparijat'>mazumdarparijat</a>)
This notebook demonstrates <a href="http://en.wikipedia.org/wiki/K-means_clustering">clustering with KMeans</a> in Shogun along with its initialization and training. The initialization of cluster centres is shown manually, randomly and using the <a href="http://en.wikipedia.org/wiki/K-means%2B%2B">KMeans++</a> algorithm. Training is done via the classical <a href="http://en.wikipedia.org/wiki/Lloyd%27s_algorithm">Lloyds</a> and mini-batch KMeans method.
It is then applied to a real world data set. Furthermore, the effect of dimensionality reduction using <a href="http://en.wikipedia.org/wiki/Principal_component_analysis">PCA</a> is analysed on the KMeans algorithm.
KMeans - An Overview
The <a href="http://en.wikipedia.org/wiki/K-means_clustering">KMeans clustering algorithm</a> is used to partition a space of n observations into k partitions (or clusters). Each of these clusters is denoted by the mean of the observation vectors belonging to it and a unique label which is attached to all the observations belonging to it. Thus, in general, the algorithm takes parameter k and an observation matrix (along with the notion of distance between points ie <i>distance metric</i>) as input and returns mean of each of the k clusters along with labels indicating belongingness of each observations. Let us construct a simple example to understand how it is done in Shogun using the <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1KMeans.html">KMeans</a> class. 
Let us start by creating a toy dataset.
End of explanation
"""


import matplotlib.pyplot as plt
%matplotlib inline

figure,axis = plt.subplots(1,1)
axis.plot(rectangle[0], rectangle[1], 'o', color='r', markersize=5)
axis.set_xlim(-5,15)
axis.set_ylim(-50,150)
axis.set_title('Toy data : Rectangle')
plt.show()

"""
Explanation: The toy data created above consists of 4 gaussian blobs, having 200 points each, centered around the vertices of a rectancle. Let's plot it for convenience.
End of explanation
"""


train_features = sg.create_features(rectangle)

"""
Explanation: With data at our disposal, it is time to apply KMeans to it using the KMeans class in Shogun. First we construct Shogun features from our data:
End of explanation
"""


# number of clusters
k = 2

# distance metric over feature matrix - Euclidean distance
distance = sg.create_distance('EuclideanDistance')
distance.init(train_features, train_features)

"""
Explanation: Next we specify the number of clusters we want and create a distance object specifying the distance metric to be used over our data for our KMeans training:
End of explanation
"""


# KMeans object created
kmeans = sg.create_machine("KMeans", k=k, distance=distance)

# KMeans training 
kmeans.train()

"""
Explanation: Next, we create a KMeans object with our desired inputs/parameters and train:
End of explanation
"""


# cluster centers
centers = kmeans.get("cluster_centers")

# Labels for data points
result = kmeans.apply()

"""
Explanation: Now that training has been done, let's get the cluster centers and label for each data point
End of explanation
"""


def plotResult(title = 'KMeans Plot'):
    figure,axis = plt.subplots(1,1)
    for i in range(totalPoints):
        if result.get("labels")[i]==0.0:
            axis.plot(rectangle[0,i], rectangle[1,i], 'go', markersize=3)
        else:
            axis.plot(rectangle[0,i], rectangle[1,i], 'yo', markersize=3)
    axis.plot(centers[0,0], centers[1,0], 'go', markersize=10)
    axis.plot(centers[0,1], centers[1,1], 'yo', markersize=10)
    axis.set_xlim(-5,15)
    axis.set_ylim(-50,150)
    axis.set_title(title)
    plt.show()
    
plotResult('KMeans Results')

"""
Explanation: Finally let us plot the centers and the data points (in different colours for different clusters):
End of explanation
"""


initial_centers = np.array([[0.,10.],[50.,50.]])

# initial centers passed
kmeans = sg.create_machine("KMeans", k=k, distance=distance, initial_centers=initial_centers)

"""
Explanation: <b>Note:</b> You might not get the perfect result always. That is an inherent flaw of KMeans algorithm. In subsequent sections, we will discuss techniques which allow us to counter this.<br>
Now that we have already worked out a simple KMeans implementation, it's time to understand certain specifics of KMeans implementaion and the options provided by Shogun to its users.
Initialization of cluster centers
The KMeans algorithm requires that the cluster centers are initialized with some values. Shogun offers 3 ways to initialize the clusters. <ul><li>Random initialization (default)</li><li>Initialization by hand</li><li>Initialization using <a href="http://en.wikipedia.org/wiki/K-means%2B%2B">KMeans++ algorithm</a></li></ul>Unless the user supplies initial centers or tells Shogun to use KMeans++, Random initialization is the default method used for cluster center initialization. This was precisely the case in the example discussed above.
Initialization by hand
There are 2 ways to initialize centers by hand. One way is to pass on the centers during KMeans object creation, as follows:
End of explanation
"""


# KMeans training 
kmeans.train(train_features)

# cluster centers
centers = kmeans.get("cluster_centers")

# Labels for data points
result = kmeans.apply()

# plot the results
plotResult('Hand initialized KMeans Results 1')

"""
Explanation: Now, let's first get results by repeating the rest of the steps:
End of explanation
"""


new_initial_centers = np.array([[5.,5.],[0.,100.]])

# set new initial centers
kmeans.put("initial_centers", new_initial_centers)

"""
Explanation: The other way to initialize centers by hand is as follows:
End of explanation
"""


# KMeans training 
kmeans.train(train_features)

# cluster centers
centers = kmeans.get("cluster_centers")

# Labels for data points
result = kmeans.apply()

# plot the results
plotResult('Hand initialized KMeans Results 2')

"""
Explanation: Let's complete the rest of the code to get results.
End of explanation
"""


# set flag for using KMeans++
kmeans = sg.create_machine("KMeans", k=k, distance=distance, kmeanspp=True)

"""
Explanation: Note the difference that inititial cluster centers can have on final result. 
Initializing using KMeans++ algorithm
In Shogun, a user can also use <a href="http://en.wikipedia.org/wiki/K-means%2B%2B">KMeans++ algorithm</a> for center initialization. Using KMeans++ for center initialization is beneficial because it reduces total iterations used by KMeans and also the final centers mostly correspond to the global minima, which is often not the case with KMeans with random initialization. One of the ways to use KMeans++ is to set flag as <i>true</i> during KMeans object creation, as follows:
End of explanation
"""


# KMeans training 
kmeans.train(train_features)

# cluster centers
centers = kmeans.get("cluster_centers")

# Labels for data points
result = kmeans.apply()

# plot the results
plotResult('KMeans with KMeans++ Results')

"""
Explanation: Completing rest of the steps to get result:
End of explanation
"""


# set training method to mini-batch
kmeans = sg.create_machine("KMeansMiniBatch", k=k, distance=distance)

"""
Explanation: Training Methods
Shogun offers 2 training methods for KMeans clustering:<ul><li><a href='http://en.wikipedia.org/wiki/K-means_clustering#Standard_algorithm'>Classical Lloyd's training</a> (default)</li><li><a href='http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf'>mini-batch KMeans training</a></li></ul>Lloyd's training method is used by Shogun by default unless user switches to mini-batch training method.
Mini-Batch KMeans
Mini-batch KMeans is very useful in case of extremely large datasets and/or very high dimensional data which is often the case in text mining. One can switch to Mini-batch KMeans training while creating KMeans object as follows:
End of explanation
"""


# KMeans training 
kmeans.train(train_features)

# cluster centers
centers = kmeans.get("cluster_centers")

# Labels for data points
result = kmeans.apply()

# plot the results
plotResult('Mini-batch KMeans Results')

"""
Explanation: Completing the code to get results:
End of explanation
"""


with open(os.path.join(SHOGUN_DATA_DIR, 'uci/iris/iris.data')) as f:
    feats = []
    # read data from file
    for line in f:
        words = line.rstrip().split(',')
        feats.append([float(i) for i in words[0:4]])

# create observation matrix
obsmatrix = np.array(feats).T

# plot the data
figure,axis = plt.subplots(1,1)
# First 50 data belong to Iris Sentosa, plotted in green
axis.plot(obsmatrix[2,0:50], obsmatrix[3,0:50], 'o', color='green', markersize=5)
# Next 50 data belong to Iris Versicolour, plotted in red
axis.plot(obsmatrix[2,50:100], obsmatrix[3,50:100], 'o', color='red', markersize=5)
# Last 50 data belong to Iris Virginica, plotted in blue
axis.plot(obsmatrix[2,100:150], obsmatrix[3,100:150], 'o', color='blue', markersize=5)
axis.set_xlim(-1,8)
axis.set_ylim(-1,3)
axis.set_title('3 varieties of Iris plants')
plt.show()

"""
Explanation: Applying KMeans on Real Data
In this section we see how useful KMeans can be in classifying the different varieties of Iris plant. For this purpose, we make use of Fisher's Iris dataset borrowed from the <a href='http://archive.ics.uci.edu/ml/datasets/Iris'>UCI Machine Learning Repository</a>. There are 3 varieties of Iris plants
<ul><li>Iris Sensosa</li><li>Iris Versicolour</li><li>Iris Virginica</li></ul>
The Iris dataset enlists 4 features that can be used to segregate these varieties, namely
<ul><li>sepal length</li><li>sepal width</li><li>petal length</li><li>petal width</li></ul>
It is additionally acknowledged that petal length and petal width are the 2 most important features (ie. features with very high class correlations)[refer to <a href='http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.names'>summary statistics</a>]. Since the entire feature vector is impossible to plot, we only plot these two most important features in order to understand the dataset (at least partially). Note that we could have extracted the 2 most important features by applying PCA (or any one of the many dimensionality reduction methods available in Shogun) as well.
End of explanation
"""


def apply_kmeans_iris(data):
    # wrap to Shogun features
    train_features = sg.create_features(data)

    # number of cluster centers = 3
    k = 3

    # distance function features - euclidean
    distance = sg.create_distance('EuclideanDistance')
    distance.init(train_features, train_features)

    # initialize KMeans object, use kmeans++ to initialize centers [play around: change it to False and compare results]
    kmeans = sg.create_machine("KMeans", k=k, distance=distance, kmeanspp=True)

    # training method is Lloyd by default [play around: change it to mini-batch by uncommenting the following lines]
    #kmeans = sg.create_machine("KMeansMiniBatch", k=k, distance=distance)

    # training kmeans
    kmeans.train(train_features)

    # labels for data points
    result = kmeans.apply()
    return result

result = apply_kmeans_iris(obsmatrix)

"""
Explanation: In the above plot we see that the data points labelled Iris Sentosa form a nice separate cluster of their own. But in case of other 2 varieties, while the data points of same label do form clusters of their own, there is some mixing between the clusters at the boundary. Now let us apply KMeans algorithm and see how well we can extract these clusters.
End of explanation
"""


# plot the clusters over the original points in 2 dimensions
figure,axis = plt.subplots(1,1)
for i in range(150):
    if result.get("labels")[i]==0.0:
        axis.plot(obsmatrix[2,i],obsmatrix[3,i],'ro', markersize=5)
    elif result.get("labels")[i]==1.0:
        axis.plot(obsmatrix[2,i],obsmatrix[3,i],'go', markersize=5)
    else:
        axis.plot(obsmatrix[2,i],obsmatrix[3,i],'bo', markersize=5)

axis.set_xlim(-1,8)
axis.set_ylim(-1,3)
axis.set_title('Iris plants clustered based on attributes')
plt.show()

"""
Explanation: Now let us create a 2-D plot of the clusters formed making use of the two most important features (petal length and petal width) and compare it with the earlier plot depicting the actual labels of data points.
End of explanation
"""


# first 50 are iris sensosa labelled 0, next 50 are iris versicolour labelled 1 and so on
labels = np.concatenate((np.zeros(50),np.ones(50),2.*np.ones(50)),0)

# bind labels assigned to Shogun multiclass labels
ground_truth = sg.create_labels(np.array(labels,dtype='float64'))

"""
Explanation: From the above plot, it can be inferred that the accuracy of KMeans algorithm is very high for Iris dataset. Don't believe me? Alright, then let us make use of one of Shogun's clustering evaluation techniques to formally validate the claim. But before that, we have to label each sample in the dataset with a label corresponding to the class to which it belongs.
End of explanation
"""


def analyzeResult(result): 
    # shogun object for clustering accuracy
    AccuracyEval = sg.create_evaluation("ClusteringAccuracy")

    # evaluates clustering accuracy
    accuracy = AccuracyEval.evaluate(result, ground_truth)

    # find out which sample points differ from actual labels (or ground truth)
    compare = result.get("labels")-labels
    diff = np.nonzero(compare)
    return (diff,accuracy)

(diff,accuracy_4d) = analyzeResult(result)
print('Accuracy : ' + str(accuracy_4d))

# plot the difference between ground truth and predicted clusters
figure,axis = plt.subplots(1,1)
axis.plot(obsmatrix[2,:],obsmatrix[3,:],'x',color='black', markersize=5)
axis.plot(obsmatrix[2,diff],obsmatrix[3,diff],'x',color='r', markersize=7)
axis.set_xlim(-1,8)
axis.set_ylim(-1,3)
axis.set_title('Difference')
plt.show()

"""
Explanation: Now we can compute clustering accuracy making use of the ClusteringAccuracy class in Shogun
End of explanation
"""


def apply_pca_to_data(target_dims):
    train_features = sg.create_features(obsmatrix)
    submean = sg.create_transformer("PruneVarSubMean", divide_by_std=False)
    submean.fit(train_features)
    submean.transform(train_features)
    preprocessor = sg.create_transformer("PCA", target_dim=target_dims)
    preprocessor.fit(train_features)
    pca_transform = preprocessor.get("transformation_matrix")
    new_features = np.dot(pca_transform.T, train_features.get("feature_matrix"))
    return new_features

oneD_matrix = apply_pca_to_data(1)

"""
Explanation: In the above plot, wrongly clustered data points are marked in red. We see that the Iris Sentosa plants are perfectly clustered without error. The Iris Versicolour plants and Iris Virginica plants are also clustered with high accuracy, but there are some plant samples of either class that have been clustered with the wrong class. This happens near the boundary of the 2 classes in the plot and was well expected. Having mastered KMeans, it's time to move on to next interesting topic.  
PCA as a preprocessor to KMeans
KMeans is highly affected by the <i>curse of dimensionality</i>. So, dimension reduction becomes an important preprocessing step. Shogun offers a variety of dimension reduction techniques to choose from. Since our data is not very high dimensional, PCA is a good choice for dimension reduction. We have already seen the accuracy of KMeans when all four dimensions are used. In the following exercise we shall see how the accuracy varies as one chooses lower dimensions to represent data. 
1-Dimensional representation
Let us first apply PCA to reduce training features to 1 dimension
End of explanation
"""


figure,axis = plt.subplots(1,1)
# First 50 data belong to Iris Sentosa, plotted in green
axis.plot(oneD_matrix[0,0:50], np.zeros(50), 'go', markersize=5)
# Next 50 data belong to Iris Versicolour, plotted in red
axis.plot(oneD_matrix[0,50:100], np.zeros(50), 'ro', markersize=5)
# Last 50 data belong to Iris Virginica, plotted in blue
axis.plot(oneD_matrix[0,100:150], np.zeros(50), 'bo', markersize=5)
axis.set_xlim(-5,5)
axis.set_ylim(-1,1)
axis.set_title('3 varieties of Iris plants')
plt.show()

"""
Explanation: Next, let us get an idea of the data in 1-D by plotting it.
End of explanation
"""


result = apply_kmeans_iris(oneD_matrix)

"""
Explanation: Let us now apply KMeans to the 1-D data to get clusters.
End of explanation
"""


(diff,accuracy_1d) = analyzeResult(result)
print('Accuracy : ' + str(accuracy_1d))

# plot the difference between ground truth and predicted clusters
figure,axis = plt.subplots(1,1)
axis.plot(oneD_matrix[0,:],np.zeros(150),'x',color='black', markersize=5)
axis.plot(oneD_matrix[0,diff],np.zeros(len(diff)),'x',color='r', markersize=7)
axis.set_xlim(-5,5)
axis.set_ylim(-1,1)
axis.set_title('Difference')
plt.show()

"""
Explanation: Now that we have the results, the inevitable step is to check how good these results are.
End of explanation
"""


twoD_matrix = apply_pca_to_data(2)

figure,axis = plt.subplots(1,1)
# First 50 data belong to Iris Sentosa, plotted in green
axis.plot(twoD_matrix[0,0:50], twoD_matrix[1,0:50], 'go', markersize=5)
# Next 50 data belong to Iris Versicolour, plotted in red
axis.plot(twoD_matrix[0,50:100], twoD_matrix[1,50:100], 'ro', markersize=5)
# Last 50 data belong to Iris Virginica, plotted in blue
axis.plot(twoD_matrix[0,100:150], twoD_matrix[1,100:150], 'bo', markersize=5)
axis.set_title('3 varieties of Iris plants')
plt.show()

"""
Explanation: 2-Dimensional Representation
We follow the same steps as above and get the clustering accuracy.
STEP 1 : Apply PCA and plot the data (plotting is optional)
End of explanation
"""


result = apply_kmeans_iris(twoD_matrix)

"""
Explanation: STEP 2 : Apply KMeans to obtain clusters
End of explanation
"""


(diff,accuracy_2d) = analyzeResult(result)
print('Accuracy : ' + str(accuracy_2d))

# plot the difference between ground truth and predicted clusters
figure,axis = plt.subplots(1,1)
axis.plot(twoD_matrix[0,:],twoD_matrix[1,:],'x',color='black', markersize=5)
axis.plot(twoD_matrix[0,diff],twoD_matrix[1,diff],'x',color='r', markersize=7)
axis.set_title('Difference')
plt.show()

"""
Explanation: STEP 3: Get the accuracy of the results
End of explanation
"""


threeD_matrix = apply_pca_to_data(3)

"""
Explanation: 3-Dimensional Representation
Again, we follow the same steps, but skip plotting data.
STEP 1: Apply PCA to data
End of explanation
"""


result = apply_kmeans_iris(threeD_matrix)

"""
Explanation: STEP 2: Apply KMeans to 3-D representation of data
End of explanation
"""


(diff,accuracy_3d) = analyzeResult(result)
print('Accuracy : ' + str(accuracy_3d))

# plot the difference between ground truth and predicted clusters
figure,axis = plt.subplots(1,1)
axis.plot(obsmatrix[2,:],obsmatrix[3,:],'x',color='black', markersize=5)
axis.plot(obsmatrix[2,diff],obsmatrix[3,diff],'x',color='r', markersize=7)
axis.set_title('Difference')
axis.set_xlim(-1,8)
axis.set_ylim(-1,3)
plt.show()

"""
Explanation: STEP 3: Get accuracy of results. In this step, the 'difference' plot positions data points based petal length 
    and petal width in the original data. This will enable us to visually compare these results with that of KMeans applied
    to 4-Dimensional data (ie. our first result on Iris dataset)
End of explanation
"""


from scipy.interpolate import interp1d

x = np.array([1, 2, 3, 4])
y = np.array([accuracy_1d, accuracy_2d, accuracy_3d, accuracy_4d])
f = interp1d(x, y)
xnew = np.linspace(1,4,10)
plt.plot(x,y,'o',xnew,f(xnew),'-')
plt.xlim([0,5])
plt.xlabel('no. of dims')
plt.ylabel('Clustering Accuracy')
plt.title('PCA Results')
plt.show()

"""
Explanation: Finally, let us plot clustering accuracy vs. number of dimensions to consolidate our results.
End of explanation
"""


