{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Imaging Lab 2 Prelab: iPython Review\n", "\n", "### EECS 16A: Designing Information Devices and Systems I, Fall 2016" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Overview\n", "\n", "There are a handful of essential iPython and NumPy commands you will want to know for this week's lab and for the labs to come. This \"prelab\" aims to teach you proper usage of these commands and can serve as a reference doc in the future. Please note that **this prelab is NOT required**, but highly recommended, especially if you are new to Python or programming in general. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "from numpy import linalg" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Control Flow in Python\n", "\n", "Programming languages usually contain statements that can be used to direct or \"control the flow\" of execution. This includes (but not limited to) conditional statements such as \"if\", \"else\", and \"elif\", and loop-control statements such as \"while\", \"for\", \"break\", and \"continue\". " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Conditional Statements: (if, else, elif)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "if condition is False!\n" ] } ], "source": [ "# Example 1: Simple if/else\n", "\n", "x = 16\n", "\n", "if x > 20: # Asking the question, \"Is x greater than 20?\"\n", " print('if condition is True!')\n", "else:\n", " print('if condition is False!')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "first if condition is False and second if condition is True!\n" ] } ], "source": [ "# Example 2: Introducing elif\n", "\n", "x = 16\n", "\n", "if x > 20: # Asking the question, \"Is x greater than 20?\"\n", " print('first if condition is True!')\n", "elif x > 10 and x < 20: # Asking the question, \"Is x greater than 10 AND less than 20?\"\n", " print('first if condition is False and second if condition is True!')\n", "else:\n", " print('Neither if condition was True!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Loop-Control Statements: (while, for)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "i: 0\n", "i: 1\n", "i: 2\n", "i: 3\n", "i: 4\n" ] } ], "source": [ "# Example 3: while\n", "\n", "i = 0\n", "while i < 5: # Check if i < 5 every iteration. Stop looping if the condition is false, i.e. if i >= 5.\n", " print('i:',i)\n", " i += 1 # increment i by 1" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "i: 0\n", "i: 1\n", "i: 2\n", "i: 3\n", "i: 4\n" ] } ], "source": [ "# Example 4: for (pun not intended)\n", "\n", "# Notes: Unlike while loops, which can theoretically run \"forever\" given the right condition,\n", "# for loops serves a different prupose -- iterating a fixed number of times. For loops in Python\n", "# expect an iterable object -- something similar to a list -- to control the number of iterations.\n", "# The example below is \"equivalent\" to the while loop in the previous example.\n", "\n", "for i in range(0,5): # read about range() here: http://pythoncentral.io/pythons-range-function-explained/ . \n", " print('i:',i)\n", "\n", "# Notice no i += 1 statement!" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "word: 16a\n" ] } ], "source": [ "# Example 5: Iterating through lists\n", "\n", "char_list = [1, 6, 'a']\n", "word = ''\n", "\n", "for element in char_list:\n", " word += str(element)\n", "\n", "print('word:',word)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## NumPy\n", "\n", "From the NumPy website, \"NumPy is the fundamental package for scientific computing with Python. It contains among other things: a powerful N-dimensional array object.\" For the purposes of this course, we primarily use NumPy for its fast and fancy matrix functions. In general, Python list operations are slow; NumPy functions exploit the NumPy array object to \"vectorize\" the code, which usually improves the runtime of matrix calculations. **As a general rule of thumb, if a task involves vectors or matrices, you should resort to NumPy.** In addition to speeding up basic operations, NumPy contains an enormous library of matrix functions, so if you ever need to manipulate a vector or matrix, NumPy most likely already has a function implemented to suit your needs.\n", "\n", "Quintessential NumPy Documentation: http://docs.scipy.org/doc/numpy/reference/index.html" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating a NumPy array object" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Python list: [1, 2, 3, 4]\n", "NumPy array: [1 2 3 4]\n" ] } ], "source": [ "# Example 6: Going from Python list to NumPy array\n", "\n", "py_lst = [1,2,3,4]\n", "np_arr = np.array(py_lst)\n", "print('Python list:',py_lst)\n", "print('NumPy array:',np_arr)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0 1 2 3]\n", " [1 2 3 4]\n", " [2 3 4 5]\n", " [3 4 5 6]]\n" ] } ], "source": [ "# Example 7: Populating an empty NumPy array\n", "\n", "np_arr = np.empty([4,4], dtype=np.int) # An empty 4x4 numpy array\n", "\n", "for i in range(0,4):\n", " for j in range(0,4):\n", " np_arr[i,j] = i+j\n", "\n", "print(np_arr)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "np_zeros:\n", " [[ 0. 0. 0. 0. 0.]\n", " [ 0. 0. 0. 0. 0.]\n", " [ 0. 0. 0. 0. 0.]\n", " [ 0. 0. 0. 0. 0.]\n", " [ 0. 0. 0. 0. 0.]]\n", "\n", "np_id:\n", " [[ 1. 0. 0. 0. 0.]\n", " [ 0. 1. 0. 0. 0.]\n", " [ 0. 0. 1. 0. 0.]\n", " [ 0. 0. 0. 1. 0.]\n", " [ 0. 0. 0. 0. 1.]]\n" ] } ], "source": [ "# Example 8: Creating a NumPy array of zeros and the Identity matrix\n", "\n", "np_zeros = np.zeros([5,5]) # 5x5 matrix of all zeros.\n", "np_id = np.eye(5) # 5x5 Identity matrix.\n", "\n", "print('np_zeros:\\n',np_zeros)\n", "print('\\nnp_id:\\n',np_id)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "np_arr1: [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]\n", "np_arr2: [0 1 2 3 4 5 6 7 8 9]\n" ] } ], "source": [ "# Example 9: Creating a NumPy array that spans a certain set/list of numbers\n", "\n", "np_arr1 = np.linspace(0, 9, 10) # args for linspace(): (start, stop, num=50, endpoint=True, retstep=False, dtype=None)\n", "print('np_arr1:',np_arr1)\n", "\n", "np_arr2 = np.arange(0, 10, 1) # args for arange(): ([start,] stop, [step,] dtype=None)\n", "print('np_arr2:',np_arr2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### NumPy array slicing\n", "\n", "Array slicing is a technique in Python (and other languages) that programmers use to extract specific index-based information from an array. Array slicing answers queries such as, \"What are the first/last n elements in this array?\", \"What are the elements in the first r rows and first c columns of this matrix?\", \"What is every nth element in this array?\"" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "First ten elements of simple_arr: [0 1 2 3 4 5 6 7 8 9]\n", "\n", "Last ten elements of simple_arr: [90 91 92 93 94 95 96 97 98 99]\n", "\n", "Elements 16-26 of simple_arr: [16 17 18 19 20 21 22 23 24 25]\n" ] } ], "source": [ "# Example 10: Basic vector/list slicing\n", "\n", "simple_arr = np.arange(0,100,1)\n", "\n", "print('\\nFirst ten elements of simple_arr:',simple_arr[:10])\n", "print('\\nLast ten elements of simple_arr:',simple_arr[-10:]) # you should be aware that in Python, \n", "# requesting a negative index (-n) from list a is the same as requesting is equivlanet to requesting a[len(a)-n].\n", "print('\\nElements 16-26 of simple_arr:',simple_arr[16:26]) # Notice slicing includes the first index and excudes that last index." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Every-other element of simple_arr, starting from 0: [ 0 2 4 6 8 10 12 14 16 18]\n", "\n", "Every-third element of simple_arr, starting from 0: [ 0 3 6 9 12 15 18]\n", "\n", "Every-other element of simple_arr, starting from 10-16: [10 12 14]\n" ] } ], "source": [ "# Example 11: Some fancy vector/list slicing\n", "\n", "simple_arr = np.arange(0,20,1)\n", "\n", "print('\\nEvery-other element of simple_arr, starting from 0:',simple_arr[::2])\n", "print('\\nEvery-third element of simple_arr, starting from 0:',simple_arr[::3])\n", "print('\\nEvery-other element of simple_arr, starting from 10-16:',simple_arr[10:16:2])" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "i:\n", " [[ 0 1 2 3 4]\n", " [ 5 6 7 8 9]\n", " [10 11 12 13 14]\n", " [15 16 17 18 19]\n", " [20 21 22 23 24]]\n", "\n", "First row of i: [0 1 2 3 4]\n", "\n", "First column of i: [ 0 5 10 15 20]\n", "\n", "Rows 1-3 of i:\n", " [[ 5 6 7 8 9]\n", " [10 11 12 13 14]\n", " [15 16 17 18 19]]\n", "\n", "Columns 1-3 of i:\n", " [[ 1 2 3]\n", " [ 6 7 8]\n", " [11 12 13]\n", " [16 17 18]\n", " [21 22 23]]\n", "\n", "Top left 3x3 of i:\n", " [[ 0 1 2]\n", " [ 5 6 7]\n", " [10 11 12]]\n", "\n", "Every-other column of i:\n", " [[ 0 2 4]\n", " [ 5 7 9]\n", " [10 12 14]\n", " [15 17 19]\n", " [20 22 24]]\n" ] } ], "source": [ "# Example 12: Slicing NumPy arrays\n", "\n", "i = np.array(range(25), dtype=np.int).reshape([5,5])\n", "print('i:\\n',i)\n", "\n", "print('\\nFirst row of i:',i[0])\n", "print('\\nFirst column of i:',i[:,0])\n", "print('\\nRows 1-3 of i:\\n',i[1:4])\n", "print('\\nColumns 1-3 of i:\\n',i[:,1:4])\n", "print('\\nTop left 3x3 of i:\\n',i[:3,:3])\n", "print('\\nEvery-other column of i:\\n',i[:,::2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### NumPy array reshaping\n", "\n", "Reshaping is useful when you want to do something such as turn a vector into a matrix or vice-versa. We want to be able to do this because it is often easier to construct the desired array as a vector then reshape the vector into a matrix." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of test_arr: (15, 189)\n", "Number of elements in test_arr: 2835\n" ] } ], "source": [ "# Example 13: Determining the shape of a NumPy\n", "\n", "test_arr = np.zeros([15,189])\n", "\n", "print('Shape of test_arr:',test_arr.shape) # Notice .shape is a NumPy array property NOT a function, i.e. no paranthesis.\n", "print('Number of elements in test_arr:',test_arr.size)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "test_arr: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]\n", "Shape of test_arr: (16,)\n", "\n", "Reshaped test_arr:\n", " [[ 0 1 2 3]\n", " [ 4 5 6 7]\n", " [ 8 9 10 11]\n", " [12 13 14 15]]\n", "Shape of test_arr_4x4: (4, 4)\n", "\n", "test_arr back as a vector: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]\n", "Shape of test_arr_vec: (16,)\n" ] } ], "source": [ "# Example 14: Using reshape()\n", "\n", "test_arr = np.array(range(16), dtype=np.int)\n", "print('\\ntest_arr:',test_arr)\n", "print('Shape of test_arr:',test_arr.shape)\n", "\n", "test_arr_4x4 = test_arr.reshape([4,4]) # Notice reshape() is called on the array object, i.e. array.reshape(dimensions) NOT np.reshape(arr, dimensions)!\n", "print('\\nReshaped test_arr:\\n',test_arr_4x4)\n", "print('Shape of test_arr_4x4:',test_arr_4x4.shape)\n", "\n", "test_arr_vec = test_arr_4x4.reshape(test_arr_4x4.size) # Use array.flatten() instead. This is just to show array.reshape works in both directions.\n", "print('\\ntest_arr back as a vector:',test_arr_vec)\n", "print('Shape of test_arr_vec:',test_arr_vec.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Useful NumPy functions: (transpose(), linalg.inv(), dot(), concatenate(), vstack(), hstack())" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "norm:\n", " [[ 0 1 2 3]\n", " [ 4 5 6 7]\n", " [ 8 9 10 11]\n", " [12 13 14 15]]\n", "\n", "norm_transpose:\n", " [[ 0 4 8 12]\n", " [ 1 5 9 13]\n", " [ 2 6 10 14]\n", " [ 3 7 11 15]]\n", "\n", "norm easy transpose:\n", " [[ 0 4 8 12]\n", " [ 1 5 9 13]\n", " [ 2 6 10 14]\n", " [ 3 7 11 15]]\n" ] } ], "source": [ "# Example 15: numpy.transpose()\n", "\n", "norm = np.array(range(16), dtype=np.int).reshape([4,4])\n", "print('\\nnorm:\\n',norm)\n", "\n", "norm_transpose = np.transpose(norm)\n", "print('\\nnorm_transpose:\\n',norm_transpose)\n", "\n", "print('\\nnorm easy transpose:\\n',norm.T) # numpy.transpose(arr) == arr.T" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "i:\n", " [[ 1. 0. 0. 0.]\n", " [ 0. 1. 0. 0.]\n", " [ 0. 0. 1. 0.]\n", " [ 0. 0. 0. 1.]]\n", "\n", "i_inv:\n", " [[ 1. 0. 0. 0.]\n", " [ 0. 1. 0. 0.]\n", " [ 0. 0. 1. 0.]\n", " [ 0. 0. 0. 1.]]\n", "\n", "As expected, i == inv(i).\n" ] } ], "source": [ "# Example 16: numpy.linalg.inv (finds the inverse of a matrix)\n", "\n", "i = np.eye(4)\n", "print('\\ni:\\n',i)\n", "\n", "i_inv = np.linalg.inv(i) # Notice .inv() is a function in the linalg library of NumPy.\n", "print('\\ni_inv:\\n',i_inv)\n", "print('\\nAs expected, i == inv(i).')" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "a:\n", " [[2 3]\n", " [4 5]]\n", "\n", "b:\n", " [[1 2]\n", " [0 2]]\n", "\n", "Matrix multiplication.\n", "a*b:\n", " [[ 2 10]\n", " [ 4 18]]\n", "\n", "Order matters in numpy.dot()!\n", "b*a:\n", " [[10 13]\n", " [ 8 10]]\n", "Notice a*b != b*a.\n", "\n", "e: [2 2]\n", "\n", "numpy.dot() can be used to multiply a matrix and vector too.\n", "a*e: [10 18]\n" ] } ], "source": [ "# Example 17: numpy.dot() (how to do matrix multiplication in NumPy!)\n", "\n", "a = np.array([[2,3],[4,5]])\n", "print('\\na:\\n',a)\n", "b = np.array([[1,2],[0,2]])\n", "print('\\nb:\\n',b)\n", "\n", "print('\\nMatrix multiplication.')\n", "c = np.dot(a,b)\n", "print('a*b:\\n',c)\n", "\n", "print('\\nOrder matters in numpy.dot()!')\n", "d = np.dot(b,a)\n", "print('b*a:\\n',d)\n", "print('Notice a*b != b*a.')\n", "\n", "e = np.array([2,2])\n", "print('\\ne:',e)\n", "\n", "print('\\nnumpy.dot() can be used to multiply a matrix and vector too.')\n", "f = np.dot(a,e)\n", "print('a*e:',f)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "a:\n", " [[2 3]\n", " [4 5]]\n", "\n", "b:\n", " [[1 2]\n", " [0 2]]\n", "\n", "Append b to the \"bottom\" of a:\n", " [[2 3]\n", " [4 5]\n", " [1 2]\n", " [0 2]]\n", "\n", "Append b to the \"right\" of a:\n", " [[2 3 1 2]\n", " [4 5 0 2]]\n" ] } ], "source": [ "# Example 18: numpy.concatenate() (how to append/attach multiple arrays.)\n", "\n", "a = np.array([[2,3],[4,5]])\n", "print('\\na:\\n',a)\n", "b = np.array([[1,2],[0,2]])\n", "print('\\nb:\\n',b)\n", "\n", "c = np.concatenate([a,b], axis=0) # axis controls how to concatenate the arrays. axis=0 attach vertically, axis=1 attach horizontally.\n", "print('\\nAppend b to the \"bottom\" of a:\\n',c)\n", "\n", "d = np.concatenate([a,b], axis=1)\n", "print('\\nAppend b to the \"right\" of a:\\n',d)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "a:\n", " [[2 3]\n", " [4 5]]\n", "\n", "b:\n", " [[1 2]\n", " [0 2]]\n", "\n", "vstack a and b:\n", " [[2 3]\n", " [4 5]\n", " [1 2]\n", " [0 2]]\n", "Notice this is equivalent to concatenate with axis=0.\n", "\n", "hstack a and b:\n", " [[2 3 1 2]\n", " [4 5 0 2]]\n", "Notice this is equivalent to concatenate with axis=1.\n" ] } ], "source": [ "# Example 19: numpy.vstack() and numpy.hstack()\n", "\n", "a = np.array([[2,3],[4,5]])\n", "print('\\na:\\n',a)\n", "b = np.array([[1,2],[0,2]])\n", "print('\\nb:\\n',b)\n", "\n", "c = np.vstack([a,b])\n", "print('\\nvstack a and b:\\n',c)\n", "print('Notice this is equivalent to concatenate with axis=0.')\n", "\n", "d = np.hstack([a,b])\n", "print('\\nhstack a and b:\\n',d)\n", "print('Notice this is equivalent to concatenate with axis=1.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Extras" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a: 16.5\n", "floor of a: 16.0\n", "ceiling of a: 17.0\n" ] } ], "source": [ "# Example 20: np.floor(), np.ceil()\n", "\n", "a = 16.5\n", "print('a:',a)\n", "print('floor of a:',np.floor(a))\n", "print('ceiling of a:',np.ceil(a))" ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python [Root]", "language": "python", "name": "Python [Root]" }, "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.5.2" } }, "nbformat": 4, "nbformat_minor": 0 }