{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", " \n", "## [mlcourse.ai](https://mlcourse.ai) – Open Machine Learning Course \n", "\n", "Authors: [Olga Daykhovskaya](https://www.linkedin.com/in/odaykhovskaya/), [Yury Kashnitskiy](https://yorko.github.io). This material is subject to the terms and conditions of the [Creative Commons CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) license. Free use is permitted for any non-commercial purpose." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#
Assignment #7 (demo)\n", "##
Unupervised learning\n", "\n", "**Same assignment as a [Kaggle Kernel](https://www.kaggle.com/kashnitsky/a7-demo-unsupervised-learning) + [solution](https://www.kaggle.com/kashnitsky/a7-demo-unsupervised-learning-solution).**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this task, we will look at how data dimensionality reduction and clustering methods work. At the same time, we'll practice solving classification task again.\n", "\n", "We will work with the [Samsung Human Activity Recognition](https://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones) dataset. Download the data [here](https://drive.google.com/file/d/14RukQ0ylM2GCdViUHBBjZ2imCaYcjlux/view?usp=sharing). The data comes from accelerometers and gyros of Samsung Galaxy S3 mobile phones ( you can find more info about the features using the link above), the type of activity of a person with a phone in his/her pocket is also known – whether he/she walked, stood, lay, sat or walked up or down the stairs.\n", "\n", "First, we pretend that the type of activity is unknown to us, and we will try to cluster people purely on the basis of available features. Then we solve the problem of determining the type of physical activity as a classification problem.\n", "\n", "Fill the code where needed (\"Your code is here\") and answer the questions in the [web form](https://docs.google.com/forms/d/1wBf5UoRndv6PpzIwYnM9f0ysoGa4Yqcqle-HBlBP5QQ/edit)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import seaborn as sns\n", "from tqdm import tqdm_notebook\n", "\n", "%matplotlib inline\n", "from matplotlib import pyplot as plt\n", "\n", "plt.style.use([\"seaborn-darkgrid\"])\n", "plt.rcParams[\"figure.figsize\"] = (12, 9)\n", "plt.rcParams[\"font.family\"] = \"DejaVu Sans\"\n", "\n", "from sklearn import metrics\n", "from sklearn.cluster import AgglomerativeClustering, KMeans, SpectralClustering\n", "from sklearn.decomposition import PCA\n", "from sklearn.model_selection import GridSearchCV\n", "from sklearn.preprocessing import StandardScaler\n", "from sklearn.svm import LinearSVC\n", "\n", "RANDOM_STATE = 17" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "PATH_TO_SAMSUNG_DATA = \"../../data/samsung_HAR\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X_train = np.loadtxt(os.path.join(PATH_TO_SAMSUNG_DATA, \"samsung_train.txt\"))\n", "y_train = np.loadtxt(\n", " os.path.join(PATH_TO_SAMSUNG_DATA, \"samsung_train_labels.txt\")\n", ").astype(int)\n", "\n", "X_test = np.loadtxt(os.path.join(PATH_TO_SAMSUNG_DATA, \"samsung_test.txt\"))\n", "y_test = np.loadtxt(\n", " os.path.join(PATH_TO_SAMSUNG_DATA, \"samsung_test_labels.txt\")\n", ").astype(int)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Checking dimensions\n", "assert X_train.shape == (7352, 561) and y_train.shape == (7352,)\n", "assert X_test.shape == (2947, 561) and y_test.shape == (2947,)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For clustering, we do not need a target vector, so we'll work with the combination of training and test samples. Merge `X_train` with `X_test`, and `y_train` with `y_test`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Define the number of unique values of the labels of the target class." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# np.unique(y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# n_classes = np.unique(y).size" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[These labels correspond to:](https://archive.ics.uci.edu/ml/machine-learning-databases/00240/UCI%20HAR%20Dataset.names)\n", "- 1 – walking\n", "- 2 – walking upstairs\n", "- 3 – walking downstairs\n", "- 4 – sitting\n", "- 5 – standing\n", "- 6 – laying down" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Scale the sample using `StandardScaler` with default parameters." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Reduce the number of dimensions using PCA, leaving as many components as necessary to explain at least 90% of the variance of the original (scaled) data. Use the scaled dataset and fix `random_state` (RANDOM_STATE constant)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "# pca =\n", "# X_pca =" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Question 1: **
\n", "What is the minimum number of principal components required to cover the 90% of the variance of the original (scaled) data?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Answer options:**\n", "- 56 \n", "- 65\n", "- 66\n", "- 193" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Вопрос 2:**
\n", "What percentage of the variance is covered by the first principal component? Round to the nearest percent.\n", "\n", "**Answer options:**\n", "- 45\n", "- 51 \n", "- 56\n", "- 61" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Visualize data in projection on the first two principal components." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "# plt.scatter(, , c=y, s=20, cmap='viridis');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 3:**
\n", "If everything worked out correctly, you will see a number of clusters, almost perfectly separated from each other. What types of activity are included in these clusters?
\n", "\n", "**Answer options:**\n", "- 1 cluster: all 6 activities\n", "- 2 clusters: (walking, walking upstairs, walking downstairs ) and (sitting, standing, laying)\n", "- 3 clusters: (walking), (walking upstairs, walking downstairs) and (sitting, standing, laying)\n", "- 6 clusters" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "------------------------------" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Perform clustering with the `KMeans` method, training the model on data with reduced dimensionality (by PCA). In this case, we will give a clue to look for exactly 6 clusters, but in general case we will not know how many clusters we should be looking for.\n", "\n", "Options:\n", "\n", "- ** n_clusters ** = n_classes (number of unique labels of the target class)\n", "- ** n_init ** = 100\n", "- ** random_state ** = RANDOM_STATE (for reproducibility of the result)\n", "\n", "Other parameters should have default values." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Visualize data in projection on the first two principal components. Color the dots according to the clusters obtained." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here\n", "# plt.scatter(, , c=cluster_labels, s=20, cmap='viridis');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Look at the correspondence between the cluster marks and the original class labels and what kinds of activities the `KMeans` algorithm is confused at." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# tab = pd.crosstab(y, cluster_labels, margins=True)\n", "# tab.index = ['walking', 'going up the stairs',\n", "# 'going down the stairs', 'sitting', 'standing', 'laying', 'all']\n", "# tab.columns = ['cluster' + str(i + 1) for i in range(6)] + ['all']\n", "# tab" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see that for each class (i.e., each activity) there are several clusters. Let's look at the maximum percentage of objects in a class that are assigned to a single cluster. This will be a simple metric that characterizes how easily the class is separated from others when clustering.\n", "\n", "Example: if for class \"walking downstairs\" (with 1406 instances belonging to it), the distribution of clusters is:\n", " - cluster 1 - 900\n", " - cluster 3 - 500\n", " - cluster 6 - 6,\n", " \n", "then such a share will be 900/1406 $ \\approx $ 0.64.\n", " \n", "\n", "** Question 4: **
\n", "Which activity is separated from the rest better than others based on the simple metric described above?
\n", "\n", "**Answer:**\n", "- walking\n", "- standing\n", "- walking downstairs\n", "- all three options are incorrect" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It can be seen that kMeans does not distinguish activities very well. Use the elbow method to select the optimal number of clusters. Parameters of the algorithm and the data we use are the same as before, we change only `n_clusters`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# # Your code here\n", "# inertia = []\n", "# for k in tqdm_notebook(range(1, n_classes + 1)):\n", "# pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Question 5: **
\n", "How many clusters can we choose according to the elbow method?
\n", "\n", "**Answer options:**\n", "- 1\n", "- 2\n", "- 3\n", "- 4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "------------------------" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's try another clustering algorithm, described in the article – agglomerative clustering." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ag = AgglomerativeClustering(n_clusters=n_classes,\n", "# linkage='ward').fit(X_pca)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Calculate the Adjusted Rand Index (`sklearn.metrics`) for the resulting clustering and for ` KMeans` with the parameters from the 4th question." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Question 6: **
\n", "Select all the correct statements.
\n", "\n", "** Answer options: **\n", "- According to ARI, KMeans handled clustering worse than Agglomerative Clustering \n", "- For ARI, it does not matter which tags are assigned to the cluster, only the partitioning of instances into clusters matters \n", "- In case of random partitioning into clusters, ARI will be close to zero " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "-------------------------------" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can notice that the task is not very well solved when we try to detect several clusters (> 2). Now, let's solve the classification problem, given that the data is labeled.\n", "\n", "For classification, use the support vector machine – class `sklearn.svm.LinearSVC`. In this course, we didn't study this algorithm separately, but it is well-known and you can read about it, for example [here](http://cs231n.github.io/linear-classify/#svmvssoftmax).\n", "\n", "Choose the `C` hyperparameter for` LinearSVC` using `GridSearchCV`.\n", "\n", "- Train the new `StandardScaler` on the training set (with all original features), apply scaling to the test set\n", "- In `GridSearchCV`, specify `cv` = 3." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# # Your code here\n", "# scaler = StandardScaler()\n", "# X_train_scaled =\n", "# X_test_scaled =" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "svc = LinearSVC(random_state=RANDOM_STATE)\n", "svc_params = {\"C\": [0.001, 0.01, 0.1, 1, 10]}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# %%time\n", "# # Your code here\n", "# best_svc = None" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# best_svc.best_params_, best_svc.best_score_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 7**
\n", "Which value of the hyperparameter `C` was chosen the best on the basis of cross-validation?
\n", "\n", "**Answer options:**\n", "- 0.001\n", "- 0.01\n", "- 0.1 \n", "- 1\n", "- 10" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# y_predicted = best_svc.predict(X_test_scaled)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# tab = pd.crosstab(y_test, y_predicted, margins=True)\n", "# tab.index = ['walking', 'climbing up the stairs',\n", "# 'going down the stairs', 'sitting', 'standing', 'laying', 'all']\n", "# tab.columns = ['walking', 'climbing up the stairs',\n", "# 'going down the stairs', 'sitting', 'standing', 'laying', 'all']\n", "# tab" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Question 8: **
\n", "Which activity type is worst detected by SVM in terms of precision? Recall?
\n", "\n", "**Answer options:**\n", "- precision – going up the stairs, recall – laying\n", "- precision – laying, recall – sitting\n", "- precision – walking, recall – walking\n", "- precision – standing, recall – sitting " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, do the same thing as in Question 7, but add PCA.\n", "\n", "- Use `X_train_scaled` and` X_test_scaled`\n", "- Train the same PCA as before, on the scaled training set, apply scaling to the test set\n", "- Choose the hyperparameter `C` via cross-validation on the training set with PCA-transformation. You will notice how much faster it works now.\n", "\n", "** Question 9: **
\n", "What is the difference between the best quality (accuracy) for cross-validation in the case of all 561 initial characteristics and in the second case, when the principal component method was applied? Round to the nearest percent.
\n", "\n", "** Options: **\n", "- quality is the same\n", "- 2%\n", "- 4%\n", "- 10%\n", "- 20%" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your code here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Question 10: **
\n", "Select all the correct statements:\n", "\n", "** Answer options: **\n", "- Principal component analysis in this case allowed to reduce the model training time, while the quality (mean cross-validation accuracy) suffered greatly, by more than 10%\n", "- PCA can be used to visualize data, but there are better methods for this task, for example, tSNE. However, PCA has lower computational complexity \n", "- PCA builds linear combinations of initial features, and in some applications they might be poorly interpreted by humans " ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "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.1" } }, "nbformat": 4, "nbformat_minor": 2 }