python_reference/tutorials/python_data_entry_point.ipynb

1603 lines
342 KiB
Plaintext
Raw Normal View History

2014-06-25 22:06:16 +00:00
{
"metadata": {
"name": "",
2014-06-26 21:41:00 +00:00
"signature": "sha256:ea0d498feb91238c4ac1c1b582ca9e09d18639ea850f6cd2cbd12081785e39e5"
2014-06-25 22:06:16 +00:00
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Sebastian Raschka](http://sebastianraschka.com) \n",
"\n",
2014-06-26 14:41:36 +00:00
"- [Open in IPython nbviewer](http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/python_data_entry_point.ipynb?create=1) \n",
2014-06-25 22:06:16 +00:00
"\n",
2014-06-26 14:41:36 +00:00
"- [Link to this IPython notebook on Github](https://github.com/rasbt/python_reference/blob/master/tutorials/python_data_entry_point.ipynb) \n",
2014-06-25 22:06:16 +00:00
"\n",
"- [Link to the GitHub Repository pattern_classification](http://nbviewer.ipython.org/github/rasbt/pattern_classification/blob/master/python_howtos/)"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import time\n",
"import platform\n",
"print('Last updated: %s' %time.strftime('%d/%m/%Y'))\n",
"print('Created using Python', platform.python_version())"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
2014-06-26 12:58:21 +00:00
"Last updated: 26/06/2014\n",
2014-06-25 22:06:16 +00:00
"Created using Python 3.4.1\n"
]
}
],
"prompt_number": 1
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n",
"I would be happy to hear your comments and suggestions. \n",
"Please feel free to drop me a note via\n",
"[twitter](https://twitter.com/rasbt), [email](mailto:bluewoodtree@gmail.com), or [google+](https://plus.google.com/+SebastianRaschka).\n",
"<hr>"
]
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Entry point: Data "
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"- Using Python's sci-packages to prepare data for Machine Learning tasks and other data analyses"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this short tutorial I want to provide a short overview of some of my favorite Python tools for common procedures as entry points for general pattern classification and machine learning tasks, and various other data analyses. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Sections"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- [Installing Python packages](#Installing-Python-packages)\n",
"\n",
"- [About the dataset](#About-the-dataset)\n",
"\n",
"- [Downloading and saving CSV data files from the web](#Downloading-and-savin-CSV-data-files-from-the-web)\n",
"\n",
"- [Reading in a dataset from a CSV file](#Reading-in-a-dataset-from-a-CSV-file)\n",
"\n",
2014-06-26 04:24:05 +00:00
"- [Visualizating of a dataset](#Visualizating-of-a-data)\n",
2014-06-25 22:06:16 +00:00
"\n",
" - [Histograms](#Histograms)\n",
"\n",
" - [Scatterplots](#Scatterplots)\n",
"\n",
"- [Splitting into training and test dataset](#Splitting-into-training-and-test-dataset)\n",
"\n",
"- [Feature Scaling](#Feature-Scaling)\n",
"\n",
"- [Linear Transformation: Principal Component Analysis (PCA)](#PCA)\n",
"\n",
"- [Linear Transformation: Multiple Discrciminant Analysis (MDA)](#MDA)\n",
"\n",
"- [Simple Supervised Classification](#Simple-Supervised-Classification)\n",
"\n",
" - [Linear Discriminant Analysis as simple linear classifier](#Linear-Discriminant-Analysis-as-simple-linear-classifier)\n",
" \n",
" - [Classification Stochastic Gradient Descent (SGD)](#SGD)\n",
"\n",
2014-06-25 22:06:16 +00:00
"- [Saving the processed datasets](#Saving-the-processed-datasets)\n",
"\n",
" - [Pickle](#Pickle)\n",
"\n",
" - [Comma Separated Values (CSV)](#Comma-Separated-Values)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Installing Python packages"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**In this section want to recommend a way for installing the required Python-packages packages if you have not done so, yet. Otherwise you can skip this part.**\n",
"\n",
"The packages we will be using in this tutorial are:\n",
"\n",
"- [NumPy](http://www.numpy.org)\n",
"- [SciPy](http://www.scipy.org)\n",
"- [matplotlib](http://matplotlib.org)\n",
"- [scikit-learn](http://scikit-learn.org/stable/)\n",
"\n",
"Although they can be installed step-by-step \"manually\", but I highly recommend you to take a look at the [Anaconda](https://store.continuum.io/cshop/anaconda/) Python distribution for scientific computing.\n",
"\n",
"Anaconda is distributed by Continuum Analytics, but it is completely free and includes more than 195+ packages for science and data analysis as of today.\n",
"The installation procedure is nicely summarized here: http://docs.continuum.io/anaconda/install.html\n",
"\n",
"If this is too much, the [Miniconda](http://conda.pydata.org/miniconda.html) might be right for you. Miniconda is basically just a Python distribution with the Conda package manager, which let's us install a list of Python packages into a specified `conda` environment from the Shell terminal, e.g.,\n",
"\n",
"<pre>$[bash]> conda create -n myenv python=3\n",
"$[bash]> source activate myenv\n",
"$[bash]> conda install -n myenv numpy scipy matplotlib scikit-learn</pre>\n",
"\n",
"When we start \"python\" in your current shell session now, it will use the Python distribution in the virtual environment \"myenv\" that we have just created. To un-attach the virtual environment, you can just use\n",
"<pre>$[bash]> source deactivate myenv</pre>\n",
"\n",
"**Note:** environments will be created in ROOT_DIR/envs by default, you can use the `-p` instead of the `-n` flag in the conda commands above in order to specify a custom path.\n",
"\n",
"**I find this procedure very convenient, especially if you are working with different distributions and versions of Python with different modules and packages installed and it is extremely useful for testing your own modules.**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"About the dataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For the following tutorial, we will be working with the free \"Wine\" Dataset that is deposited on the UCI machine learning repository \n",
"(http://archive.ics.uci.edu/ml/datasets/Wine).\n",
2014-06-25 22:06:16 +00:00
"\n",
"<br>\n",
"\n",
"<font size=\"1\">\n",
"**Reference:**\n",
"Forina, M. et al, PARVUS - An Extendible Package for Data\n",
"Exploration, Classification and Correlation. Institute of Pharmaceutical\n",
"and Food Analysis and Technologies, Via Brigata Salerno, \n",
"16147 Genoa, Italy.</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Wine dataset consists of 3 different classes where each row correspond to a particular wine sample.\n",
"\n",
"The class labels (1, 2, 3) are listed in the first column, and the columns 2-14 correspond to the following 13 attributes (features):\n",
"\n",
"1) Alcohol \n",
"2) Malic acid \n",
"3) Ash \n",
"4) Alcalinity of ash \n",
"5) Magnesium \n",
"6) Total phenols \n",
"7) Flavanoids \n",
"8) Nonflavanoid phenols \n",
"9) Proanthocyanins \n",
"10) Color intensity \n",
"11) Hue \n",
"12) OD280/OD315 of diluted wines \n",
"13) Proline \n",
"\n",
"An excerpt from the wine_data.csv dataset:\n",
" \n",
"<pre>1,14.23,1.71,2.43,15.6,127,2.8,3.06,.28,2.29,5.64,1.04,3.92,1065\n",
"1,13.2,1.78,2.14,11.2,100,2.65,2.76,.26,1.28,4.38,1.05,3.4,1050\n",
"[...]\n",
"2,12.37,.94,1.36,10.6,88,1.98,.57,.28,.42,1.95,1.05,1.82,520\n",
"2,12.33,1.1,2.28,16,101,2.05,1.09,.63,.41,3.27,1.25,1.67,680\n",
"[...]\n",
"3,12.86,1.35,2.32,18,122,1.51,1.25,.21,.94,4.1,.76,1.29,630\n",
"3,12.88,2.99,2.4,20,104,1.3,1.22,.24,.83,5.4,.74,1.42,530</pre>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Downloading and saving CSV data files from the web"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Usually, we have our data stored locally on our disk in as a common text (or CSV) file with comma-, tab-, or whitespace-separated rows. Below is just an example for how you can CSV datafile from a HTML website directly into Python and optionally save it locally."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import csv\n",
"import urllib\n",
"\n",
"url = 'https://raw.githubusercontent.com/rasbt/pattern_classification/master/data/wine_data.csv'\n",
"csv_cont = urllib.request.urlopen(url)\n",
"csv_cont = csv_cont.read() #.decode('utf-8')\n",
"\n",
"# Optional: saving the data to your local drive\n",
"with open('./wine_data.csv', 'wb') as out:\n",
" out.write(csv_cont)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 2
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note:** If you'd rather like to work with the data directly in `str`ing format, you could just apply the `.decode('utf-8')` method to the data that was read in byte-format by default.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Reading in a dataset from a CSV file"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since it is quite typical to have the input data stored locally, as mentioned above, we will use the [`numpy.loadtxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html) function now to read in the data from the CSV file. \n",
"(alternatively [`np.genfromtxt()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html) could be used in similar way, it provides some additional options)"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import numpy as np\n",
"\n",
"# reading in all data into a NumPy array\n",
"all_data = np.loadtxt(open(\"./wine_data.csv\",\"r\"),\n",
" delimiter=\",\", \n",
" skiprows=0, \n",
" dtype=np.float64\n",
" )\n",
"\n",
"# load class labels from column 1\n",
"y_wine = all_data[:,0]\n",
"\n",
"# conversion of the class labels to integer-type array\n",
"y_wine = y_wine.astype(np.int64, copy=False)\n",
"\n",
"# load the 14 features\n",
"X_wine = all_data[:,1:]\n",
"\n",
"# printing some general information about the data\n",
"print('\\ntotal number of samples (rows):', X_wine.shape[0])\n",
"print('total number of features (columns):', X_wine.shape[1])\n",
"\n",
"# printing the 1st wine sample\n",
"float_formatter = lambda x: '{:.2f}'.format(x)\n",
"np.set_printoptions(formatter={'float_kind':float_formatter})\n",
"print('\\n1st sample (i.e., 1st row):\\nClass label: {:d}\\n{:}\\n'\n",
" .format(int(y_wine[0]), X_wine[0]))\n",
"\n",
"# printing the rel.frequency of the class labels\n",
"print('Class label frequencies')\n",
"print('Class 1 samples: {:.2%}'.format(list(y_wine).count(1)/y_wine.shape[0]))\n",
"print('Class 2 samples: {:.2%}'.format(list(y_wine).count(2)/y_wine.shape[0]))\n",
"print('Class 3 samples: {:.2%}'.format(list(y_wine).count(3)/y_wine.shape[0]))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n",
"total number of samples (rows): 178\n",
"total number of features (columns): 13\n",
"\n",
"1st sample (i.e., 1st row):\n",
"Class label: 1\n",
"[14.23 1.71 2.43 15.60 127.00 2.80 3.06 0.28 2.29 5.64 1.04 3.92 1065.00]\n",
"\n",
"Class label frequencies\n",
"Class 1 samples: 33.15%\n",
"Class 2 samples: 39.89%\n",
"Class 3 samples: 26.97%\n"
]
}
],
2014-06-26 21:41:00 +00:00
"prompt_number": 2
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
2014-06-26 04:24:05 +00:00
"Visualizating of a dataset"
2014-06-25 22:06:16 +00:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are endless way to visualize datasets for get an initial idea of how the data looks like. The most common ones are probably histograms and scatter plots."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Histograms"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Histograms are a useful data to explore the distribution of each feature across the different classes. This could provide us with intuitive insights which features have a good and not-so-good inter-class separation. Below, we will plot a sample histogram for the \"Alcohol content\" feature for the three wine classes."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%matplotlib inline"
],
"language": "python",
"metadata": {},
"outputs": [],
2014-06-26 21:41:00 +00:00
"prompt_number": 3
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from matplotlib import pyplot as plt\n",
"from math import floor, ceil # for rounding up and down\n",
"\n",
"plt.figure(figsize=(10,8))\n",
"\n",
2014-06-26 12:58:21 +00:00
"# bin width of the histogram in steps of 0.15\n",
"bins = np.arange(floor(min(X_wine[:,0])), ceil(max(X_wine[:,0])), 0.15)\n",
2014-06-25 22:06:16 +00:00
"\n",
"# get the max count for a particular bin for all classes combined\n",
"max_bin = max(np.histogram(X_wine[:,0], bins=bins)[0])\n",
"\n",
"# the order of the colors for each histogram\n",
"colors = ('blue', 'red', 'green')\n",
"\n",
"for label,color in zip(\n",
" range(1,4), colors):\n",
"\n",
" mean = np.mean(X_wine[:,0][y_wine == label]) # class sample mean\n",
" stdev = np.std(X_wine[:,0][y_wine == label]) # class standard deviation\n",
" plt.hist(X_wine[:,0][y_wine == label], \n",
" bins=bins, \n",
" alpha=0.3, # opacity level\n",
" label='class {} ($\\mu={:.2f}$, $\\sigma={:.2f}$)'.format(label, mean, stdev), \n",
" color=color)\n",
"\n",
"plt.ylim([0, max_bin*1.3])\n",
"plt.title('Wine data set - Distribution of alocohol contents')\n",
"plt.xlabel('alcohol by volume', fontsize=14)\n",
"plt.ylabel('count', fontsize=14)\n",
"plt.legend(loc='upper right')\n",
"\n",
"plt.show()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "display_data",
2014-06-26 21:41:00 +00:00
"png": "iVBORw0KGgoAAAANSUhEUgAAAmgAAAH8CAYAAABl8FOBAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XlcVnX+///nhRuhIFtIooBKpuJGWu5KWWoplU6aZi5T\nU2mLjeXHJSfFadHKdpsxrVTUFnHKMEsat5SyITV3k8SRxchBFAREEDi/P/p6/bzkuvTCDnLUx/12\n83bjep/3efE6h+u6eHrOuQ42wzAMAQAAwDI8qrsBAAAAOCKgAQAAWAwBDQAAwGIIaAAAABZDQAMA\nALAYAhoAAIDFENBw1di0aZNatGhxSb5XdHS0Pvjgg0vyvayudevW2rhxoym1li5dqr59+9ofe3h4\n6ODBg6bUliRvb28dOnTItHruKCoqUkxMjHx9fXXfffdVen2z98G5Ro8ereeee+6i1uV1AFw8Ahou\nWzNnztSdd97pMHb99dc7HVu2bJl69Oihn3/++ZL0ZrPZZLPZ3JobHh6udevWVXFHFf3RX+yHDh2S\nh4eHvL295e3treDgYMXExGjNmjUO83bv3q2ePXu6Vau8vPy884YPH67ExMSL7vlszsJDfn6+wsPD\nTanvruXLl+t///ufjh07pk8//fSSfm93VOa5bOa6F8Pd55G7Fi5cqB49ephSC6gsAhouW7169dL3\n33+vM/dazsrKUmlpqbZv325/g87KylJqauoFA0J1stlsqq77RZvxffPy8pSfn6+dO3fq9ttv18CB\nA7Vo0SLT+ykrK7vYFp26lMHhfNLS0tS8eXN5ePB2bBbuv44rAe8IuGx17NhRp0+f1vbt2yX9fgrz\nlltuUfPmzR3GIiIiFBwcrA0bNqhx48b29cPDw/Xaa6+pXbt28vX11dChQ1VcXGxf/uWXX6p9+/by\n8/NTt27dtGvXLpe9/Pvf/1aLFi3k6+urJ598UoZh2H9JpKam6tZbb1VgYKCuvfZaPfDAA8rLy5Mk\njRgxQunp6YqJiZG3t7dmz54tSRo8eLCuu+46+fr6qlevXtq7d6/L771w4UI1a9ZMPj4+atq0qT76\n6CP7sg8//FCtWrWSv7+/+vXrp/T0dEmyB9Z27drJ29tb8fHx7u94F4KCgjRu3DjFxsZq0qRJ9vGz\njxAmJyerY8eOql+/voKDgzVhwgSHfnx9feXj46MffvhBCxcuVLdu3fT0008rMDBQsbGxTo9orFq1\nSs2aNdO1116riRMn2vd7bGysRowYYZ935uhKWVmZpk6dqk2bNumJJ56Qt7e3xo0bJ8nxqGJeXp5G\njhypoKAghYeH68UXX7TXXrhwobp3767/+7//k7+/v5o2barVq1e73Df79u1TdHS0/Pz81Lp1a61c\nuVKSNH36dD3//PP69NNP5e3trQULFlRYNzk5WV26dJGfn58aNmyoJ598UqdPn3b6fc7XsyTNnz9f\nrVq1ko+PjyIjI/XTTz+dt78zjh07pgEDBsjHx0edO3d2OPL6/fff66abbpKvr69uvvlmbd682eV+\nOFt5ebleeuklRUREyMfHRx07dlRmZuYFa0ZHR2vatGnq3r27fHx81LdvX+Xk5EhyfB55e3vrP//5\njyTXrwPp95/5e++9p+bNm8vPz09PPPGEfZ+MHTtWmzdvlre3t/z9/SVJX331lSIjI+Xj46NGjRrp\ntddec2t7gUozgMvYLbfcYrzxxhuGYRjG448/bnz44YfG1KlTHcYeeughwzAMY/369UajRo3s64aH\nhxudOnUysrKyjGPHjhktW7Y05s6daxiGYWzbts0ICgoykpOTjfLycmPRokVGeHi4UVxcXKGH7Oxs\nw9vb2/jXv/5llJaWGm+88YZRs2ZN44MPPjAMwzAOHDhgrFmzxigpKTGys7ONnj17Gn/9618d+li7\ndq1DzQULFhgFBQVGSUmJ8de//tVo37690+0vKCgwfHx8jJSUFMMwDOO3334z9uzZYxiGYaxYscKI\niIgwfv75Z6OsrMx44YUXjK5du9rXtdlsRmpqaiX2tqP//ve/hs1mM8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fDdd9/Z\nlw8ZMsSYNWuWYRgVn2+GYRihoaHGe++9Z+Tl5TndLsAsnOLEZa1nz55KSkrS8ePHlZ2drWbNmqlL\nly76/vvvdfz4ce3Zs+e8158FBwfbv77mmmtUUFAg6ffrgl577TX5+fnZ/2VmZiorK6tCjV9//VWN\nGjVyGDv7VOqRI0c0dOhQNWrUSPXr19eIESPsp2ScKS8v1+TJkxUREaH69eurSZMmstlsOnr0aIW5\ndevW1aeffqq5c+eqYcOGGjBggPbv32/fhqeeesref0BAgCTp8OHDLr/32SIjI+0fAPjuu+/cWufs\n+mdOCZ3tgw8+UEpKilq2bKmbb75Zq1atOm+ts/ejO3NCQ0P166+/ut2rq+vQjh49qtOnTyssLMyh\n9tn77uznjpeXlyTZnz9n+/XXXytsR1hYmNs/h5SUFA0YMEDXXXed6tevr6lTpzp9/lyo58zMTDVr\n1szt/s7sR5vNpgYNGtiXnf06+fXXXxUaGupy3fPJyMhw2c+Farp63Trjzuvg3J9lYWGhy3r/+te/\n9NVXXyk8PFzR0dH64YcfzrOVwMUjoOGy1rlzZ+Xl5Wn+/Pnq1q2bJMnHx0cNGzbUvHnz1LBhQ4df\nWBdy5hd2aGiopk6dquPHj9v/FRQUOL0NQsOGDZWRkWF/bBiGw+Nnn31WNWrU0O7du5WXl6fFixc7\nfMrs3JCwdOlSJSQkaO3atcrLy9N///tfh2vaztWnTx998803+u2339SiRQs9/PDD9m2YN2+ewzYU\nFhaqc+fObu2LPXv2KD8/X/n5+fZ9647PP/9cDRo00A033FBhWUREhD766CNlZ2dr0qRJuvfee1VU\nVOQyKLlzIf/Z1xOlp6crJCRE
2014-06-25 22:06:16 +00:00
"text": [
2014-06-26 21:41:00 +00:00
"<matplotlib.figure.Figure at 0x1063ddac8>"
2014-06-25 22:06:16 +00:00
]
}
],
2014-06-26 21:41:00 +00:00
"prompt_number": 4
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Scatterplots"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Scatter plots are useful for visualizing features in more than just one dimension, for example to get a feeling for the correlation between particular features. \n",
"Unfortunately, we can't plot all 13 features here at once, since the visual cortex of us humans is limited to a maximum of three dimensions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below, we will create an example 2D-Scatter plot from the features \"Alcohol content\" and \"Malic acid content\". \n",
"Additionally, we will use the [`scipy.stats.pearsonr`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html) function to calculate a Pearson correlation coefficient between these two features.\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from scipy.stats import pearsonr\n",
"\n",
"plt.figure(figsize=(10,8))\n",
"\n",
"for label,marker,color in zip(\n",
" range(1,4),('x', 'o', '^'),('blue', 'red', 'green')):\n",
"\n",
" # Calculate Pearson correlation coefficient\n",
" R = pearsonr(X_wine[:,0][y_wine == label], X_wine[:,1][y_wine == label])\n",
" plt.scatter(x=X_wine[:,0][y_wine == label], # x-axis: feat. from col. 1\n",
" y=X_wine[:,1][y_wine == label], # y-axis: feat. from col. 2\n",
" marker=marker, # data point symbol for the scatter plot\n",
" color=color,\n",
" alpha=0.7, \n",
" label='class {:}, R={:.2f}'.format(label, R[0]) # label for the legend\n",
" )\n",
" \n",
"plt.title('Wine Dataset')\n",
"plt.xlabel('alcohol by volume in percent')\n",
"plt.ylabel('malic acid in g/l')\n",
"plt.legend(loc='upper right')\n",
"\n",
"plt.show()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "display_data",
2014-06-26 21:41:00 +00:00
"png": "iVBORw0KGgoAAAANSUhEUgAAAloAAAH4CAYAAACSZ0OSAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xd8VF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YhIvXTkiD08HT8OO3fC229DfPy55318YNIk2LQJHngAunSB\nkSNLnmPOHDg7kpWRAa++Cikp5a/BZrNx22230bJlS44fP058fDzDhg0rdd+IiAh27dpFWloaDzzw\nAEOHDqWgoACwh7AxY8aQkZHBkSNHuO+++wB78MjMzOTkyZOkpqYye/ZsvL29L1hTZcPH2eOys7NZ\nsmQJvXr1cjy3adMmAgMDy7xFRUWVes6YmBhatWqFj4+PY1uXLl3KDHH79u2jS5cujsedO3cuse/x\n48eZO3cu48ePr7YFbHUJHhERqZf69IHCQnjmGfvjd9+Ftm0rdo5bb4XXXrOHrB9/hN69ISio/MdH\nR0dz+vRpJk+ejNls7/u45pprSt13+PDhjvsvvPACb731FgcOHKBTp054eHhw8OBBkpOTCQ4OJiIi\nAgAPDw9SUlI4ePAgnTp1olu3bhetqTLDaYZhMGXKFGbOnElmZiYtWrRgy5Ytjuf79etXqUsgZWVl\n4e/vX2Kbn58f8X9MxBfY38/Pj6ysLMfj5557jrfeegsfHx9MJpOGDkVERJzJz+/cfV/fks9lZ9t7\nvPr1g8WLYdcuWLCg5D5hYfDK
2014-06-25 22:06:16 +00:00
"text": [
2014-06-26 21:41:00 +00:00
"<matplotlib.figure.Figure at 0x106804780>"
2014-06-25 22:06:16 +00:00
]
}
],
2014-06-26 21:41:00 +00:00
"prompt_number": 5
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we want to pack 3 different features into one scatter plot at once, we can also do the same thing in 3D:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from mpl_toolkits.mplot3d import Axes3D\n",
"\n",
"fig = plt.figure(figsize=(8,8))\n",
"ax = fig.add_subplot(111, projection='3d')\n",
" \n",
"for label,marker,color in zip(\n",
" range(1,4),('x', 'o', '^'),('blue','red','green')):\n",
" \n",
" ax.scatter(X_wine[:,0][y_wine == label], \n",
" X_wine[:,1][y_wine == label], \n",
" X_wine[:,2][y_wine == label], \n",
" marker=marker, \n",
" color=color, \n",
" s=40, \n",
" alpha=0.7,\n",
" label='class {}'.format(label))\n",
"\n",
"ax.set_xlabel('alcohol by volume in percent')\n",
"ax.set_ylabel('malic acid in g/l')\n",
"ax.set_zlabel('ash content in g/l')\n",
"\n",
"plt.title('Wine dataset')\n",
" \n",
"plt.show()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "display_data",
2014-06-26 21:41:00 +00:00
"png": "iVBORw0KGgoAAAANSUhEUgAAAcwAAAHMCAYAAABY25iGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsvXmUVOWd//++t/a9u4GmbZoGBAkIyiIKImvUqLjGNWZQ\nJzHKccwYRyff4zITz/klmWRmgsZ8Z8YlUb/GmBhHR8ERTVBBFkUkCCJEoJutm26g1+rabtVdnt8f\n5XO5VV1VXcutqltVz+scztGq6lvPvXXv834+n+ezcIQQAgaDwWAwGBnhyz0ABoPBYDAqASaYDAaD\nwWBkARNMBoPBYDCygAkmg8FgMBhZwASTwWAwGIwsYILJYDAYDEYWMMFkMBgMBiMLmGAyGAwGg5EF\nTDAZDAaDwcgCJpgMBoPBYGQBE0wGg8FgMLKACSaDwWAwGFnABJPBYDAYjCxggslgMBgMRhYwwWQw\nGAwGIwuYYDIYDAaDkQVMMBkMBoPByAImmAwGg8FgZAETTAaDwWAwsoAJJoPBYDAYWcAEk8FgMBiM\nLGCCyWAwGAxGFjDBZDAYDAYjC5hgMhgMBoORBUwwGQwGg8HIAiaYDAaDwWBkARNMBoPBYDCygAkm\ng5ElmzdvxrRp00ryXcuWLcNzzz1Xku9iMBjZwQSTUbP87Gc/w4oVKxJeO+uss1K+9uqrr2Lx4sX4\n8ssvSzI2juPAcVxWn504cSI++OCDIo+odN/DYBgVJpiMmmXp0qX46KOPQAgBAHR3d0OSJOzatQuK\noqivtbe3Y8mSJeUcakY4jlPPo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00:00
"text": [
2014-06-26 21:41:00 +00:00
"<matplotlib.figure.Figure at 0x107c42940>"
2014-06-25 22:06:16 +00:00
]
}
],
2014-06-26 21:41:00 +00:00
"prompt_number": 6
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Splitting into training and test dataset "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is a typical procedure for machine learning and pattern classification tasks to split one dataset into two: a training dataset and a test dataset. \n",
"The training dataset is henceforth used to train our algorithms or classifier, and the test dataset is a way to validate the outcome quite objectively before we apply it to \"new, real world data\".\n",
"\n",
"Here, we will split the dataset randomly so that 70% of the total dataset will become our training dataset, and 30% will become our test dataset, respectively."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from sklearn.cross_validation import train_test_split\n",
"from sklearn import preprocessing\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(X_wine, y_wine,\n",
" test_size=0.30, random_state=123)"
],
"language": "python",
"metadata": {},
"outputs": [],
2014-06-26 21:41:00 +00:00
"prompt_number": 7
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that since this a random assignment, the original relative frequencies for each class label are not maintained."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('Class label frequencies')\n",
" \n",
"print('\\nTraining Dataset:') \n",
"for l in range(1,4):\n",
" print('Class {:} samples: {:.2%}'.format(l, list(y_train).count(l)/y_train.shape[0]))\n",
" \n",
"print('\\nTest Dataset:') \n",
"for l in range(1,4):\n",
" print('Class {:} samples: {:.2%}'.format(l, list(y_test).count(l)/y_test.shape[0]))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Class label frequencies\n",
"\n",
"Training Dataset:\n",
"Class 1 samples: 36.29%\n",
"Class 2 samples: 42.74%\n",
"Class 3 samples: 20.97%\n",
"\n",
"Test Dataset:\n",
"Class 1 samples: 25.93%\n",
"Class 2 samples: 33.33%\n",
"Class 3 samples: 40.74%\n"
]
}
],
2014-06-26 21:41:00 +00:00
"prompt_number": 8
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Feature Scaling"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another popular procedure is to standardize the data prior to fitting the model and other analyses so that the features will have the properties of a standard normal distribution with \n",
"\n",
"$\\mu = 0$ and $\\sigma = 1$\n",
"\n",
"where $\\mu$ is the mean (average) and $\\sigma$ is the standard deviation from the mean, so that the standard scores of the samples are calculated as follows:\n",
"\n",
"\\begin{equation} z = \\frac{x - \\mu}{\\sigma}\\end{equation} "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"std_scale = preprocessing.StandardScaler().fit(X_train)\n",
"X_train = std_scale.transform(X_train)\n",
"X_test = std_scale.transform(X_test)"
],
"language": "python",
"metadata": {},
"outputs": [],
2014-06-26 21:41:00 +00:00
"prompt_number": 9
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"f, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(10,5))\n",
"\n",
"for a,x_dat, y_lab in zip(ax, (X_train, X_test), (y_train, y_test)):\n",
"\n",
" for label,marker,color in zip(\n",
" range(1,4),('x', 'o', '^'),('blue','red','green')):\n",
"\n",
" a.scatter(x=x_dat[:,0][y_lab == label], \n",
" y=x_dat[:,1][y_lab == label], \n",
" marker=marker, \n",
" color=color, \n",
" alpha=0.7, \n",
" label='class {}'.format(label)\n",
" )\n",
"\n",
" a.legend(loc='upper right')\n",
"\n",
"ax[0].set_title('Training Dataset')\n",
"ax[1].set_title('Test Dataset')\n",
"f.text(0.5, 0.04, 'malic acid (standardized)', ha='center', va='center')\n",
"f.text(0.08, 0.5, 'alcohol (standardized)', ha='center', va='center', rotation='vertical')\n",
"\n",
"plt.show()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "display_data",
2014-06-26 21:41:00 +00:00
"png": "iVBORw0KGgoAAAANSUhEUgAAAmQAAAFXCAYAAAAMF1IiAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xd4VMX6wPHvbnpIJ6SABBAUCaDkilERBBsiRUVFkKIg\nyrUBYuWnCIjtKqhXUQSlSxNBgdBUkHpBQoeAUgIkIZBGet02vz+OLEQSSMhuNtm8n+fZhz1lz3kn\n7hnfnTNnRqeUUgghhBBCCIfROzoAIYQQQoi6ThIyIYQQQggHk4RMCCGEEMLBJCETQgghhHAwSciE\nEEIIIRxMEjIhhBBCCAeThExUWvfu3fn+++9tvq8QQghRV0lCVkf4+Pjg6+uLr68ver0eb29v6/LC\nhQsrdazVq1czaNAgm+9bGRs3bkSv11vL0LhxY/r27cuuXbsqfIzx48fbJTZHnUcIobFlfQfQpUsX\nZsyYUe72U6dOlaqPwsLC6NWrF+vWravwOWbPnk2nTp0qHVtlVdd5ROVJQlZH5Ofnk5eXR15eHk2a\nNGHlypXW5SeeeMK6n8lkcmCUldOoUSNrGf744w9uuOEGOnXqxO+//+7o0IQQDlTR+q6idDpdhfbL\nyckhLy+PAwcOcN9999G7d2/mzJlT6fOJOkqJOqdp06Zq/fr1SimlNmzYoBo1aqQ+/vhjFRYWpp58\n8kmVlZWlevTooRo0aKACAwNVz5491enTp62f79y5s5o+fbpSSqlZs2apO+64Q7322msqMDBQNWvW\nTK1Zs+aq9j1x4oTq1KmT8vX1Vffee6964YUX1MCBA8ssw4YNG9Q111xzyfqXXnpJtW/f3ro8YsQI\n1bhxY+Xn56duvvlmtWXLFqWUUmvWrFHu7u7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Dg4\nGL1ez5o1a/j111+t+69cuZLjx4+jlMLPzw8XFxdcXFyIjo7G19eXTz75hKKiIsxmM3FxcdYhOEJD\nQ0udRwjhGM899xxvvfWW9cdeeno6K1asALShdA4ePIjZbMbX1xc3NzdcXFwA7RqOj4+/4vHPX+Op\nqal89dVXTJgwgY8++giAgoICdDodwcHBWCwWZs2aRVxcnPWzoaGhnD59GqPRaF2Xn59PYGAg7u7u\nxMbGsmDBAmudWF68YWFhdO3alVdeeYW8vDwsFgvx8fHWrhdlnUfUDJKQiUuSnpdffpmioiKCg4Pp\n0KEDDzzwQLmJ0T877Zd1vIruO3/+fLZv3079+vV555136Nu3b6lbqf/83JkzZ6zj/kRHR3Po0CE2\nbdrEvffeC0C3bt3o1q0b119/PU2bNsXLy4uIiAjrMfr06QNA/fr1ad++Pb6+vnz55Zc8/vjjBAUF\nsXDhQh566CHr/sePH+e+++7D19eXDh068OKLL9K5c2f0ej0rV65k3759XHvttTRo0IBhw4ZZk79/\nnkcI4RgjR47kwQcfpGvXrvj5+XH77bcTGxsLQEpKCn369MHf35/IyEi6dOliHT9w5MiRLFmyhKCg\nIF5++eVyjx8QEICPjw833ngja9euZcmSJQwePBiAyMhIXn31VW6//XbCwsKIi4ujY8eO1s/ec889\ntG7dmrCwMEJCQgCYMmUKY8eOxc/Pj/fee4++ffta979cvHPnzsVgMBAZGUlQUBB9+vQhJSWl3POI\nmkGnauDPdrPZTPv27bnmmmuIiYlxdDjCQfr27UtkZCTjxo1zdChCCCGEXdXIFrIvvviCyMhIuddd\nx+zatYv4+HgsFgtr1qxhxYoVPPzww44OSwghhLC7GpeQnT59mtWrV/PMM89In5s6JiUlhbvuugtf\nX19GjRrF1KlTuemmmxwdlhBC
"text": [
2014-06-26 21:41:00 +00:00
"<matplotlib.figure.Figure at 0x107d70e80>"
]
}
],
2014-06-26 21:41:00 +00:00
"prompt_number": 10
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id=\"PCA\"></a>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Linear Transformation: Principal Component Analysis (PCA)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The main purposes of a principal component analysis are the analysis of data to identify patterns and finding patterns to reduce the dimensions of the dataset with minimal loss of information.\n",
"\n",
"Here, our desired outcome of the principal component analysis is to project a feature space (our dataset consisting of n x d-dimensional samples) onto a smaller subspace that represents our data \"well\". A possible application would be a pattern classification task, where we want to reduce the computational costs and the error of parameter estimation by reducing the number of dimensions of our feature space by extracting a subspace that describes our data \"best\".\n",
"\n",
"If you are interested in the Principal Component Analysis in more detail, I have outlined the procedure in a separate article \n",
"[\"Implementing a Principal Component Analysis (PCA) in Python step by step](http://sebastianraschka.com/Articles/2014_pca_step_by_step.html)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here, we will use the [`sklearn.decomposition.PCA`](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html) to transform our training data onto 2 dimensional subspace:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from sklearn.decomposition import PCA\n",
2014-06-26 21:41:00 +00:00
"sklearn_pca = PCA(n_components=2) # number of components to keep\n",
"sklearn_transf = sklearn_pca.fit_transform(X_train)\n",
"\n",
"plt.figure(figsize=(10,8))\n",
"\n",
"for label,marker,color in zip(\n",
" range(1,4),('x', 'o', '^'),('blue', 'red', 'green')):\n",
"\n",
" plt.scatter(x=sklearn_transf[:,0][y_train == label],\n",
" y=sklearn_transf[:,1][y_train == label], \n",
" marker=marker, \n",
" color=color,\n",
" alpha=0.7, \n",
" label='class {}'.format(label)\n",
" )\n",
"\n",
"plt.xlabel('vector 1')\n",
"plt.ylabel('vector 2')\n",
"\n",
"plt.legend()\n",
"plt.title('Most significant singular vectors after linear transformation via PCA')\n",
"\n",
"plt.show()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "display_data",
2014-06-26 21:41:00 +00:00
"png": "iVBORw0KGgoAAAANSUhEUgAAAl4AAAH4CAYAAACbjOPoAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XlcVFX/B/DPDPsyDCAiioBbluRailsq+ZRLaZZprqRP\nPVr2ZGpWrqm5VT+1TNO0UtTc0hb3LbdyC1wRVzAVBFH2fZ2Z8/vjPAwg24Aww/J5v16+nDt3Od97\nucx8OefccxRCCAEiIiIiqnRKUwdAREREVFsw8SIiIiIyEiZeREREREbCxIuIiIjISJh4ERERERkJ\nEy8iIiIiI2HiRUahUqlw9+7dxz7Opk2b0Lt3b/3yqVOn8MQTT8DBwQE7d+7ESy+9hA0bNjx2OZXl\npZdewk8//VTp5cyZMwd+fn6VXk5NkXsfqVQq7Nq1q1LKUCqVuH37NgBg3LhxmD9/fqWUU51kZGSg\nf//+cHR0xJAhQ0wdTiGPft4YQ3h4OFQqFTjSUw0mqMbw8vISlpaWIjY2tsD7bdu2FQqFQoSFhT3W\n8RUKhfjnn38e6xgVrWfPnmLZsmVGLbNHjx7ixx9/NGqZZTVnzhwxcuRIU4dRoqp0HR+9jyrjXq+K\nvz9CyM+NI0eOmKTsDRs2CB8fH6HVak1Sfn537twRCoWiSsRSXv7+/kKpVAp7e3vh4OAg2rZtK/bs\n2aNfn5SUJCZMmCA8PT2Fvb29aNq0qZg4cWKh74wePXoIJycnkZWVZexTqBVY41WDKBQKNGnSBFu2\nbNG/FxwcjIyMDCgUigopQ1Sxv8LCw8Ph7e1t1DIr6lpWpsf5Oel0ugqMpHiPcx2FEBV6LxZ1H5X3\n+BqNpiJCqnDFXTOFQlHiuVbm+YSFhaF58+ZQKsv+VVRZcVW1z7iy6tq1K1JSUpCYmIi3334bb7zx\nBpKSkpCdnY1//etfuH79Og4ePIiUlBScOXMGLi4uCAwM1O9/9+5dBAYGwtXVtdJ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QIf39/YW5uLtatWyd0Op2YOXOmcHd31yfWhw4dEiqVSp9sHD9+XFy5ckUIIcTly5dF\nvXr1xI4dO4QQQty9e7dQU2P+zxtD7s9mzZqJ0NBQkZGRIXx9fcXUqVOLvBfmzp0rRowYoV/es2eP\n8Pb2LnCeuXHs3btX3L59WwghxJ9//ilsbW31f0A+Kn+8OTk5YunSpcLBwUEkJSWJIUOGiNGjRxe5\nX35NmzYVGzduFCEhIcLCwkI8fPiw1H2obJh41SC5idf8+fPFtGnTxP79+0WvXr2ERqPRJ14ajUZY\nWlqK69ev6/dbvXq18PX1FUII8eabb4qxY8cW+Ks5V2mJlyH7ajQaYWFhof+yFEKImTNnFqrxyp+0\nvfHGG+KLL74QQpQt8erVq5fB/b/atm0rdu7cqS+jWbNm+nVpaWlCoVDoP4B8fX1L7Ju0du3aQjUi\nRcVXUjlhYWHC3Ny8QM3RyJEjy5145ZeQkCAUCoU+GRw1apQYNWpUseeTW/bcuXOFEEKEhIQIlUql\nTyzt7OwK3BenT58WjRs3FkIIMXbsWPHhhx8WecxHr+OGDRtEx44dC2zTuXNnsW7dOv32s2fP1q9L\nTU0Vjo6O4tdffxXp6eklxv+or7/+Wrz22mv65dISr3fffVefKOV68sknxV9//aXfP38tVVEeTbzy\n13jZ2NgU+MJ3dXUVAQEBpV7fR128eFE4OTnplx+9ZkUpLvG6c+dOsfs8eg+NHj1ajBkzRr9+3759\n4qmnnhJCCHHkyBHRvHlz8ffffxeqCXz0Pu3Zs6f47rvv9Ms3b94UFhYWQqvVFhmXv7+/eOKJJ/TL\nly9fFgqFQl/DLIQQderUEUFB
2014-06-25 22:06:16 +00:00
"text": [
2014-06-26 21:41:00 +00:00
"<matplotlib.figure.Figure at 0x107d70908>"
2014-06-25 22:06:16 +00:00
]
}
],
2014-06-26 21:41:00 +00:00
"prompt_number": 11
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 4,
"metadata": {},
"source": [
"PCA for feature extraction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As mentioned in the short introduction above (and in more detail in my separate [PCA article](http://sebastianraschka.com/Articles/2014_pca_step_by_step.html)), PCA is commonly used in the field of pattern classification for feature selection (or dimensionality reduction). \n",
"By default, the transformed data will be ordered by the components with the maximum variance (in descending order). \n",
"\n",
"In the example above, I only kept the top 2 components (the 2 components with the maximum variance along the axes): The sample space of projected onto a 2-dimensional subspace, which was basically sufficient for plotting the data onto a 2D scatter plot.\n",
"\n",
"However, if we want to use PCA for feature selection, we probably don't want to reduce the dimensionality that drastically. By default, the `PCA` function (`PCA(n_components=None)`) keeps all the components in ranked order. So we could basically either set the number `n_components` to a smaller size then the input dataset, or we could extract the top **n** components later from the returned NumPy array.\n",
"\n",
"To get an idea about how well each components (relatively) \"explains\" the variance, we can use `explained_variance_ratio_` instant method, which also confirms that the components are ordered from most explanatory to least explanatory (the ratios sum up to 1.0)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"sklearn_pca = PCA(n_components=None)\n",
"sklearn_transf = sklearn_pca.fit_transform(X_train)\n",
"sklearn_pca.explained_variance_ratio_"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 27,
"text": [
"array([0.36, 0.21, 0.10, 0.08, 0.06, 0.05, 0.04, 0.03, 0.02, 0.02, 0.01,\n",
" 0.01, 0.01])"
]
}
],
"prompt_number": 27
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='MDA'></a>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
2014-06-26 04:24:05 +00:00
"Linear Transformation: Multiple Discriminant Analysis (MDA)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The main purposes of a Multiple Discriminant Analysis is to analyze the data to identify patterns to project it onto a subspace that yields a better separation of the classes. Also, the dimensionality of the dataset shall be reduced with minimal loss of information.\n",
"\n",
"**The approach is very similar to a Principal Component Analysis (PCA), but in addition to finding the component axes that maximize the variance of our data, we are additionally interested in the axes that maximize the separation of our classes (e.g., in a supervised pattern classification problem)**\n",
"\n",
"Here, our desired outcome of the multiple discriminant analysis is to project a feature space (our dataset consisting of n d-dimensional samples) onto a smaller subspace that represents our data \"well\" and has a good class separation. A possible application would be a pattern classification task, where we want to reduce the computational costs and the error of parameter estimation by reducing the number of dimensions of our feature space by extracting a subspace that describes our data \"best\"."
]
},
{
"cell_type": "heading",
"level": 4,
"metadata": {},
"source": [
"Principal Component Analysis (PCA) Vs. Multiple Discriminant Analysis (MDA)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Both Multiple Discriminant Analysis (MDA) and Principal Component Analysis (PCA) are linear transformation methods and closely related to each other. In PCA, we are interested to find the directions (components) that maximize the variance in our dataset, where in MDA, we are additionally interested to find the directions that maximize the separation (or discrimination) between different classes (for example, in pattern classification problems where our dataset consists of multiple classes. In contrast two PCA, which ignores the class labels).\n",
"\n",
"**In other words, via PCA, we are projecting the entire set of data (without class labels) onto a different subspace, and in MDA, we are trying to determine a suitable subspace to distinguish between patterns that belong to different classes. Or, roughly speaking in PCA we are trying to find the axes with maximum variances where the data is most spread (within a class, since PCA treats the whole data set as one class), and in MDA we are additionally maximizing the spread between classes.**\n",
"\n",
"In typical pattern recognition problems, a PCA is often followed by an MDA."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](../Images/mda_overview.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you are interested, you can find more information about the MDA in my IPython notebook \n",
"[Stepping through a Multiple Discriminant Analysis - using Python's NumPy and matplotlib](http://nbviewer.ipython.org/github/rasbt/pattern_classification/blob/master/dimensionality_reduction/projection/multiple_discriminant_analysis.ipynb?create=1)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Like we did in the PCA section above, we will use a `scikit-learn` funcion, [`sklearn.lda.LDA`](http://scikit-learn.org/stable/modules/generated/sklearn.lda.LDA.html) in order to transform our training data onto 2 dimensional subspace, where MDA is basically the more generalized form of an LDA (Linear Discriminant Analysis):"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from sklearn.lda import LDA\n",
"sklearn_lda = LDA(n_components=2)\n",
"sklearn_transf = sklearn_lda.fit_transform(X_train, y_train)\n",
"\n",
"plt.figure(figsize=(10,8))\n",
"\n",
"for label,marker,color in zip(\n",
" range(1,4),('x', 'o', '^'),('blue', 'red', 'green')):\n",
"\n",
"\n",
" plt.scatter(x=sklearn_transf[:,0][y_train == label],\n",
" y=sklearn_transf[:,1][y_train == label], \n",
" marker=marker, \n",
" color=color,\n",
" alpha=0.7, \n",
" label='class {}'.format(label)\n",
" )\n",
"\n",
"plt.xlabel('vector 1')\n",
"plt.ylabel('vector 2')\n",
"\n",
"plt.legend()\n",
"plt.title('Most significant singular vectors after linear transformation via LDA')\n",
"\n",
"plt.show()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "display_data",
2014-06-26 21:41:00 +00:00
"png": "iVBORw0KGgoAAAANSUhEUgAAAmgAAAH4CAYAAAD+YRGXAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XlcVOX+B/DPGYadYRhkFVnEJSXNTKTCVKyrqWmaVxRF\nMrMsK1PSm5rllt0Ws26baWnuez8r0zKz1NyuVOaeiplsyqbsOzPP74/nMojsCMwAn/frNS+YmTPn\nfM9hGL48y/dRhBACRERERGQ2VKYOgIiIiIjKYoJGREREZGaYoBERERGZGSZoRERERGaGCRoRERGR\nmWGCRkRERGRmmKCRSWk0Gly5cuW297NhwwY8/PDDxvuHDx9Ghw4d4OjoiG+++QaDBw/G2rVrb/s4\nDWXw4MFYt25dgx9n/vz5iIiIaPDjNBcl7yONRoMdO3Y0yDFUKhUuX74MAJg8eTIWL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szYdR4dHY0LFy7g0UcfhRACn3/+Od577z04OTnBwcEB\ns2fPxubNmwEAK1euxMSJE/HQQw8BAFq3bo077rjDuO+br+OuXbtwxx13IDw8HCqVCmFhYejUqZNx\n0L6iKHjiiSfQuXNnqFQqqNVqqFQqYze+u7t7pd3d99xzD4KCgqBSqeDr64tJkybhwIEDNb5+n332\nGZ555hn07NnT+LOytrbGf//7X2NsL774Iry8vMpdv8rcfO6WlpaYO3cuLCwsMGjQIDg4OODChQvV\nXl9nZ2c89thjsLGxgYODA155
"text": [
2014-06-26 21:41:00 +00:00
"<matplotlib.figure.Figure at 0x107d5c3c8>"
]
}
],
2014-06-26 21:41:00 +00:00
"prompt_number": 29
},
{
"cell_type": "heading",
"level": 4,
"metadata": {},
"source": [
"MDA for feature extraction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we want to use MDA for projecting our data onto a smaller subspace (i.e., for dimensionality reduction), we can directly set the number of components to keep via `LDA(n_components=...)`; this is analogous to the [PCA function](#PCA-for-feature-extraction), which we have seen above.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Simple Supervised Classification"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Linear Discriminant Analysis as simple linear classifier"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The LDA that we've just used in the section above can also be used as a simple linear classifier."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# fit model\n",
"lda_clf = LDA()\n",
"lda_clf.fit(X_train, y_train)\n",
"LDA(n_components=None, priors=None)\n",
"\n",
"# prediction\n",
"print('1st sample from test dataset classified as:', lda_clf.predict(X_test[0,:]))\n",
"print('actual class label:', y_test[0])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1st sample from test dataset classified as: [3]\n",
"actual class label: 3\n"
]
}
],
"prompt_number": 14
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another handy subpackage of sklearn is `metrics`. The [`metrics.accuracy_score`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html), for example, is quite useful to evaluate how many samples can be classified correctly:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from sklearn import metrics\n",
"pred_train = lda_clf.predict(X_train)\n",
"\n",
"print('Prediction accuracy for the training dataset')\n",
"print('{:.2%}'.format(metrics.accuracy_score(y_train, pred_train)))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Prediction accuracy for the training dataset\n",
"100.00%\n"
]
}
],
"prompt_number": 15
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To verify that over model was not overfitted to the training dataset, let us evaluate the classifier's accuracy on the test dataset:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"pred_test = lda_clf.predict(X_test)\n",
"\n",
"print('Prediction accuracy for the test dataset')\n",
"print('{:.2%}'.format(metrics.accuracy_score(y_test, pred_test)))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Prediction accuracy for the test dataset\n",
"98.15%\n"
]
}
],
"prompt_number": 16
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Confusion Matrix** \n",
"As we can see above, there was a very low misclassification rate when we'd apply the classifier on the test data set. A confusion matrix can tell us in more detail which particular classes could not classified correctly.\n",
"\n",
2014-06-26 04:24:05 +00:00
"<table cellspacing=\"0\" border=\"0\">\n",
"\t<colgroup width=\"60\"></colgroup>\n",
"\t<colgroup span=\"4\" width=\"82\"></colgroup>\n",
"\t<tr>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" colspan=2 rowspan=2 height=\"44\" align=\"center\" bgcolor=\"#FFFFFF\"><b><font face=\"Helvetica\" size=4><br></font></b></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" colspan=3 align=\"center\" bgcolor=\"#FFFFFF\"><b><font face=\"Helvetica\" size=4>predicted class</font></b></td>\n",
"\t\t</tr>\n",
"\t<tr>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#EEEEEE\"><font face=\"Helvetica\" size=4>class 1</font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#EEEEEE\"><font face=\"Helvetica\" size=4>class 2</font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#EEEEEE\"><font face=\"Helvetica\" size=4>class 3</font></td>\n",
"\t</tr>\n",
"\t<tr>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" rowspan=3 height=\"116\" align=\"center\" bgcolor=\"#F6F6F6\"><b><font face=\"Helvetica\" size=4>actual class</font></b></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#EEEEEE\"><font face=\"Helvetica\" size=4>class 1</font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#99FFCC\"><font face=\"Helvetica\" size=4>True positives</font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#F6F6F6\"><font face=\"Helvetica\" size=4><br></font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#F6F6F6\"><font face=\"Helvetica\" size=4><br></font></td>\n",
"\t</tr>\n",
"\t<tr>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#EEEEEE\"><font face=\"Helvetica\" size=4>class 2</font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#FFFFFF\"><font face=\"Helvetica\" size=4><br></font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#99FFCC\"><font face=\"Helvetica\" size=4>True positives</font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#FFFFFF\"><font face=\"Helvetica\" size=4><br></font></td>\n",
"\t</tr>\n",
"\t<tr>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#EEEEEE\"><font face=\"Helvetica\" size=4>class 3</font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#F6F6F6\"><font face=\"Helvetica\" size=4><br></font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#F6F6F6\"><font face=\"Helvetica\" size=4><br></font></td>\n",
"\t\t<td style=\"border-top: 1px solid #c1c1c1; border-bottom: 1px solid #c1c1c1; border-left: 1px solid #c1c1c1; border-right: 1px solid #c1c1c1\" align=\"left\" bgcolor=\"#99FFCC\"><font face=\"Helvetica\" size=4>True positives</font></td>\n",
"\t</tr>\n",
"</table>"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('Confusion Matrix of the LDA-classifier')\n",
"print(metrics.confusion_matrix(y_test, lda_clf.predict(X_test)))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Confusion Matrix of the LDA-classifier\n",
"[[14 0 0]\n",
" [ 1 17 0]\n",
" [ 0 0 22]]\n"
]
}
],
"prompt_number": 17
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As we can see, one sample from class 2 was incorrectly labeled as class 1, from the perspective of class 1, this would be 1 \"False Negative\" or a \"False Postive\" from the perspective of class 2, respectively"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='SGD'></a>"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Classification Stochastic Gradient Descent (SGD)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us now compare the classification accuracy of the LDA classifier with a simple classification (we also use the probably not ideal default settings here) via stochastic gradient descent, an algorithm that minimizes a linear objective function. \n",
"More information about the `sklearn.linear_model.SGDClassifier` can be found [here](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from sklearn.linear_model import SGDClassifier\n",
"\n",
"sdg_clf = SGDClassifier()\n",
"sdg_clf.fit(X_train, y_train)\n",
"\n",
"pred_train = sdg_clf.predict(X_train)\n",
"pred_test = sdg_clf.predict(X_test)\n",
"\n",
"print('\\nPrediction accuracy for the training dataset')\n",
"print('{:.2%}\\n'.format(metrics.accuracy_score(y_train, pred_train)))\n",
"\n",
"print('Prediction accuracy for the test dataset')\n",
"print('{:.2%}\\n'.format(metrics.accuracy_score(y_test, pred_test)))\n",
"\n",
"print('Confusion Matrix of the SGD-classifier')\n",
"print(metrics.confusion_matrix(y_test, sdg_clf.predict(X_test)))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n",
"Prediction accuracy for the training dataset\n",
"99.19%\n",
"\n",
"Prediction accuracy for the test dataset\n",
"100.00%\n",
"\n",
"Confusion Matrix of the SGD-classifier\n",
"[[14 0 0]\n",
" [ 0 18 0]\n",
" [ 0 0 22]]\n"
]
}
],
"prompt_number": 18
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Quite impressively, we achieved a 100% prediction accuracy on the test dataset without any additional efforts of tweaking any parameters and settings."
]
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Saving the processed datasets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Pickle"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The in-built [`pickle`](https://docs.python.org/3.4/library/pickle.html) module is a convenient tool in Python's standard library to save Python objects in byte format. This allows us, for example, to save our NumPy arrays and load them in a later or different Python session to continue working with our data, e.g., to train a classifier."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# export objects via pickle\n",
"\n",
"import pickle\n",
"\n",
"pickle_out = open('standardized_data.pkl', 'wb')\n",
"pickle.dump([X_train, X_test, y_train, y_test], pickle_out)\n",
"pickle_out.close()"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 19
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# import objects via pickle\n",
"\n",
"my_object_file = open('standardized_data.pkl', 'rb')\n",
"X_train, X_test, y_train, y_test = pickle.load(my_object_file)\n",
"my_object_file.close()"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 20
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Comma-Separated-Values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top]](#Sections)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And it is also always a good idea to save your data in common text formats, such as the CSV format that we started with. But first, let us add back the class labels to the front column of the test and training data sets."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"training_data = np.hstack((y_train.reshape(y_train.shape[0], 1), X_train))\n",
"test_data = np.hstack((y_test.reshape(y_test.shape[0], 1), X_test))"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 21
2014-06-25 22:06:16 +00:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we can save our test and training datasets as 2 separate CSV files using the [`numpy.savetxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html) function."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"np.savetxt('./training_set.csv', training_data, delimiter=',')\n",
"np.savetxt('./test_set.csv', test_data, delimiter=',')"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 22
2014-06-25 22:06:16 +00:00
}
],
"metadata": {}
}
]
}