Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Alois-star/6554c033f5774d3bcab261e373a0d893 to your computer and use it in GitHub Desktop.
Save Alois-star/6554c033f5774d3bcab261e373a0d893 to your computer and use it in GitHub Desktop.
Created on Skills Network Labs
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a href=\"https://www.bigdatauniversity.com\"><img src=\"https://ibm.box.com/shared/static/cw2c7r3o20w9zn8gkecaeyjhgw3xdgbj.png\" width=\"400\" align=\"center\"></a>\n",
"\n",
"<h1><center>Hierarchical Clustering</center></h1>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Welcome to Lab of Hierarchical Clustering with Python using Scipy and Scikit-learn package."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h1>Table of contents</h1>\n",
"\n",
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
" <ol>\n",
" <li><a href=\"#hierarchical_agglomerative\">Hierarchical Clustering - Agglomerative</a></li>\n",
" <ol>\n",
" <li><a href=\"#generating_data\">Generating Random Data</a></li>\n",
" <li><a href=\"#agglomerative_clustering\">Agglomerative Clustering</a></li>\n",
" <li><a href=\"#dendrogram\">Dendrogram Associated for the Agglomerative Hierarchical Clustering</a></li>\n",
" </ol> \n",
" <li><a href=\"#clustering_vehicle_dataset\">Clustering on the Vehicle Dataset</a></li>\n",
" <ol>\n",
" <li><a href=\"#data_cleaning\">Data Cleaning</a></li>\n",
" <li><a href=\"#clustering_using_scipy\">Clustering Using Scipy</a></li>\n",
" <li><a href=\"#clustering_using_skl\">Clustering using scikit-learn</a></li>\n",
" </ol>\n",
" </ol>\n",
"</div>\n",
"<br>\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h1 id=\"hierarchical_agglomerative\">Hierarchical Clustering - Agglomerative</h1>\n",
"\n",
"We will be looking at a clustering technique, which is <b>Agglomerative Hierarchical Clustering</b>. Remember that agglomerative is the bottom up approach. <br> <br>\n",
"In this lab, we will be looking at Agglomerative clustering, which is more popular than Divisive clustering. <br> <br>\n",
"We will also be using Complete Linkage as the Linkage Criteria. <br>\n",
"<b> <i> NOTE: You can also try using Average Linkage wherever Complete Linkage would be used to see the difference! </i> </b>"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np \n",
"import pandas as pd\n",
"from scipy import ndimage \n",
"from scipy.cluster import hierarchy \n",
"from scipy.spatial import distance_matrix \n",
"from matplotlib import pyplot as plt \n",
"from sklearn import manifold, datasets \n",
"from sklearn.cluster import AgglomerativeClustering \n",
"from sklearn.datasets.samples_generator import make_blobs \n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n",
"<h3 id=\"generating_data\">Generating Random Data</h3>\n",
"We will be generating a set of data using the <b>make_blobs</b> class. <br> <br>\n",
"Input these parameters into make_blobs:\n",
"<ul>\n",
" <li> <b>n_samples</b>: The total number of points equally divided among clusters. </li>\n",
" <ul> <li> Choose a number from 10-1500 </li> </ul>\n",
" <li> <b>centers</b>: The number of centers to generate, or the fixed center locations. </li>\n",
" <ul> <li> Choose arrays of x,y coordinates for generating the centers. Have 1-10 centers (ex. centers=[[1,1], [2,5]]) </li> </ul>\n",
" <li> <b>cluster_std</b>: The standard deviation of the clusters. The larger the number, the further apart the clusters</li>\n",
" <ul> <li> Choose a number between 0.5-1.5 </li> </ul>\n",
"</ul> <br>\n",
"Save the result to <b>X1</b> and <b>y1</b>."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"X1, y1 = make_blobs(n_samples=50, centers=[[4,4], [-2, -1], [1, 1], [10,4]], cluster_std=0.9)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plot the scatter plot of the randomly generated data"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.collections.PathCollection at 0x7faf5e9003c8>"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXUAAAD4CAYAAAATpHZ6AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAUoElEQVR4nO3db4xcZ3XH8d8PZxGbELSgLDRZZ3GqItMQA4ZRCl2pEkmoTQlJ6rZSUoEigbRvShtacHEaqbQvWltyRYsEKrIIBSlpaJU/JiIBx+CgCAQp62xIYhwDooR4k9ZGyPx1wTanL3Y22V3PzM7MfWbuc+98P5KV3dnJnaNkfeaZ85znXEeEAAD18IKyAwAApENSB4AaIakDQI2Q1AGgRkjqAFAj55TxohdccEFs2LChjJcGgMo6ePDgDyNistNzSknqGzZs0NzcXBkvDQCVZfuptZ5D+QUAaoSkDgA1QlIHgBohqQNAjZDUAaBGSOoAUCOltDRitOydX9DufUf0zImTumhiXNu3bNR1m6fKDguoJZI6Bmrv/IJuvvtxnTx1RpK0cOKkbr77cUkisQMDQPkFA7V735HnEvqSk6fOaPe+IyVFBNQbSR0D9cyJkz09DqAYkjoG6qKJ8Z4eB1AMSR0DtX3LRo2PrVvx2PjYOm3fsrGkiIB6Y6MUA7W0GUr3CzAcJHUM3HWbp0jiwJBQfgGAGkmyUrf9fUk/lXRG0umIaKS4LgCgNynLL2+JiB8mvB5QG5yqxbBQUwcGjFO1GKZUNfWQ9IDtg7ZnE10TqAVO1WKYUq3UZyLiGdsvl7Tf9pMR8dDyJzST/awkTU9PJ3pZjLoqlDU4VYthSrJSj4hnmv88JukeSZe3eM6eiGhERGNysuPNsIGuLJU1Fk6cVOj5ssbe+YWyQ1uBU7UYpsJJ3fZ5ts9f+lrS70t6ouh1gbVUpazBqdpq2ju/oJldB3TJjvs0s+tAdouFdlK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SbLpG77GkkLEfHNsmPp0rslfb7sILSYIJ9e9v1RZZY0l9jeIGmzpIfLjeQs/6LFxcSvyw6kjd+UdFzSvzVLRJ+wfV7ZQS0XEQuS/kmLn7KflfTjiHig3KhaekVEPCstLjgkvbzkeNbSVZ4pLanb/mKz3rb6z7WSbpH0t2XF1mWMS8+5RYtlhdvLi/Q5bvFYdp90bL9Y0l2S3hcRPyk7niW2r5Z0LCIOlh1LB+dIeoOkf42IzZJ+rvLLBis0a9PXSrpE0kWSzrP9znKjqrZe8kxpt7OLiKtaPW57kxZ/Gb5pW1r8uPGI7csj4n+GGGLbGJfYvlHS1ZKujDwa/o9KunjZ9+tV8sfe1WyPaTGh3x4Rd5cdzyozkq6x/QeSXiTpJbZvi4icEtJRSUcjYukTzp3KLKlLukrSf0fEcUmyfbek35V0W6lRne1/bV8YEc/avlDSsbIDaqXXPJNd+SUiHo+Il0fEhojYoMVf4jcMO6GvxfZWSR+UdE1E/KLseJq+IelVti+x/UItbk7dW3JMz/Hiu/Stkg5HxIfLjme1iLg5ItY3f++ul3Qgs4Su5t+Dp21vbD50paRvlRhSKz+Q9Cbb5zb/n1+pzDZzm+6VdGPz6xslfbbEWFrqJ89kl9Qr5KOSzpe03/ajtj9edkDNDZX3Stqnxb9E/xkRh8qNaoUZSe+SdEXzv9mjzVUxevPnkm63/Zik10v6x5LjWaH5KeJOSY9IelyLeabU4/i275D0NUkbbR+1/R5JuyS91fZ3tNhptyvDGHvOM4wJAIAaYaUOADVCUgeAGiGpA0CNkNQBoEZI6gBQIyR1AKgRkjoA1Mj/A/OJL2cfwp8pAAAAAElFTkSuQmCC\n",
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plt.scatter(X1[:, 0], X1[:, 1], marker='o') "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n",
"<h3 id=\"agglomerative_clustering\">Agglomerative Clustering</h3>\n",
"We will start by clustering the random data points we just created."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The <b> Agglomerative Clustering </b> class will require two inputs:\n",
"<ul>\n",
" <li> <b>n_clusters</b>: The number of clusters to form as well as the number of centroids to generate. </li>\n",
" <ul> <li> Value will be: 4 </li> </ul>\n",
" <li> <b>linkage</b>: Which linkage criterion to use. The linkage criterion determines which distance to use between sets of observation. The algorithm will merge the pairs of cluster that minimize this criterion. </li>\n",
" <ul> \n",
" <li> Value will be: 'complete' </li> \n",
" <li> <b>Note</b>: It is recommended you try everything with 'average' as well </li>\n",
" </ul>\n",
"</ul> <br>\n",
"Save the result to a variable called <b> agglom </b>"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"agglom = AgglomerativeClustering(n_clusters = 4, linkage = 'average')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Fit the model with <b> X2 </b> and <b> y2 </b> from the generated data above."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"text/plain": [
"AgglomerativeClustering(affinity='euclidean', compute_full_tree='auto',\n",
" connectivity=None, linkage='average', memory=None,\n",
" n_clusters=4, pooling_func='deprecated')"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agglom.fit(X1,y1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Run the following code to show the clustering! <br>\n",
"Remember to read the code and comments to gain more understanding on how the plotting works."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create a figure of size 6 inches by 4 inches.\n",
"plt.figure(figsize=(6,4))\n",
"\n",
"# These two lines of code are used to scale the data points down,\n",
"# Or else the data points will be scattered very far apart.\n",
"\n",
"# Create a minimum and maximum range of X1.\n",
"x_min, x_max = np.min(X1, axis=0), np.max(X1, axis=0)\n",
"\n",
"# Get the average distance for X1.\n",
"X1 = (X1 - x_min) / (x_max - x_min)\n",
"\n",
"# This loop displays all of the datapoints.\n",
"for i in range(X1.shape[0]):\n",
" # Replace the data points with their respective cluster value \n",
" # (ex. 0) and is color coded with a colormap (plt.cm.spectral)\n",
" plt.text(X1[i, 0], X1[i, 1], str(y1[i]),\n",
" color=plt.cm.nipy_spectral(agglom.labels_[i] / 10.),\n",
" fontdict={'weight': 'bold', 'size': 9})\n",
" \n",
"# Remove the x ticks, y ticks, x and y axis\n",
"plt.xticks([])\n",
"plt.yticks([])\n",
"#plt.axis('off')\n",
"\n",
"\n",
"\n",
"# Display the plot of the original data before clustering\n",
"plt.scatter(X1[:, 0], X1[:, 1], marker='.')\n",
"# Display the plot\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"<h3 id=\"dendrogram\">Dendrogram Associated for the Agglomerative Hierarchical Clustering</h3>\n",
"Remember that a <b>distance matrix</b> contains the <b> distance from each point to every other point of a dataset </b>. <br>\n",
"Use the function <b> distance_matrix, </b> which requires <b>two inputs</b>. Use the Feature Matrix, <b> X2 </b> as both inputs and save the distance matrix to a variable called <b> dist_matrix </b> <br> <br>\n",
"Remember that the distance values are symmetric, with a diagonal of 0's. This is one way of making sure your matrix is correct. <br> (print out dist_matrix to make sure it's correct)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"dist_matrix = distance_matrix(X1,X1) \n",
"print(dist_matrix)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using the <b> linkage </b> class from hierarchy, pass in the parameters:\n",
"<ul>\n",
" <li> The distance matrix </li>\n",
" <li> 'complete' for complete linkage </li>\n",
"</ul> <br>\n",
"Save the result to a variable called <b> Z </b>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Z = hierarchy.linkage(dist_matrix, 'complete')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A Hierarchical clustering is typically visualized as a dendrogram as shown in the following cell. Each merge is represented by a horizontal line. The y-coordinate of the horizontal line is the similarity of the two clusters that were merged, where cities are viewed as singleton clusters. \n",
"By moving up from the bottom layer to the top node, a dendrogram allows us to reconstruct the history of merges that resulted in the depicted clustering. \n",
"\n",
"Next, we will save the dendrogram to a variable called <b>dendro</b>. In doing this, the dendrogram will also be displayed.\n",
"Using the <b> dendrogram </b> class from hierarchy, pass in the parameter:\n",
"<ul> <li> Z </li> </ul>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dendro = hierarchy.dendrogram(Z)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Practice\n",
"We used __complete__ linkage for our case, change it to __average__ linkage to see how the dendogram changes."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# write your code here\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"\n",
"<!-- Your answer is below:\n",
" \n",
"Z = hierarchy.linkage(dist_matrix, 'average')\n",
"dendro = hierarchy.dendrogram(Z)\n",
"\n",
"-->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n",
"<h1 id=\"clustering_vehicle_dataset\">Clustering on Vehicle dataset</h1>\n",
"\n",
"Imagine that an automobile manufacturer has developed prototypes for a new vehicle. Before introducing the new model into its range, the manufacturer wants to determine which existing vehicles on the market are most like the prototypes--that is, how vehicles can be grouped, which group is the most similar with the model, and therefore which models they will be competing against.\n",
"\n",
"Our objective here, is to use clustering methods, to find the most distinctive clusters of vehicles. It will summarize the existing vehicles and help manufacturers to make decision about the supply of new models."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Download data\n",
"To download the data, we will use **`!wget`** to download it from IBM Object Storage. \n",
"__Did you know?__ When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!wget -O cars_clus.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/cars_clus.csv"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Read data\n",
"lets read dataset to see what features the manufacturer has collected about the existing models."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"filename = 'cars_clus.csv'\n",
"\n",
"#Read csv\n",
"pdf = pd.read_csv(filename)\n",
"print (\"Shape of dataset: \", pdf.shape)\n",
"\n",
"pdf.head(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The feature sets include price in thousands (price), engine size (engine_s), horsepower (horsepow), wheelbase (wheelbas), width (width), length (length), curb weight (curb_wgt), fuel capacity (fuel_cap) and fuel efficiency (mpg)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"data_cleaning\">Data Cleaning</h2>\n",
"lets simply clear the dataset by dropping the rows that have null value:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print (\"Shape of dataset before cleaning: \", pdf.size)\n",
"pdf[[ 'sales', 'resale', 'type', 'price', 'engine_s',\n",
" 'horsepow', 'wheelbas', 'width', 'length', 'curb_wgt', 'fuel_cap',\n",
" 'mpg', 'lnsales']] = pdf[['sales', 'resale', 'type', 'price', 'engine_s',\n",
" 'horsepow', 'wheelbas', 'width', 'length', 'curb_wgt', 'fuel_cap',\n",
" 'mpg', 'lnsales']].apply(pd.to_numeric, errors='coerce')\n",
"pdf = pdf.dropna()\n",
"pdf = pdf.reset_index(drop=True)\n",
"print (\"Shape of dataset after cleaning: \", pdf.size)\n",
"pdf.head(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Feature selection\n",
"Lets select our feature set:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"featureset = pdf[['engine_s', 'horsepow', 'wheelbas', 'width', 'length', 'curb_wgt', 'fuel_cap', 'mpg']]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Normalization\n",
"Now we can normalize the feature set. __MinMaxScaler__ transforms features by scaling each feature to a given range. It is by default (0, 1). That is, this estimator scales and translates each feature individually such that it is between zero and one."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.preprocessing import MinMaxScaler\n",
"x = featureset.values #returns a numpy array\n",
"min_max_scaler = MinMaxScaler()\n",
"feature_mtx = min_max_scaler.fit_transform(x)\n",
"feature_mtx [0:5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"clustering_using_scipy\">Clustering using Scipy</h2>\n",
"In this part we use Scipy package to cluster the dataset: \n",
"First, we calculate the distance matrix. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import scipy\n",
"leng = feature_mtx.shape[0]\n",
"D = scipy.zeros([leng,leng])\n",
"for i in range(leng):\n",
" for j in range(leng):\n",
" D[i,j] = scipy.spatial.distance.euclidean(feature_mtx[i], feature_mtx[j])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In agglomerative clustering, at each iteration, the algorithm must update the distance matrix to reflect the distance of the newly formed cluster with the remaining clusters in the forest. \n",
"The following methods are supported in Scipy for calculating the distance between the newly formed cluster and each:\n",
" - single\n",
" - complete\n",
" - average\n",
" - weighted\n",
" - centroid\n",
" \n",
" \n",
"We use __complete__ for our case, but feel free to change it to see how the results change."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pylab\n",
"import scipy.cluster.hierarchy\n",
"Z = hierarchy.linkage(D, 'complete')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Essentially, Hierarchical clustering does not require a pre-specified number of clusters. However, in some applications we want a partition of disjoint clusters just as in flat clustering.\n",
"So you can use a cutting line:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.cluster.hierarchy import fcluster\n",
"max_d = 3\n",
"clusters = fcluster(Z, max_d, criterion='distance')\n",
"clusters"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Also, you can determine the number of clusters directly:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.cluster.hierarchy import fcluster\n",
"k = 5\n",
"clusters = fcluster(Z, k, criterion='maxclust')\n",
"clusters\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, plot the dendrogram:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = pylab.figure(figsize=(18,50))\n",
"def llf(id):\n",
" return '[%s %s %s]' % (pdf['manufact'][id], pdf['model'][id], int(float(pdf['type'][id])) )\n",
" \n",
"dendro = hierarchy.dendrogram(Z, leaf_label_func=llf, leaf_rotation=0, leaf_font_size =12, orientation = 'right')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"clustering_using_skl\">Clustering using scikit-learn</h2>\n",
"Lets redo it again, but this time using scikit-learn package:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dist_matrix = distance_matrix(feature_mtx,feature_mtx) \n",
"print(dist_matrix)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we can use the 'AgglomerativeClustering' function from scikit-learn library to cluster the dataset. The AgglomerativeClustering performs a hierarchical clustering using a bottom up approach. The linkage criteria determines the metric used for the merge strategy:\n",
"\n",
"- Ward minimizes the sum of squared differences within all clusters. It is a variance-minimizing approach and in this sense is similar to the k-means objective function but tackled with an agglomerative hierarchical approach.\n",
"- Maximum or complete linkage minimizes the maximum distance between observations of pairs of clusters.\n",
"- Average linkage minimizes the average of the distances between all observations of pairs of clusters."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"agglom = AgglomerativeClustering(n_clusters = 6, linkage = 'complete')\n",
"agglom.fit(feature_mtx)\n",
"agglom.labels_"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And, we can add a new field to our dataframe to show the cluster of each row:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pdf['cluster_'] = agglom.labels_\n",
"pdf.head()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.cm as cm\n",
"n_clusters = max(agglom.labels_)+1\n",
"colors = cm.rainbow(np.linspace(0, 1, n_clusters))\n",
"cluster_labels = list(range(0, n_clusters))\n",
"\n",
"# Create a figure of size 6 inches by 4 inches.\n",
"plt.figure(figsize=(16,14))\n",
"\n",
"for color, label in zip(colors, cluster_labels):\n",
" subset = pdf[pdf.cluster_ == label]\n",
" for i in subset.index:\n",
" plt.text(subset.horsepow[i], subset.mpg[i],str(subset['model'][i]), rotation=25) \n",
" plt.scatter(subset.horsepow, subset.mpg, s= subset.price*10, c=color, label='cluster'+str(label),alpha=0.5)\n",
"# plt.scatter(subset.horsepow, subset.mpg)\n",
"plt.legend()\n",
"plt.title('Clusters')\n",
"plt.xlabel('horsepow')\n",
"plt.ylabel('mpg')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see, we are seeing the distribution of each cluster using the scatter plot, but it is not very clear where is the centroid of each cluster. Moreover, there are 2 types of vehicles in our dataset, \"truck\" (value of 1 in the type column) and \"car\" (value of 1 in the type column). So, we use them to distinguish the classes, and summarize the cluster. First we count the number of cases in each group:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pdf.groupby(['cluster_','type'])['cluster_'].count()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can look at the characteristics of each cluster:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"agg_cars = pdf.groupby(['cluster_','type'])['horsepow','engine_s','mpg','price'].mean()\n",
"agg_cars"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"It is obvious that we have 3 main clusters with the majority of vehicles in those.\n",
"\n",
"__Cars__:\n",
"- Cluster 1: with almost high mpg, and low in horsepower.\n",
"- Cluster 2: with good mpg and horsepower, but higher price than average.\n",
"- Cluster 3: with low mpg, high horsepower, highest price.\n",
" \n",
" \n",
" \n",
"__Trucks__:\n",
"- Cluster 1: with almost highest mpg among trucks, and lowest in horsepower and price.\n",
"- Cluster 2: with almost low mpg and medium horsepower, but higher price than average.\n",
"- Cluster 3: with good mpg and horsepower, low price.\n",
"\n",
"\n",
"Please notice that we did not use __type__ , and __price__ of cars in the clustering process, but Hierarchical clustering could forge the clusters and discriminate them with quite high accuracy."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(16,10))\n",
"for color, label in zip(colors, cluster_labels):\n",
" subset = agg_cars.loc[(label,),]\n",
" for i in subset.index:\n",
" plt.text(subset.loc[i][0]+5, subset.loc[i][2], 'type='+str(int(i)) + ', price='+str(int(subset.loc[i][3]))+'k')\n",
" plt.scatter(subset.horsepow, subset.mpg, s=subset.price*20, c=color, label='cluster'+str(label))\n",
"plt.legend()\n",
"plt.title('Clusters')\n",
"plt.xlabel('horsepow')\n",
"plt.ylabel('mpg')\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2>Want to learn more?</h2>\n",
"\n",
"IBM SPSS Modeler is a comprehensive analytics platform that has many machine learning algorithms. It has been designed to bring predictive intelligence to decisions made by individuals, by groups, by systems – by your enterprise as a whole. A free trial is available through this course, available here: <a href=\"http://cocl.us/ML0101EN-SPSSModeler\">SPSS Modeler</a>\n",
"\n",
"Also, you can use Watson Studio to run these notebooks faster with bigger datasets. Watson Studio is IBM's leading cloud solution for data scientists, built by data scientists. With Jupyter notebooks, RStudio, Apache Spark and popular libraries pre-packaged in the cloud, Watson Studio enables data scientists to collaborate on their projects without having to install anything. Join the fast-growing community of Watson Studio users today with a free account at <a href=\"https://cocl.us/ML0101EN_DSX\">Watson Studio</a>\n",
"\n",
"<h3>Thanks for completing this lesson!</h3>\n",
"\n",
"<h4>Author: <a href=\"https://ca.linkedin.com/in/saeedaghabozorgi\">Saeed Aghabozorgi</a></h4>\n",
"<p><a href=\"https://ca.linkedin.com/in/saeedaghabozorgi\">Saeed Aghabozorgi</a>, PhD is a Data Scientist in IBM with a track record of developing enterprise level applications that substantially increases clients’ ability to turn data into actionable knowledge. He is a researcher in data mining field and expert in developing advanced analytic methods like machine learning and statistical modelling on large datasets.</p>\n",
"\n",
"<hr>\n",
"\n",
"<p>Copyright &copy; 2018 <a href=\"https://cocl.us/DX0108EN_CC\">Cognitive Class</a>. This notebook and its source code are released under the terms of the <a href=\"https://bigdatauniversity.com/mit-license/\">MIT License</a>.</p>"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python",
"language": "python",
"name": "conda-env-python-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.10"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment