{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Numpy (and Matplotlib)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import math\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This discussion is going to involve a bit more math than the previous. If I refer to a topic you don't know, please feel free to ask me to explain it. It will be hard to understand how Numpy can be useful if you aren't familiar with the concepts I'm pulling from math."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Linear Algebra"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Numpy is often used for linear algebra. That is, matrix and vector operations like matrix multiplication and the dot product. Situations where we need to run these computations occur commonly in a variety of settings, including data science. Numpy gives you a way to perform these operations quickly and without having to program them yourself.\n",
"\n",
"For example, consider matrix multiplication. Remember that a matrix is a two-dimensional array of numbers with its size denoted by (# of rows) x (# of columns). If we have two matrices, one with size L x N and the other with size N x M we can multiply them. An example is below."
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"[1 2] [2] [1x2 + 2x1] [4]\n",
"[2 1] X [1] = [2x2 + 1x1] = [5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We could write something like this in Python ourselves, storing a matrix as a list of lists (each inner list will represent one row)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def mat_multiply(M1, M2):\n",
" result = []\n",
" \n",
" for i in range(len(M1)):\n",
" row = []\n",
" for j in range(len(M2[0])):\n",
" component = 0\n",
" for k in range(len(M2)):\n",
" component += M1[i][k]*M2[k][j]\n",
" row.append(component)\n",
" result.append(row)\n",
" \n",
" return result\n",
"\n",
"M1 = [[1, 2], [2, 1]]\n",
"M2 = [[2], [1]]\n",
"print(mat_multiply(M1,M2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Alternatively, we can use Numpy. The command `np.matmul` is used to multiply two matrices. Here, the matrices must be stored as Numpy arrays, which we can easily create from the above."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"numpy_M1 = np.array(M1)\n",
"numpy_M2 = np.array(M2)\n",
"print(np.matmul(numpy_M1, numpy_M2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One immediate benefit is that the output above is formatted more like a matrix, and not just a list of lists. Another benefit, as mentioned before, is speed. Here's what happens when we multiply two random matrices:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import random\n",
"import time\n",
"\n",
"M1 = [[random.random() for _ in range(200)] for _ in range(200)]\n",
"M2 = [[random.random() for _ in range(200)] for _ in range(200)]\n",
"\n",
"numpy_M1 = np.array(M1)\n",
"numpy_M2 = np.array(M2)\n",
"\n",
"t0 = time.time()\n",
"mat_multiply(M1, M2)\n",
"t1 = time.time()\n",
"print(f'Time for our multiplication: {t1-t0}')\n",
"\n",
"t0 = time.time()\n",
"np.matmul(numpy_M1, numpy_M2)\n",
"t1 = time.time()\n",
"print(f'Time for Numpy multiplication: {t1-t0}')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Numpy implementation is much faster, which is what we would expect.\n",
"\n",
"Now, let's discuss other things we may wish to do. For starters, instead of using `np.matmul`, we can use the `@` operator. This does the same thing."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"M1 = [[1, 2], [2, 1]]\n",
"M2 = [[2], [1]]\n",
"numpy_M1 = np.array(M1)\n",
"numpy_M2 = np.array(M2)\n",
"print(numpy_M1 @ numpy_M2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We also have the dot product, which takes two vectors and returns the sum of their coordinates multiplied together."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"v1 = np.array([1, 2, 3])\n",
"v2 = np.array([2, 1, 5])\n",
"\n",
"print(np.dot(v1, v2)) # get the value of 1*2 + 2*1 + 3*5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lastly, another useful command is `np.sum`. By default, this takes an array and returns the sum of every entry of it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(np.sum(numpy_M1))\n",
"print(np.sum(v1 * v2)) # same as np.dot(v1, v2)), but a little slower"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`np.sum` can also take in a parameter called `axis`. This allows us to sum over just one dimension of the array. For example, we could get the sum of every row in a matrix. The axis we sum over is indexed as normal: 0 is the first axis, 1 is the second, and so on.\n",
"\n",
"For example, summing over axis 0 in a 2D matrix means we are summing over rows, so we will get the sum of each column. (The \"over\" part means that every part of the sum comes from a different row but the rest of the coordinates are the same.) This is a little tricky to get correct when you're starting out, and sometimes I still get confused about this. It's never a bad idea to check your results to make sure you're summing the way you want to."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"M = np.array([[1, 1, 1], [2, 2, 2]])\n",
"print(M)\n",
"print('')\n",
"print(np.sum(M,axis=0))\n",
"print(np.sum(M,axis=1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Random\n",
"\n",
"Numpy has its own way of generating randomness. This is mostly used if we want to have your randomness be immediately used to generate or sample a numpy array. For example, in the example above when we generated a random Numpy matrix, we could have instead done:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"numpy_M1 = np.random.rand(100, 100)\n",
"numpy_M2 = np.random.rand(100, 100)\n",
"np.matmul(numpy_M1, numpy_M2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The function `np.random.rand(...)` returns an array of random values between 0 and 1 with the specified shape. Here we did 100 x 100, so it is a 2d array with 100 rows and 100 columns."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similarly, we have `np.random.randn(...)`. This does the same thing, except the random values come from the normal distribution."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"numpy_M1 = np.random.randn(100, 100)\n",
"numpy_M2 = np.random.randn(100, 100)\n",
"np.matmul(numpy_M1, numpy_M2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are other methods in the `np.random` submodule, these are just two examples. Other methods that may be useful is a method to generate Numpy array of random integers and a method to randomly shuffle a Numpy array. Like other Numpy methods, its not too important to have these memorized. What is important to know is that they exist, and can be looked up when needed."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise\n",
"\n",
"Let's do one multi-part exercise to practice working with Numpy.\n",
"\n",
"Our goal in this exercise is to estimate the value of pi. We will do this by randomly sampling points in the unit square (the part of the X-Y plane where both coordinates are between -1 and 1). This square has area 4. In this square is the unit circle, which covers all points of distance no more than 1 from 0. This circle has area pi. Therefore, if we randomly sample points in this square, we expect pi/4 of them to be in the circle.\n",
"\n",
"Throughout this problem, `N` will refer to the number of points we sample. This allows us to easily rerun the experiment again with more points if we wish."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"N = 1000"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"***Part 1:*** Generate `N` random points in the unit square. This will be represented as an N x 2 array where every entry is a value between -1 and 1. (We will consider each row to be a single point.)\n",
"\n",
"(see my website [here](https://www.math.ucla.edu/~egeo/classes/f20_pic16a/notebook_week6a.html) or discussion video for solution)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"***Part 2:*** Get the squared distance between each point and 0. Remember that for a point (x, y), the squared distance between it and 0 is x^2 + y^2.\n",
"\n",
"(see my website [here](https://www.math.ucla.edu/~egeo/classes/f20_pic16a/notebook_week6a.html) or discussion video for solution)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"***Part 3:*** Get the number of points which lie inside the circle and compute our estimate for pi.\n",
"\n",
"(see my website [here](https://www.math.ucla.edu/~egeo/classes/f20_pic16a/notebook_week6a.html) or discussion video for solution)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"***Part 4 (together):*** Plot the points on the X-Y plane, as well as the unit circle.\n",
"\n",
"(see my website [here](https://www.math.ucla.edu/~egeo/classes/f20_pic16a/notebook_week6a.html) or discussion video for solution)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"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.8.3"
}
},
"nbformat": 4,
"nbformat_minor": 4
}