{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Unsupervised learning - K-means application\n",
    "Goal of the excercise is to learn how to use K-means implementation in the Scikit-learn library to perform clustering and subsequent cluster analysis on a Titanic dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "x6XOUhvFa-wT"
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import sklearn\n",
    "import sklearn.preprocessing, sklearn.cluster, sklearn.metrics\n",
    "import scipy.spatial\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "#### Data Dictionary\n",
    "\n",
    "|Variable|Definition|Key|\n",
    "|:-------|:-------|:--------|\n",
    "|survival|Survival|0 = No, 1 = Yes|\n",
    "|pclass|Ticket class|1 = 1st, 2 = 2nd, 3 = 3rd|\n",
    "|sex|Sex||\n",
    "|Age|Age in years||\n",
    "|sibsp|# of siblings / spouses aboard the Titanic||\n",
    "|parch|# of parents / children aboard the Titanic||\n",
    "|ticket|Ticket number||\n",
    "|fare|Passenger fare||\n",
    "|cabin|Cabin number||\n",
    "|embarked|Port of Embarkation|C = Cherbourg, Q = Queenstown, S = Southampton|\n",
    "\n",
    "**pclass**: A proxy for socio-economic status (SES)\n",
    "1st = Upper\n",
    "2nd = Middle\n",
    "3rd = Lower\n",
    "\n",
    "**age**: Age is fractional if less than 1. If the age is estimated, is it in the form of xx.5\n",
    "\n",
    "**sibsp**: The dataset defines family relations in this way...\n",
    "Sibling = brother, sister, stepbrother, stepsister\n",
    "Spouse = husband, wife (mistresses and fiancés were ignored)\n",
    "\n",
    "**parch**: The dataset defines family relations in this way...\n",
    "Parent = mother, father\n",
    "Child = daughter, son, stepdaughter, stepson\n",
    "Some children travelled only with a nanny, therefore parch=0 for them."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load titanic dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv('titanic.csv', index_col=0)\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### How many missing values are in there?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.isna().sum().sort_values(ascending=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## We are going to cluster the passangers into defined number of groups\n",
    "- It is clear that it is mandatory to select only a relevant subset of features and encode the categorical features as in the classification task performed in one of the previous lectures"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_clustering = df[['Survived', 'Pclass','Sex','Age','SibSp','Parch','Fare','Embarked']].copy()\n",
    "df_clustering = df_clustering.dropna()\n",
    "df_clustering.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_clustering.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_clustering.describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Lets encode categorical features\n",
    "- https://scikit-learn.org/stable/modules/preprocessing.html#preprocessing\n",
    "- https://scikit-learn.org/stable/modules/classes.html?highlight=preprocessing#module-sklearn.preprocessing\n",
    "\n",
    "We will use the same encoding methodology as in the classification lecture."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "enc = sklearn.preprocessing.OrdinalEncoder()\n",
    "enc.fit_transform(df_clustering[['Sex']])[:20]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "enc.categories_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "enc = sklearn.preprocessing.OneHotEncoder(sparse=False)\n",
    "enc.fit_transform(df_clustering[['Embarked']])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "enc.categories_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.get_dummies(df_clustering[['Embarked']]).head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_encoded = pd.DataFrame(index = df_clustering.index)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_encoded['Sex'] = sklearn.preprocessing.OrdinalEncoder().fit_transform(df_clustering[['Sex']])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_encoded = df_encoded.join(pd.get_dummies(df_clustering[['Embarked']]))\n",
    "df_encoded.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### It is important to select the appropriate scaling method of the number features\n",
    "- There are many ways how to do this - MinMax, StandardScaler, PowerTransform, ...\n",
    "- This step heavily depends on a domain knowledge because the scales of the features have significant effect on a distances between couples of dataset instances\n",
    "    - It is clear that if one variable is in range (0,1) and the second one is in a range (5000, 10 000), the difference in the second feature will be definitely more important than in the  first one from the numerical point of view\n",
    "    - Although it is possible that from the domain point of view the first variable may be more important\n",
    "    - Thus it is a good idea to at least transform the features into a simiiar scales so the effect on the distance value would be similiar\n",
    "    - Transformation depends heavily on the statistical distribution of the feature\n",
    "        - You can use PowerTransform for a heavy-tailed distribution, Standardization or MinMax normalization for normally distributed features etc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_clustering.Fare.hist(bins=20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_clustering.Fare.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "enc = sklearn.preprocessing.PowerTransformer()\n",
    "enc.fit_transform(df_clustering[['Fare']])[:20]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_encoded['Fare'] = sklearn.preprocessing.PowerTransformer().fit_transform(df_clustering[['Fare']])\n",
    "df_encoded.Fare.hist(bins=20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_encoded.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_clustering.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_encoded['Age'] = sklearn.preprocessing.minmax_scale(df_clustering.Age)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_encoded = df_encoded.join(df_clustering[['Survived', 'Pclass', 'SibSp', 'Parch']])\n",
    "df_encoded.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Check our preprocessed data by describe data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_encoded.describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Clustering\n",
    "\n",
    "Use **Elbow method** to identify potentially ideal number of clusters in our data in **KMeans** algorithm.\n",
    "\n",
    "There are two basic methods for evaluation of clusters quality:\n",
    "1. SSE - Sum of squared distances of samples to their closest cluster center, this one is specific for **KMeans** algorithm. You can find it as **inertia_** attribute of KMeans sklearn object.\n",
    "2. Silhouette Coefficient - calculated using the mean intra-cluster distance and the mean nearest-cluster distance\n",
    "\n",
    "We ussually want to find number of clusters with low SSE and high Silhoutte coef.\n",
    "\n",
    "- Take a look at [this](https://towardsdatascience.com/silhouette-coefficient-validating-clustering-techniques-e976bb81d10c) and [this](https://towardsdatascience.com/k-means-clustering-from-a-to-z-f6242a314e9a)\n",
    "\n",
    "#### Try different number of clusters from range <2, 10> for KMeans algorithm, save both evaluation criteria and plot dependency of criteria to number of clusters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = df_encoded.values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "clustering_scores = []\n",
    "for k in range(2, 11):\n",
    "    clustering = sklearn.cluster.KMeans(n_clusters=k).fit(X)\n",
    "    clustering_scores.append({\n",
    "        'k': k,\n",
    "        'sse': clustering.inertia_,\n",
    "        'silhouette': sklearn.metrics.silhouette_score(X, clustering.labels_)\n",
    "    })\n",
    "df_clustering_scores = pd.DataFrame.from_dict(clustering_scores, orient='columns')\n",
    "df_clustering_scores = df_clustering_scores.set_index('k')\n",
    "df_clustering_scores.sse.plot()\n",
    "plt.figure()\n",
    "df_clustering_scores.silhouette.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create k-means clustering using selected number of clusters"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### How big are our clusters? How many 0, 1, .. are in vector?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# hint: clustering.labels_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Explore clusters\n",
    "Try to use cluster information and exploration analysis of our data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# add new column named 'cluster_id' into df_clustering. Use values from clustering.labels_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Use groupby function to cluster_id and decribe function for both numerical and categorical features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with pd.option_context('display.max_columns', None):\n",
    "    display(df_clustering.groupby('cluster_id').describe())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with pd.option_context('display.max_columns', None):\n",
    "    display(df_clustering.groupby('cluster_id').describe(include='O'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### What can we see from previous tables?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Create additional plots showing value of different attributes based on cluster group\n",
    "\n",
    "- Is Fare different for points in different clusters?\n",
    "- Is Age different for point in different clusters?\n",
    "- Does number of suvival differ in clusters?\n",
    "- Does number of passanger of each class differ in clusters?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Q: Is Fare different for points in different clusters?\n",
    "\n",
    "- A: ....."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hint: boxplot"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Q: Is Age different for point in different clusters?\n",
    "\n",
    "- A: ....."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hint: boxplot"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Q: Does number of suvival differ in clusters?\n",
    "\n",
    "- A: ....."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hint: countplot"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Q: Does number of passanger of each class differ in clusters?\n",
    "\n",
    "- A: ....."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hint: countplot"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Write a textual description of clusters"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Is our data represented in the best way?\n",
    "\n",
    "Clustering methods depends on calculation of distance metric among data points in our data matrix.\n",
    "\n",
    "Therefore it is necessary to preproces our data matrix **X** in a best way possible to achive equal distance for every dataset feature. After such transformation we can count, that difference in age has same impact as difference in ticket class. Generally, it is very hard to create perfect tranformation for our real dataset.\n",
    "\n",
    "#### Use StandardScaler transformation for our data **X**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "col_names = ['Fare', 'Age', 'SibSp', 'Parch']\n",
    "enc = sklearn.preprocessing.StandardScaler()\n",
    "X_stand = pd.DataFrame(enc.fit_transform(df_clustering.loc[:, col_names]), columns = col_names, index=df_clustering.index)\n",
    "X_stand = pd.concat([X_stand, df_encoded.loc[:, ['Sex', 'Embarked_C', 'Embarked_Q', 'Embarked_S']], df_clustering.Survived], axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_stand"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_stand.describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Task (2p)\n",
    "- Use **KMeans** to differently preprocessed data matrix **X_stand**\n",
    "- Detect \"ideal\" number of clusters using Elbow method\n",
    "- Explore detected clusters and **describe** them to the Markdown cell\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "cv4.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "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.7.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
