{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Case Study - Titanic Survival" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Feature Extraction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we will talk about an important piece of machine learning: the extraction of\n", "quantitative features from data. By the end of this section you will\n", "\n", "- Know how features are extracted from real-world data.\n", "- See an example of extracting numerical features from textual data\n", "\n", "In addition, we will go over several basic tools within scikit-learn which can be used to accomplish the above tasks." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What Are Features?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Numerical Features" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Recall that data in scikit-learn is expected to be in two-dimensional arrays, of size\n", "**n_samples** $\\times$ **n_features**.\n", "\n", "Previously, we looked at the iris dataset, which has 150 samples and 4 features" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.datasets import load_iris\n", "\n", "iris = load_iris()\n", "print(iris.data.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These features are:\n", "\n", "- sepal length in cm\n", "- sepal width in cm\n", "- petal length in cm\n", "- petal width in cm\n", "\n", "Numerical features such as these are pretty straightforward: each sample contains a list\n", "of floating-point numbers corresponding to the features" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Categorical Features" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What if you have categorical features? For example, imagine there is data on the color of each\n", "iris:\n", "\n", " color in [red, blue, purple]\n", "\n", "You might be tempted to assign numbers to these features, i.e. *red=1, blue=2, purple=3*\n", "but in general **this is a bad idea**. Estimators tend to operate under the assumption that\n", "numerical features lie on some continuous scale, so, for example, 1 and 2 are more alike\n", "than 1 and 3, and this is often not the case for categorical features.\n", "\n", "In fact, the example above is a subcategory of \"categorical\" features, namely, \"nominal\" features. Nominal features don't imply an order, whereas \"ordinal\" features are categorical features that do imply an order. An example of ordinal features would be T-shirt sizes, e.g., XL > L > M > S. \n", "\n", "One work-around for parsing nominal features into a format that prevents the classification algorithm from asserting an order is the so-called one-hot encoding representation. Here, we give each category its own dimension. \n", "\n", "The enriched iris feature set would hence be in this case:\n", "\n", "- sepal length in cm\n", "- sepal width in cm\n", "- petal length in cm\n", "- petal width in cm\n", "- color=purple (1.0 or 0.0)\n", "- color=blue (1.0 or 0.0)\n", "- color=red (1.0 or 0.0)\n", "\n", "Note that using many of these categorical features may result in data which is better\n", "represented as a **sparse matrix**, as we'll see with the text classification example\n", "below." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Using the DictVectorizer to encode categorical features" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When the source data is encoded has a list of dicts where the values are either strings names for categories or numerical values, you can use the `DictVectorizer` class to compute the boolean expansion of the categorical features while leaving the numerical features unimpacted:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "measurements = [\n", " {'city': 'Dubai', 'temperature': 33.},\n", " {'city': 'London', 'temperature': 12.},\n", " {'city': 'San Francisco', 'temperature': 18.},\n", "]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.feature_extraction import DictVectorizer\n", "\n", "vec = DictVectorizer()\n", "vec" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "vec.fit_transform(measurements).toarray()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "vec.get_feature_names()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Derived Features" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another common feature type are **derived features**, where some pre-processing step is\n", "applied to the data to generate features that are somehow more informative. Derived\n", "features may be based in **feature extraction** and **dimensionality reduction** (such as PCA or manifold learning),\n", "may be linear or nonlinear combinations of features (such as in polynomial regression),\n", "or may be some more sophisticated transform of the features." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Combining Numerical and Categorical Features" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As an example of how to work with both categorical and numerical data, we will perform survival predicition for the passengers of the HMS Titanic.\n", "\n", "We will use a version of the Titanic (titanic3.xls) from [here](http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.xls). We converted the .xls to .csv for easier manipulation but left the data is otherwise unchanged.\n", "\n", "We need to read in all the lines from the (titanic3.csv) file, set aside the keys from the first line, and find our labels (who survived or died) and data (attributes of that person). Let's look at the keys and some corresponding example lines." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "\n", "titanic = pd.read_csv(os.path.join('datasets', 'titanic3.csv'))\n", "print(titanic.columns)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is a broad description of the keys and what they mean:\n", "\n", "```\n", "pclass Passenger Class\n", " (1 = 1st; 2 = 2nd; 3 = 3rd)\n", "survival Survival\n", " (0 = No; 1 = Yes)\n", "name Name\n", "sex Sex\n", "age Age\n", "sibsp Number of Siblings/Spouses Aboard\n", "parch Number of Parents/Children Aboard\n", "ticket Ticket Number\n", "fare Passenger Fare\n", "cabin Cabin\n", "embarked Port of Embarkation\n", " (C = Cherbourg; Q = Queenstown; S = Southampton)\n", "boat Lifeboat\n", "body Body Identification Number\n", "home.dest Home/Destination\n", "```\n", "\n", "In general, it looks like `name`, `sex`, `cabin`, `embarked`, `boat`, `body`, and `homedest` may be candidates for categorical features, while the rest appear to be numerical features. We can also look at the first couple of rows in the dataset to get a better understanding:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "titanic.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We clearly want to discard the \"boat\" and \"body\" columns for any classification into survived vs not survived as they already contain this information. The name is unique to each person (probably) and also non-informative. For a first try, we will use \"pclass\", \"sibsp\", \"parch\", \"fare\" and \"embarked\" as our features:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "labels = titanic.survived.values\n", "features = titanic[['pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked']]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "features.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The data now contains only useful features, but they are not in a format that the machine learning algorithms can understand. We need to transform the strings \"male\" and \"female\" into binary variables that indicate the gender, and similarly for \"embarked\".\n", "We can do that using the pandas ``get_dummies`` function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pd.get_dummies(features).head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This transformation successfully encoded the string columns. However, one might argue that the class is also a categorical variable. We can explicitly list the columns to encode using the ``columns`` parameter, and include ``pclass``:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "features_dummies = pd.get_dummies(features, columns=['pclass', 'sex', 'embarked'])\n", "features_dummies.head(n=16)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "data = features_dummies.values" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "np.isnan(data).any()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With all of the hard data loading work out of the way, evaluating a classifier on this data becomes straightforward. Setting up the simplest possible model, we want to see what the simplest score can be with `DummyClassifier`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from sklearn.model_selection import train_test_split\n", "from sklearn.preprocessing import Imputer\n", "\n", "\n", "train_data, test_data, train_labels, test_labels = train_test_split(\n", " data, labels, random_state=0)\n", "\n", "imp = Imputer()\n", "imp.fit(train_data)\n", "train_data_finite = imp.transform(train_data)\n", "test_data_finite = imp.transform(test_data)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.isnan(train_data_finite).any()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.dummy import DummyClassifier\n", "\n", "clf = DummyClassifier('most_frequent')\n", "clf.fit(train_data_finite, train_labels)\n", "print(\"Prediction accuracy: %f\"\n", " % clf.score(test_data_finite, test_labels))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " EXERCISE:\n", " \n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "deletable": true, "editable": true }, "outputs": [], "source": [ "# %load solutions/10_titanic.py" ] } ], "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.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }