mirror of
https://github.com/donnemartin/data-science-ipython-notebooks.git
synced 2024-03-22 13:30:56 +08:00
784 lines
60 KiB
Python
784 lines
60 KiB
Python
|
{
|
|||
|
"cells": [
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"<!--BOOK_INFORMATION-->\n",
|
|||
|
"<img align=\"left\" style=\"padding-right:10px;\" src=\"figures/PDSH-cover-small.png\">\n",
|
|||
|
"*This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).*\n",
|
|||
|
"\n",
|
|||
|
"*The text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT). If you find this content useful, please consider supporting the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!*\n",
|
|||
|
"\n",
|
|||
|
"*No changes were made to the contents of this notebook from the original.*"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"<!--NAVIGATION-->\n",
|
|||
|
"< [Fancy Indexing](02.07-Fancy-Indexing.ipynb) | [Contents](Index.ipynb) | [Structured Data: NumPy's Structured Arrays](02.09-Structured-Data-NumPy.ipynb) >"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"# Sorting Arrays"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Up to this point we have been concerned mainly with tools to access and operate on array data with NumPy.\n",
|
|||
|
"This section covers algorithms related to sorting values in NumPy arrays.\n",
|
|||
|
"These algorithms are a favorite topic in introductory computer science courses: if you've ever taken one, you probably have had dreams (or, depending on your temperament, nightmares) about *insertion sorts*, *selection sorts*, *merge sorts*, *quick sorts*, *bubble sorts*, and many, many more.\n",
|
|||
|
"All are means of accomplishing a similar task: sorting the values in a list or array.\n",
|
|||
|
"\n",
|
|||
|
"For example, a simple *selection sort* repeatedly finds the minimum value from a list, and makes swaps until the list is sorted. We can code this in just a few lines of Python:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 1,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [],
|
|||
|
"source": [
|
|||
|
"import numpy as np\n",
|
|||
|
"\n",
|
|||
|
"def selection_sort(x):\n",
|
|||
|
" for i in range(len(x)):\n",
|
|||
|
" swap = i + np.argmin(x[i:])\n",
|
|||
|
" (x[i], x[swap]) = (x[swap], x[i])\n",
|
|||
|
" return x"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 2,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([1, 2, 3, 4, 5])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 2,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x = np.array([2, 1, 4, 3, 5])\n",
|
|||
|
"selection_sort(x)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"As any first-year computer science major will tell you, the selection sort is useful for its simplicity, but is much too slow to be useful for larger arrays.\n",
|
|||
|
"For a list of $N$ values, it requires $N$ loops, each of which does on order $\\sim N$ comparisons to find the swap value.\n",
|
|||
|
"In terms of the \"big-O\" notation often used to characterize these algorithms (see [Big-O Notation](#Aside:-Big-O-Notation)), selection sort averages $\\mathcal{O}[N^2]$: if you double the number of items in the list, the execution time will go up by about a factor of four.\n",
|
|||
|
"\n",
|
|||
|
"Even selection sort, though, is much better than my all-time favorite sorting algorithms, the *bogosort*:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 3,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [],
|
|||
|
"source": [
|
|||
|
"def bogosort(x):\n",
|
|||
|
" while np.any(x[:-1] > x[1:]):\n",
|
|||
|
" np.random.shuffle(x)\n",
|
|||
|
" return x"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 4,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([1, 2, 3, 4, 5])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 4,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x = np.array([2, 1, 4, 3, 5])\n",
|
|||
|
"bogosort(x)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"This silly sorting method relies on pure chance: it repeatedly applies a random shuffling of the array until the result happens to be sorted.\n",
|
|||
|
"With an average scaling of $\\mathcal{O}[N \\times N!]$, (that's *N* times *N* factorial) this should–quite obviously–never be used for any real computation.\n",
|
|||
|
"\n",
|
|||
|
"Fortunately, Python contains built-in sorting algorithms that are *much* more efficient than either of the simplistic algorithms just shown. We'll start by looking at the Python built-ins, and then take a look at the routines included in NumPy and optimized for NumPy arrays."
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"## Fast Sorting in NumPy: ``np.sort`` and ``np.argsort``\n",
|
|||
|
"\n",
|
|||
|
"Although Python has built-in ``sort`` and ``sorted`` functions to work with lists, we won't discuss them here because NumPy's ``np.sort`` function turns out to be much more efficient and useful for our purposes.\n",
|
|||
|
"By default ``np.sort`` uses an $\\mathcal{O}[N\\log N]$, *quicksort* algorithm, though *mergesort* and *heapsort* are also available. For most applications, the default quicksort is more than sufficient.\n",
|
|||
|
"\n",
|
|||
|
"To return a sorted version of the array without modifying the input, you can use ``np.sort``:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 5,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([1, 2, 3, 4, 5])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 5,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x = np.array([2, 1, 4, 3, 5])\n",
|
|||
|
"np.sort(x)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"If you prefer to sort the array in-place, you can instead use the ``sort`` method of arrays:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 6,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"[1 2 3 4 5]\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x.sort()\n",
|
|||
|
"print(x)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"A related function is ``argsort``, which instead returns the *indices* of the sorted elements:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 7,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"[1 0 3 2 4]\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x = np.array([2, 1, 4, 3, 5])\n",
|
|||
|
"i = np.argsort(x)\n",
|
|||
|
"print(i)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"The first element of this result gives the index of the smallest element, the second value gives the index of the second smallest, and so on.\n",
|
|||
|
"These indices can then be used (via fancy indexing) to construct the sorted array if desired:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 8,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([1, 2, 3, 4, 5])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 8,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x[i]"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"### Sorting along rows or columns"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"A useful feature of NumPy's sorting algorithms is the ability to sort along specific rows or columns of a multidimensional array using the ``axis`` argument. For example:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 9,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"[[6 3 7 4 6 9]\n",
|
|||
|
" [2 6 7 4 3 7]\n",
|
|||
|
" [7 2 5 4 1 7]\n",
|
|||
|
" [5 1 4 0 9 5]]\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"rand = np.random.RandomState(42)\n",
|
|||
|
"X = rand.randint(0, 10, (4, 6))\n",
|
|||
|
"print(X)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 10,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([[2, 1, 4, 0, 1, 5],\n",
|
|||
|
" [5, 2, 5, 4, 3, 7],\n",
|
|||
|
" [6, 3, 7, 4, 6, 7],\n",
|
|||
|
" [7, 6, 7, 4, 9, 9]])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 10,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"# sort each column of X\n",
|
|||
|
"np.sort(X, axis=0)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 11,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([[3, 4, 6, 6, 7, 9],\n",
|
|||
|
" [2, 3, 4, 6, 7, 7],\n",
|
|||
|
" [1, 2, 4, 5, 7, 7],\n",
|
|||
|
" [0, 1, 4, 5, 5, 9]])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 11,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"# sort each row of X\n",
|
|||
|
"np.sort(X, axis=1)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Keep in mind that this treats each row or column as an independent array, and any relationships between the row or column values will be lost!"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"## Partial Sorts: Partitioning\n",
|
|||
|
"\n",
|
|||
|
"Sometimes we're not interested in sorting the entire array, but simply want to find the *k* smallest values in the array. NumPy provides this in the ``np.partition`` function. ``np.partition`` takes an array and a number *K*; the result is a new array with the smallest *K* values to the left of the partition, and the remaining values to the right, in arbitrary order:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 12,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([2, 1, 3, 4, 6, 5, 7])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 12,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x = np.array([7, 2, 3, 1, 6, 5, 4])\n",
|
|||
|
"np.partition(x, 3)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Note that the first three values in the resulting array are the three smallest in the array, and the remaining array positions contain the remaining values.\n",
|
|||
|
"Within the two partitions, the elements have arbitrary order.\n",
|
|||
|
"\n",
|
|||
|
"Similarly to sorting, we can partition along an arbitrary axis of a multidimensional array:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 13,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([[3, 4, 6, 7, 6, 9],\n",
|
|||
|
" [2, 3, 4, 7, 6, 7],\n",
|
|||
|
" [1, 2, 4, 5, 7, 7],\n",
|
|||
|
" [0, 1, 4, 5, 9, 5]])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 13,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"np.partition(X, 2, axis=1)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"The result is an array where the first two slots in each row contain the smallest values from that row, with the remaining values filling the remaining slots.\n",
|
|||
|
"\n",
|
|||
|
"Finally, just as there is a ``np.argsort`` that computes indices of the sort, there is a ``np.argpartition`` that computes indices of the partition.\n",
|
|||
|
"We'll see this in action in the following section."
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"## Example: k-Nearest Neighbors\n",
|
|||
|
"\n",
|
|||
|
"Let's quickly see how we might use this ``argsort`` function along multiple axes to find the nearest neighbors of each point in a set.\n",
|
|||
|
"We'll start by creating a random set of 10 points on a two-dimensional plane.\n",
|
|||
|
"Using the standard convention, we'll arrange these in a $10\\times 2$ array:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 14,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [],
|
|||
|
"source": [
|
|||
|
"X = rand.rand(10, 2)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"To get an idea of how these points look, let's quickly scatter plot them:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 15,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAe4AAAFVCAYAAAApGgzgAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAHWtJREFUeJzt3W9wVOXd//HPQliWZTdQanzQTggoRFpwUiFqBaOd6Wb0\n1swosIkBJhlHRx2nsZ0BO5aZKnGmTJAOfWBj+qA2piASJOS+q1uqndwgM02dmyRj0OAvsWOdyLRP\nMlaz+bObP+T8HgAL4U+ynOyfXHveryftnuvK5vt1dT/nnCvnHJdlWZYAAIAR5qS7AAAAED+CGwAA\ngxDcAAAYhOAGAMAgBDcAAAYhuAEAMMiMgvv06dOqqKi4ansoFFJZWZm2bt2q6urqmfwKAABwGdvB\n/frrr+uXv/ylxsbGJm0fGRnRq6++qjfffFNvvfWWBgYGdOLEiRkXCgAAZhDceXl5eu21167a7na7\n1djYKLfbLUkaHx/X/Pnz7VcIAABibAd3cXGx5s6de9V2l8ulJUuWSJIOHDigSCSi9evX268QAADE\nZCXjTS3L0t69e9Xb26va2tq4f8blciWjHAAAMsaMg/tatzp/8cUX5fF4VFdXF/f7uFwu9fUNzLQc\nY+Xk+Onfof07uXeJ/unfuf3n5Pht/dyMg/viUXIoFFIkEtHq1avV3NysdevWqaKiQi6XS5WVlQoE\nAjP9VQAAON6Mgvu73/2uGhsbJUklJSWx7Z9++unMqgIAANfEDVgAADAIwQ0AgEE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DAvRRWB4AYA\nXNddd61RINAq6dx1Zpx
|
|||
|
"text/plain": [
|
|||
|
"<matplotlib.figure.Figure at 0x10be92fd0>"
|
|||
|
]
|
|||
|
},
|
|||
|
"metadata": {},
|
|||
|
"output_type": "display_data"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"%matplotlib inline\n",
|
|||
|
"import matplotlib.pyplot as plt\n",
|
|||
|
"import seaborn; seaborn.set() # Plot styling\n",
|
|||
|
"plt.scatter(X[:, 0], X[:, 1], s=100);"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Now we'll compute the distance between each pair of points.\n",
|
|||
|
"Recall that the squared-distance between two points is the sum of the squared differences in each dimension;\n",
|
|||
|
"using the efficient broadcasting ([Computation on Arrays: Broadcasting](02.05-Computation-on-arrays-broadcasting.ipynb)) and aggregation ([Aggregations: Min, Max, and Everything In Between](02.04-Computation-on-arrays-aggregates.ipynb)) routines provided by NumPy we can compute the matrix of square distances in a single line of code:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 16,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [],
|
|||
|
"source": [
|
|||
|
"dist_sq = np.sum((X[:, np.newaxis, :] - X[np.newaxis, :, :]) ** 2, axis=-1)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"This operation has a lot packed into it, and it might be a bit confusing if you're unfamiliar with NumPy's broadcasting rules. When you come across code like this, it can be useful to break it down into its component steps:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 17,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"(10, 10, 2)"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 17,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"# for each pair of points, compute differences in their coordinates\n",
|
|||
|
"differences = X[:, np.newaxis, :] - X[np.newaxis, :, :]\n",
|
|||
|
"differences.shape"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 18,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"(10, 10, 2)"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 18,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"# square the coordinate differences\n",
|
|||
|
"sq_differences = differences ** 2\n",
|
|||
|
"sq_differences.shape"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 19,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"(10, 10)"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 19,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"# sum the coordinate differences to get the squared distance\n",
|
|||
|
"dist_sq = sq_differences.sum(-1)\n",
|
|||
|
"dist_sq.shape"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Just to double-check what we are doing, we should see that the diagonal of this matrix (i.e., the set of distances between each point and itself) is all zero:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 20,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 20,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"dist_sq.diagonal()"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"It checks out!\n",
|
|||
|
"With the pairwise square-distances converted, we can now use ``np.argsort`` to sort along each row. The leftmost columns will then give the indices of the nearest neighbors:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 21,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"[[0 3 9 7 1 4 2 5 6 8]\n",
|
|||
|
" [1 4 7 9 3 6 8 5 0 2]\n",
|
|||
|
" [2 1 4 6 3 0 8 9 7 5]\n",
|
|||
|
" [3 9 7 0 1 4 5 8 6 2]\n",
|
|||
|
" [4 1 8 5 6 7 9 3 0 2]\n",
|
|||
|
" [5 8 6 4 1 7 9 3 2 0]\n",
|
|||
|
" [6 8 5 4 1 7 9 3 2 0]\n",
|
|||
|
" [7 9 3 1 4 0 5 8 6 2]\n",
|
|||
|
" [8 5 6 4 1 7 9 3 2 0]\n",
|
|||
|
" [9 7 3 0 1 4 5 8 6 2]]\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"nearest = np.argsort(dist_sq, axis=1)\n",
|
|||
|
"print(nearest)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Notice that the first column gives the numbers 0 through 9 in order: this is due to the fact that each point's closest neighbor is itself, as we would expect.\n",
|
|||
|
"\n",
|
|||
|
"By using a full sort here, we've actually done more work than we need to in this case. If we're simply interested in the nearest $k$ neighbors, all we need is to partition each row so that the smallest $k + 1$ squared distances come first, with larger distances filling the remaining positions of the array. We can do this with the ``np.argpartition`` function:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 22,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [],
|
|||
|
"source": [
|
|||
|
"K = 2\n",
|
|||
|
"nearest_partition = np.argpartition(dist_sq, K + 1, axis=1)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"In order to visualize this network of neighbors, let's quickly plot the points along with lines representing the connections from each point to its two nearest neighbors:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 23,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAe4AAAFVCAYAAAApGgzgAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xd8TYcbx/HPTW6GSGIGHTah9qxNQlRUrEhIokmVGkV/\ndqlaHRpttVRDzdgSRKzUDInaIwSJvbVFrUQiO/f+/gghRmXfe3Oe9+vlJffcc859HufK9+yj0mq1\nWoQQQghhEIx0XYAQQgghMk+CWwghhDAgEtxCCCGEAZHgFkIII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aTSpeXm7MmvUL771Xg+3bQxkw4DMu\nXryAo2NbZs+eJSeuCSFEDkhwi1zTpUt3Nm/ezltvvc13301h8OD+AHz33Q/4+6+jaNFifP31BFxd\nu3Lr1j86rVUIIQyVBLfIVXXq1GP79lAaNmzMunVr6NatI3fu3KZt2/bs2XOIDh06snfvHtq0acrm\nzRt1Xa4QQhgcCW6R60qXLs369X/g6urG8eNhfPCBHeHhxylZsiTLlvnz448zSExMpF8/T0aMGEps\nbKyuSxZCCIMhwS3yhLm5OT4+85g06Vtu375Fly6OrF8fgEqlok+ffuzc+Se1atVh5cpltGvXkqNH\nj+q6ZCGEMAjZCm6tVsvkyZNxc3PDy8uLmzdvZnh/06ZNODs74+rqip+fX64UKgyPSqVi6NBhrFix\nGrXahIED++Lt/Q0ajQZb22ps3bqLIUOGcfXqFZo3b87MmdNJTU3VddlCCKHXshXcwcHBJCUl4e/v\nz6hRo/D29s7w/o8//sj
|
|||
|
"text/plain": [
|
|||
|
"<matplotlib.figure.Figure at 0x115ae2898>"
|
|||
|
]
|
|||
|
},
|
|||
|
"metadata": {},
|
|||
|
"output_type": "display_data"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"plt.scatter(X[:, 0], X[:, 1], s=100)\n",
|
|||
|
"\n",
|
|||
|
"# draw lines from each point to its two nearest neighbors\n",
|
|||
|
"K = 2\n",
|
|||
|
"\n",
|
|||
|
"for i in range(X.shape[0]):\n",
|
|||
|
" for j in nearest_partition[i, :K+1]:\n",
|
|||
|
" # plot a line from X[i] to X[j]\n",
|
|||
|
" # use some zip magic to make it happen:\n",
|
|||
|
" plt.plot(*zip(X[j], X[i]), color='black')"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Each point in the plot has lines drawn to its two nearest neighbors.\n",
|
|||
|
"At first glance, it might seem strange that some of the points have more than two lines coming out of them: this is due to the fact that if point A is one of the two nearest neighbors of point B, this does not necessarily imply that point B is one of the two nearest neighbors of point A.\n",
|
|||
|
"\n",
|
|||
|
"Although the broadcasting and row-wise sorting of this approach might seem less straightforward than writing a loop, it turns out to be a very efficient way of operating on this data in Python.\n",
|
|||
|
"You might be tempted to do the same type of operation by manually looping through the data and sorting each set of neighbors individually, but this would almost certainly lead to a slower algorithm than the vectorized version we used. The beauty of this approach is that it's written in a way that's agnostic to the size of the input data: we could just as easily compute the neighbors among 100 or 1,000,000 points in any number of dimensions, and the code would look the same.\n",
|
|||
|
"\n",
|
|||
|
"Finally, I'll note that when doing very large nearest neighbor searches, there are tree-based and/or approximate algorithms that can scale as $\\mathcal{O}[N\\log N]$ or better rather than the $\\mathcal{O}[N^2]$ of the brute-force algorithm. One example of this is the KD-Tree, [implemented in Scikit-learn](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KDTree.html)."
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"## Aside: Big-O Notation\n",
|
|||
|
"\n",
|
|||
|
"Big-O notation is a means of describing how the number of operations required for an algorithm scales as the input grows in size.\n",
|
|||
|
"To use it correctly is to dive deeply into the realm of computer science theory, and to carefully distinguish it from the related small-o notation, big-$\\theta$ notation, big-$\\Omega$ notation, and probably many mutant hybrids thereof.\n",
|
|||
|
"While these distinctions add precision to statements about algorithmic scaling, outside computer science theory exams and the remarks of pedantic blog commenters, you'll rarely see such distinctions made in practice.\n",
|
|||
|
"Far more common in the data science world is a less rigid use of big-O notation: as a general (if imprecise) description of the scaling of an algorithm.\n",
|
|||
|
"With apologies to theorists and pedants, this is the interpretation we'll use throughout this book.\n",
|
|||
|
"\n",
|
|||
|
"Big-O notation, in this loose sense, tells you how much time your algorithm will take as you increase the amount of data.\n",
|
|||
|
"If you have an $\\mathcal{O}[N]$ (read \"order $N$\") algorithm that takes 1 second to operate on a list of length *N*=1,000, then you should expect it to take roughly 5 seconds for a list of length *N*=5,000.\n",
|
|||
|
"If you have an $\\mathcal{O}[N^2]$ (read \"order *N* squared\") algorithm that takes 1 second for *N*=1000, then you should expect it to take about 25 seconds for *N*=5000.\n",
|
|||
|
"\n",
|
|||
|
"For our purposes, the *N* will usually indicate some aspect of the size of the dataset (the number of points, the number of dimensions, etc.). When trying to analyze billions or trillions of samples, the difference between $\\mathcal{O}[N]$ and $\\mathcal{O}[N^2]$ can be far from trivial!\n",
|
|||
|
"\n",
|
|||
|
"Notice that the big-O notation by itself tells you nothing about the actual wall-clock time of a computation, but only about its scaling as you change *N*.\n",
|
|||
|
"Generally, for example, an $\\mathcal{O}[N]$ algorithm is considered to have better scaling than an $\\mathcal{O}[N^2]$ algorithm, and for good reason. But for small datasets in particular, the algorithm with better scaling might not be faster.\n",
|
|||
|
"For example, in a given problem an $\\mathcal{O}[N^2]$ algorithm might take 0.01 seconds, while a \"better\" $\\mathcal{O}[N]$ algorithm might take 1 second.\n",
|
|||
|
"Scale up *N* by a factor of 1,000, though, and the $\\mathcal{O}[N]$ algorithm will win out.\n",
|
|||
|
"\n",
|
|||
|
"Even this loose version of Big-O notation can be very useful when comparing the performance of algorithms, and we'll use this notation throughout the book when talking about how algorithms scale."
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"<!--NAVIGATION-->\n",
|
|||
|
"< [Fancy Indexing](02.07-Fancy-Indexing.ipynb) | [Contents](Index.ipynb) | [Structured Data: NumPy's Structured Arrays](02.09-Structured-Data-NumPy.ipynb) >"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"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.4.3"
|
|||
|
}
|
|||
|
},
|
|||
|
"nbformat": 4,
|
|||
|
"nbformat_minor": 0
|
|||
|
}
|