︠12636745-7254-4761-a9d7-3d7177c92627s︠
%auto
import numpy as np # Import the numpy library
︡684a19da-bcba-4e34-b0e8-33147d4a4620︡︡{"done":true}
︠e428819d-09a1-4de8-a573-c0954dee5858i︠
%md
# Broadcasting with NumPy
︡4fa00ffc-dd85-4053-8381-c29ad0a87ddc︡︡{"done":true,"md":"# Broadcasting with NumPy"}
︠85a07b2a-d1c2-4189-a94f-274818a07cdfi︠
%md
Often large amounts of data needs to be manipulated by addition, subtraction, division, and multiplication. In order to make programing simpler, and computation more efficient, problems are often vectorized. In other words, problems are formulated in terms of vectors, matrices, tensors, and scalers (0th order tensors), generally referred to as arrays. Operations commonly need to be applied element wise to matrix and vector quantities. With a lower level language, like C, these operations would be performed using loops, such as a for loop. However higher level languages, like NumPy in Python, allows programmers to generalize operations to apply to arrays, without need for explicit loops. In addition to allowing the programmer to avoid having to write loops, NumPy utilizes libraries that use specialized CPU routines which are more efficient than simple loops. Broadcasting refers how computations with arrays of different sizes, or shapes, are performed. Before defining specifically how broadcasting in NumPy works consider a few examples.
︡eae2b6fe-3f9c-4779-9473-a77599693f6d︡︡{"done":true,"md":"Often large amounts of data needs to be manipulated by addition, subtraction, division, and multiplication. In order to make programing simpler, and computation more efficient, problems are often vectorized. In other words, problems are formulated in terms of vectors, matrices, tensors, and scalers (0th order tensors), generally referred to as arrays. Operations commonly need to be applied element wise to matrix and vector quantities. With a lower level language, like C, these operations would be performed using loops, such as a for loop. However higher level languages, like NumPy in Python, allows programmers to generalize operations to apply to arrays, without need for explicit loops. In addition to allowing the programmer to avoid having to write loops, NumPy utilizes libraries that use specialized CPU routines which are more efficient than simple loops. Broadcasting refers how computations with arrays of different sizes, or shapes, are performed. Before defining specifically how broadcasting in NumPy works consider a few examples."}
︠d32f1909-e441-4cc4-a24f-44e247e7a293i︠
%md
Here are two arrays with shape or dimension of (3,).
︡0bf181d1-96f0-4862-9b56-c4c885966fd1︡︡{"done":true,"md":"Here are two arrays with shape or dimension of (3,)."}
︠2414236a-a79e-4427-9fa1-e8e46ff6b153s︠
a = np.array([1.0, 2.0, 3.0]) # shape (3,)
b = np.array([2.0, 2.0, 2.0]) # shape (3,)
a,b
︡1a82b1c8-1a72-4cec-a38e-2d097060043a︡︡{"stdout":"(array([ 1., 2., 3.]), array([ 2., 2., 2.]))\n"}︡{"done":true}
︠ea3eb1c3-b397-4c0d-8341-36f4d76031b2s︠
︡3d488495-e446-4a51-a40e-23f13b661393︡︡{"done":true}
︠e08c6106-d8c4-46af-b068-85c37cbd061ai︠
%md
a*b in effect multiplies corresponding elements in each array together and results in another array of shape (3,)
︡862036f5-3429-4b9c-9f22-18571c5f0561︡︡{"done":true,"md":"a*b in effect multiplies corresponding elements in each array together and results in another array of shape (3,)"}
︠fa4c2f79-fe61-4e03-9e25-9cff5c329845s︠
a*b
︡c2fe4469-ba45-4d7d-a774-e9f51b4efa27︡︡{"stdout":"array([ 2., 4., 6.])\n"}︡{"done":true}
︠bd18a55d-d173-4e03-86cc-6cb15c7b79f9i︠
%md
This result is fairly straight forward. Notice that the array b is the same number for all array positions. Here we can use NumPy's broadcasting feature to simplify the operation. Again array a has shape (3,), but b is a scaler or a 0th-order tensor.
︡dd425900-d31e-47b3-a38f-f25d8e44e1a6︡︡{"done":true,"md":"This result is fairly straight forward. Notice that the array b is the same number for all array positions. Here we can use NumPy's broadcasting feature to simplify the operation. Again array a has shape (3,), but b is a scaler or a 0th-order tensor."}
︠0c5e957d-9a9e-4043-88c7-6630c111f54c︠
a = np.array([1.0, 2.0, 3.0]) # shape (3,)
b = 2.0 # scalar
a,b
︡ea0ac08b-778f-41fe-add9-0021f2e79354︡︡{"stdout":"(array([ 1., 2., 3.]), 2.00000000000000)\n"}︡{"done":true}
︠e1b72928-f8a6-4ab4-b840-0e9270434dd6︠
a*b
︡4830f4a5-21b3-438c-b9d5-e59ac9bb12eb︡︡{"stdout":"array([ 2., 4., 6.])\n"}︡{"done":true}
︠2ca998e5-cbbc-45d8-a04a-1794ab0934a8i︠
%md
This is the same result as the first case, but b did not need to be defined as an array with the same shape as array a. b can be thought of as being "stretched" across the length of array a. For this example it seems trivial, but when moving to larger and higher order arrays this is a powerful tool.
︡6663bae1-3aea-4dd2-b2af-98ccec99e842︡︡{"done":true,"md":"This is the same result as the first case, but b did not need to be defined as an array with the same shape as array a. b can be thought of as being \"stretched\" across the length of array a. For this example it seems trivial, but when moving to larger and higher order arrays this is a powerful tool."}
︠4e147c33-b3de-49e3-befb-e097f687ba4ci︠
%md
The next example shows how to multiply each column of an array of shape (2,3) by a different value using broadcasting. Each element in the first column of a is multiplied by the first element of b, each element in the second column of a is multiplied by the second element of b, and each element in the third column of a is multiplied by the third element of b. This results in having the first column of a multiplied by 1, the second column multiplied by 2, and the third column multiplied by 3.
︡5b787587-5146-477a-b007-7e7f9cc21f38︡︡{"done":true,"md":"The next example shows how to multiply each column of an array of shape (2,3) by a different value using broadcasting. Each element in the first column of a is multiplied by the first element of b, each element in the second column of a is multiplied by the second element of b, and each element in the third column of a is multiplied by the third element of b. This results in having the first column of a multiplied by 1, the second column multiplied by 2, and the third column multiplied by 3."}
︠5ae0a66a-fe82-4042-86a8-b7e8ded24cd7︠
a = np.array([[1.0, 2.0, 3.0],[2.0, 4.0, 6.0]]) # is an array of shape (2,3)
b = np.array([1.0,2.0,3.0]) # b is an array of shape (3,)
a*b
︡89a59474-7785-45e9-93f0-3015b512b44b︡︡{"stdout":"array([[ 1., 4., 9.],\n [ 2., 8., 18.]])\n"}︡{"done":true}
︠3056284e-af36-4052-afb0-0b99654dd083i︠
%md
Similarly, broadcasting can be used to add 1 to the first column of a, 2 to the second column of a, and 3 to the third column of a.
︡c6352081-0722-4f15-beb9-7c4d141e8793︡︡{"done":true,"md":"Similarly, broadcasting can be used to add 1 to the first column of a, 2 to the second column of a, and 3 to the third column of a."}
︠4b32153c-cf44-4c74-9d6e-7641b8e8bf92s︠
a+b
︡5ce46ea3-e49b-402c-aec7-4c7dffb65d9a︡︡{"stdout":"array([[ 2., 4., 6.],\n [ 3., 6., 9.]])\n"}︡{"done":true}
︠f7895b08-4e7a-4594-ab21-7ccd19ddf5a5i︠
%md
In the following case broadcasting does not work.
︡c72c996e-a094-4d2b-a92b-528959c8d767︡︡{"done":true,"md":"In the following case broadcasting does not work."}
︠33f476a8-c2cc-411d-808c-4da1d52b0e09s︠
a = np.array([1,2,3]) # shape (3,)
b = np.array([1,2,3,4]) # shape (4,)
a*b
︡29d7c363-5fc1-4b7a-b7ce-50bff4d7d68e︡︡{"stderr":"Error in lines 3-3\nTraceback (most recent call last):\n File \"/projects/sage/sage-6.10/local/lib/python2.7/site-packages/smc_sagews/sage_server.py\", line 904, in execute\n exec compile(block+'\\n', '', 'single') in namespace, locals\n File \"\", line 1, in \nValueError: operands could not be broadcast together with shapes (3,) (4,) \n"}︡{"done":true}
︠75a4c419-2aa6-41c8-9d07-40db94c3e7bbi︠
%md
To understand when broadcasting does and doesn't work a formal understanding is required.
︡ecf113b6-7825-4dd4-b86b-688db7599db4︡︡{"done":true,"md":"To understand when broadcasting does and doesn't work a formal understanding is required."}
︠03a02293-6d90-4fe7-bde7-211f0d9cd14ci︠
%md
### Definition
The following is based on the official [NumPy documentation](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
Broadcasting describes how NumPy treats arrays of different sizes (matrices, vectors, and tensors) during an operation.
When operating on arrays NumPy compares their shapes starting with the last dimension. Where the shape of an n-dimensional array is of the form (d1 , d2 , d3, ... , dn). In order for dimensions of two different arrays to be compatible for broadcasting one of the following two conditions must be met.
1. They must be equal
2. One of them must be 1
The resulting array has a size that is the maximum along each of the input arrays.
Note: The shape of any given array, a, can be found by a.shape.
**Examples**
In the previous example array a had shape (3,) and b was a scalar, or in otherwords of shape (1,).
---
A (2d array): 1x3
B (1d array): 1
a*b (2d array): 1x3
---
Numpy compares the last dimensions 3 and 1, the second condition for broadcasting is met. b is "stretched" to match a and the operation proceeds.
Here are a couple more generic examples.
---
A (3d array): 256 x 256 x 3
B (1d array): 3
Result (3d array): 256 x 256 x 3
---
In this case both A and B arrays have axes with length one that are expanded when broadcasting.
---
A (4d array): 8 x 1 x 6 x 1
B (3d array): 7 x 1 x 5
Result (4d array): 8 x 7 x 6 x 5
---
**Now a couple examples that do not work**
---
A (1d array): 3
B (1d array): 4
---
A * B will result in an error because their shapes are not compatible according to the two conditions stated earlier.
---
A (1d array): 2 x 1
B (1d array): 8 x 4 x 3
---
Here we see that the last dimension is compatible and the second to last is not.
︡4bbbc722-cf53-4388-a0f8-c8675f6f60b4︡︡{"done":true,"md":"\n### Definition\n\nThe following is based on the official [NumPy documentation](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\n\nBroadcasting describes how NumPy treats arrays of different sizes (matrices, vectors, and tensors) during an operation.\n\n\nWhen operating on arrays NumPy compares their shapes starting with the last dimension. Where the shape of an n-dimensional array is of the form (d1 , d2 , d3, ... , dn). In order for dimensions of two different arrays to be compatible for broadcasting one of the following two conditions must be met.\n\n\n1. They must be equal\n2. One of them must be 1\n\n\nThe resulting array has a size that is the maximum along each of the input arrays.\n\n\nNote: The shape of any given array, a, can be found by a.shape.\n\n\n**Examples**\n\n\nIn the previous example array a had shape (3,) and b was a scalar, or in otherwords of shape (1,).\n\n---\n\n A (2d array): 1x3\n\n B (1d array): 1\n\n a*b (2d array): 1x3\n\n---\n\nNumpy compares the last dimensions 3 and 1, the second condition for broadcasting is met. b is \"stretched\" to match a and the operation proceeds.\n\n\nHere are a couple more generic examples.\n\n---\n\n A (3d array): 256 x 256 x 3\n\n B (1d array): 3\n\n Result (3d array): 256 x 256 x 3\n\n---\n\nIn this case both A and B arrays have axes with length one that are expanded when broadcasting.\n\n---\n\n A (4d array): 8 x 1 x 6 x 1\n\n B (3d array): 7 x 1 x 5\n\n Result (4d array): 8 x 7 x 6 x 5\n\n---\n\n**Now a couple examples that do not work**\n\n---\n\n A (1d array): 3\n\n B (1d array): 4\n\n---\n\nA * B will result in an error because their shapes are not compatible according to the two conditions stated earlier.\n\n---\n\n A (1d array): 2 x 1\n\n B (1d array): 8 x 4 x 3\n \n---\n\nHere we see that the last dimension is compatible and the second to last is not."}
︠744d1eb0-0a4a-4bf8-a971-a18a9c74a543i︠
%md
### Outer Operations and np.newaxis
︡d9173532-aa52-4eca-869c-68d2685e9853︡︡{"done":true,"md":"### Outer Operations and np.newaxis"}
︠5b8d1d0d-fc89-40da-b9a4-052a1fb5dda2i︠
%md
When using broadcasting the command `np.newaxis` can be helpful. The newaxis object creates an axis of length one. For example, given a 1-dimensional array with shape (x,) using new axis the shape can be changed to (1,x) or (x,1) depending on what is desired. In effect making a row or column vector.
The following example has an array, a, of shape (4,) and a second array, b, of shape (3,). According to the two conditions stated earlier broadcasting for these two matrices is not valid
︡5ed5b907-75bb-4006-a27c-cfe24c20a2dc︡︡{"done":true,"md":"When using broadcasting the command `np.newaxis` can be helpful. The newaxis object creates an axis of length one. For example, given a 1-dimensional array with shape (x,) using new axis the shape can be changed to (1,x) or (x,1) depending on what is desired. In effect making a row or column vector.\n\nThe following example has an array, a, of shape (4,) and a second array, b, of shape (3,). According to the two conditions stated earlier broadcasting for these two matrices is not valid"}
︠480a8ce7-0b87-4afb-b843-362b99d53363s︠
a = np.array([0.0,10.0,20.0,30.0]) # a is of shape (4,)
b = np.array([0,1.0,2.0]) # b is of shape (3,)
a + b
︡da9dc525-feba-4814-b8eb-8740be48667e︡︡{"stderr":"Error in lines 3-3\nTraceback (most recent call last):\n File \"/projects/sage/sage-6.10/local/lib/python2.7/site-packages/smc_sagews/sage_server.py\", line 904, in execute\n exec compile(block+'\\n', '', 'single') in namespace, locals\n File \"\", line 1, in \nValueError: operands could not be broadcast together with shapes (4,) (3,) \n"}︡{"done":true}
︠3f45c893-9fe4-41b4-9904-25e5e48ad594i︠
%md
An axis of length 1 can be created for array a changing its shape to (4,1) using np.newaxis to make broadcasting valid.
︡476e2076-c2fe-48ee-9bde-c4ada851f9c7︡︡{"done":true,"md":"An axis of length 1 can be created for array a changing its shape to (4,1) using np.newaxis to make broadcasting valid."}
︠4dbc29e7-246e-4fd9-a4d5-f6308253a4e1s︠
a[:,np.newaxis]+b # a is now of shape (4,1) and the operation can be completed
︡86da9a36-1866-4e87-9609-b9d76e576102︡︡{"stdout":"array([[ 0., 1., 2.],\n [ 10., 11., 12.],\n [ 20., 21., 22.],\n [ 30., 31., 32.]])\n"}︡{"done":true}
︠f50486e4-4f4a-4c27-badd-a1b8def0037ai︠
%md
The result can be visualized with the following figure.
![](http://scipy.github.io/old-wiki/pages/image004de9e.gif?action=AttachFile&do=get&target=image004.gif)
“EricsBroadcastingDoc - SciPy wiki dump,” Scipy: EricsBroadcastingDoc. [Online]. Available: http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc. [Accessed: 02-Apr-2016].
︡901d3f26-7769-4c25-ae75-2875909836f7︡︡{"done":true,"md":"The result can be visualized with the following figure.\n\n\n![](http://scipy.github.io/old-wiki/pages/image004de9e.gif?action=AttachFile&do=get&target=image004.gif)\n\n\n“EricsBroadcastingDoc - SciPy wiki dump,” Scipy: EricsBroadcastingDoc. [Online]. Available: http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc. [Accessed: 02-Apr-2016]."}
︠d8d84791-2681-4bc3-9cfa-f12d79add914i︠
%md
This corresponds to an "outer" operation. A common outer operation is the outer product of two vectors. Using numpy broadcasting the outer product of a and b can easily be realized.
︡89d0d0eb-433c-4e85-8894-55cf1f9bc74d︡︡{"done":true,"md":"This corresponds to an \"outer\" operation. A common outer operation is the outer product of two vectors. Using numpy broadcasting the outer product of a and b can easily be realized."}
︠8195528c-660c-4100-a80d-1b436fff55b7s︠
a[:,np.newaxis]*b
︡ea6afa45-893a-4b3a-8a70-7fd4e6f9ae92︡︡{"stdout":"array([[ 0., 0., 0.],\n [ 0., 10., 20.],\n [ 0., 20., 40.],\n [ 0., 30., 60.]])\n"}︡{"done":true}
︠f9d70b56-8df4-4644-8877-c5430bb06a8ci︠
%md
### Practical Applications
Lets explore two practical examples that showcase how useful broadcasting can be.
︡8f827937-16e2-4bd1-9988-2b586455af3b︡︡{"done":true,"md":"### Practical Applications\n\nLets explore two practical examples that showcase how useful broadcasting can be."}
︠16027c2c-e7ac-4469-ad5c-8ad6cbe489cfi︠
%md
#### Example 1
︡603036cc-492b-4775-a1f6-fb5723c4874b︡︡{"done":true,"md":"#### Example 1"}
︠b7dc2e58-0d1e-4d2b-aa54-eb66c23f69b5i︠
%md
This is an example taken with permission from [Eli Bendersky's website](http://eli.thegreenplace.net/2015/broadcasting-arrays-in-numpy/) from a blog post explaining broadcasting in NumPy.
E. Bendersky, “Broadcasting arrays in Numpy - Eli Bendersky’s website.” [Online]. Available: http://eli.thegreenplace.net/2015/broadcasting-arrays-in-numpy/. [Accessed: 02-Apr-2016].
︡54d5c652-f996-4528-af43-bd800dfab545︡︡{"done":true,"md":"This is an example taken with permission from [Eli Bendersky's website](http://eli.thegreenplace.net/2015/broadcasting-arrays-in-numpy/) from a blog post explaining broadcasting in NumPy.\n\n\nE. Bendersky, “Broadcasting arrays in Numpy - Eli Bendersky’s website.” [Online]. Available: http://eli.thegreenplace.net/2015/broadcasting-arrays-in-numpy/. [Accessed: 02-Apr-2016]."}
︠d2456e47-deb1-4203-8bf5-25ae80993bc4i︠
%md
Say we have a large data set; each datum is a list of parameters. In NumPy terms, we have a 2-D array, where each row is a datum and the number of rows is the size of the data set. Suppose we want to apply some sort of scaling to all this data - every parameter gets its own scaling factor; in other words, every parameter is multiplied by some factor.
Just to have something tangible to think about, let's count calories in foods using a macro-nutrient breakdown. Roughly put, the caloric parts of food are made of fats (9 calories per gram), protein (4 calories per gram) and carbs (4 calories per gram). So if we list some foods (our data), and for each food list its macro-nutrient breakdown (parameters), we can then multiply each nutrient by its caloric value (apply scaling) to compute the caloric breakdown of each food item:
![](http://eli.thegreenplace.net/images/2015/cal-data.png)
︡6ed796b2-e9c6-4f76-ac87-dea1acd746ec︡︡{"done":true,"md":"Say we have a large data set; each datum is a list of parameters. In NumPy terms, we have a 2-D array, where each row is a datum and the number of rows is the size of the data set. Suppose we want to apply some sort of scaling to all this data - every parameter gets its own scaling factor; in other words, every parameter is multiplied by some factor.\n\n\nJust to have something tangible to think about, let's count calories in foods using a macro-nutrient breakdown. Roughly put, the caloric parts of food are made of fats (9 calories per gram), protein (4 calories per gram) and carbs (4 calories per gram). So if we list some foods (our data), and for each food list its macro-nutrient breakdown (parameters), we can then multiply each nutrient by its caloric value (apply scaling) to compute the caloric breakdown of each food item:\n![](http://eli.thegreenplace.net/images/2015/cal-data.png)"}
︠87b4eb11-7061-4ea3-9e8d-d2c4cb88af27i︠
%md
Here is the first table shown above that has quantities in terms of grams (g).
︡64c9a4e9-47f6-46eb-a632-52b638ee4808︡︡{"done":true,"md":"Here is the first table shown above that has quantities in terms of grams (g)."}
︠0896dd19-2121-48ce-a546-f2528b4856a2s︠
macros = np.array([
[0.3, 2.5, 3.5],
[2.9, 27.5, 0],
[0.4, 1.3, 23.9],
[14.4, 6, 2.3]]) # shape (4,3)
︡90543730-cadd-4aeb-8a44-78d6f33084e7︡︡{"done":true}
︠de9026d5-a007-4981-9dad-ee27bc60cd7ci︠
%md
Next a key to convert grams of fats, proteins, and carbs to calories is created. 9 cal per gram of fat, 4 cals per gram of protein, and 4 cals per gram of carbs.
︡c47ea1b3-c6a3-4a77-bf4c-fa74188e4129︡︡{"done":true,"md":"Next a key to convert grams of fats, proteins, and carbs to calories is created. 9 cal per gram of fat, 4 cals per gram of protein, and 4 cals per gram of carbs."}
︠1c8455bd-50c8-4bec-a30a-07856e22a250s︠
cal_per_macro = np.array([9,4,4]) # shape (3,)
︡1f3971f7-1694-4f71-9ec8-91d3be5fde6b︡︡{"done":true}
︠f83ffa17-78bb-474b-948b-e81011b56751i︠
%md
Now, even if the table has an arbitrarily large number of entries converting grams of nutrient to calories is easy. As shown below the second table is generated.
︡9aeab8b8-770d-4ec6-aa18-b09ac134f74c︡︡{"done":true,"md":"Now, even if the table has an arbitrarily large number of entries converting grams of nutrient to calories is easy. As shown below the second table is generated."}
︠c7482383-c842-4dec-b7cf-2ae48529a87bs︠
Food_cal = macros*cal_per_macro
Food_cal
︡d39704a8-5892-4c79-9332-97440d3f0f18︡︡{"stdout":"array([[ 2.7, 10. , 14. ],\n [ 26.1, 110. , 0. ],\n [ 3.6, 5.2, 95.6],\n [ 129.6, 24. , 9.2]])\n"}︡{"done":true}
︠8534ec32-e8b6-43af-8eee-8156e9ae2d32i︠
%md
#### Example 2
︡04471da6-692f-48e5-9080-9f6d2c3c6183︡︡{"done":true,"md":"#### Example 2"}
︠91257fcf-0798-44db-b8f4-7ee0d12cd69ei︠
%md
Consider an image represented as an array of RGB values of shape (d1,d2,3), where d1 x d2 is the size of the image in pixels, and for each pixel there are three numeric values Red, Green, and Blue (RGB).
Here the SciPy library is used to import a generic image and matplotlib is used to display the image.
︡0b364c31-acbf-489a-a32e-e62b18830d3d︡︡{"done":true,"md":"Consider an image represented as an array of RGB values of shape (d1,d2,3), where d1 x d2 is the size of the image in pixels, and for each pixel there are three numeric values Red, Green, and Blue (RGB).\n\n\nHere the SciPy library is used to import a generic image and matplotlib is used to display the image."}
︠bebc63fc-23ea-49b7-bbf6-13e408e771c0s︠
%auto
import scipy.misc
import matplotlib.pyplot as plt
︡ddcae87c-4f51-45e3-8fb6-9496213b9196︡︡{"done":true}
︠22a54cb2-2988-484b-8064-7fea7f3ace45s︠
image = scipy.misc.face() # import a generic image from the scipy library
print('image.shape = ' + str(image.shape))
f = plt.imshow(image)
plt.show(f)
︡d24cf2da-ceb6-44fa-a3ca-70ca023449cc︡︡{"stdout":"image.shape = (768, 1024, 3)\n"}︡{"file":{"filename":"2e1714d5-782b-4014-a0cd-6d3c0144b3ef.svg","show":true,"uuid":"dd831257-458c-4adf-b21c-233691ae2b8e"},"once":false}︡{"done":true}
︠219bc09f-59e4-4edb-9c5e-8175fde6b4b4i︠
%md
The shape is (768,1024,3) so the size of the image is 768 x 1024. We can use broadcasting to apply a filter to the RGB values at each pixel. As a simple example, to leave the R values and get rid of the G and B values multiply the image array by an array of shape (3,): [1,0,0].
︡a191933d-b17b-41c9-b67e-11fb12592f51︡︡{"done":true,"md":"The shape is (768,1024,3) so the size of the image is 768 x 1024. We can use broadcasting to apply a filter to the RGB values at each pixel. As a simple example, to leave the R values and get rid of the G and B values multiply the image array by an array of shape (3,): [1,0,0]."}
︠615a8699-346a-405a-975a-a65134d491e7s︠
red_filter = np.array([1,0,0],dtype='uint8') # shape (3,)
red_image = image * red_filter
f = plt.imshow(red_image)
plt.show(f)
︡5340bcc3-fb44-4891-af3b-2a3f9f70b370︡︡{"file":{"filename":"fa88cc61-da7b-4f10-9fbd-b5c4e31dfa10.svg","show":true,"uuid":"f2b40f71-920b-42e7-88e6-f6c8fdca4905"},"once":false}︡{"done":true}
︠515556d2-9082-43e6-be1e-532096814dcai︠
%md
### Note for Matlab/Octave users
Various other high level programming languages offer similar functionality. For Matlab/Octave users, the case of an array times a scalar works the same, but when two arrays are multiplied together the behavior is very different. Similar functionality to NumPy's broadcasting can be achieved in Matlab/Octave using the bsxfun() or the repmat() function, but it is not as straightforward or readable as the built in broadcasting for numpy. The Matlab/Octave * operator is similar to the NumPy .dot() or * using the NumPy matrix class.
︡985c8f1b-52bc-4880-a25b-10dec4a3e95e︡︡{"done":true,"md":"### Note for Matlab/Octave users\n\nVarious other high level programming languages offer similar functionality. For Matlab/Octave users, the case of an array times a scalar works the same, but when two arrays are multiplied together the behavior is very different. Similar functionality to NumPy's broadcasting can be achieved in Matlab/Octave using the bsxfun() or the repmat() function, but it is not as straightforward or readable as the built in broadcasting for numpy. The Matlab/Octave * operator is similar to the NumPy .dot() or * using the NumPy matrix class."}
︠f7604da3-5d4e-423b-976a-211974b52cbei︠
%md
For example, vectors are always matrices, and may need transposition for scalar multiplication.
︡64fb864e-ca08-45c5-9ce2-dd17d7b0f226︡︡{"done":true,"md":"\nFor example, vectors are always matrices, and may need transposition for scalar multiplication."}
︠0034f820-451f-49af-bfa5-fcc106d930ees︠
%octave
a = [1, 2; 3, 4];
b = [5, 10];
a*b'
︡8e0b3821-04ee-4e6d-b817-572e471e0772︡︡{"stdout":"\n\nans =\n\n 25\n 55\n\n"}︡{"done":true}
︠6a5dda2b-cfe0-4a37-be08-841d860bc922i︠
%md
### Note for R users
Numpy does not have R's way of repeating vectors that are too short.
︡ffab8549-f365-48a8-b201-b7f03ce29248︡︡{"done":true,"md":"### Note for R users\n\nNumpy does not have R's way of repeating vectors that are too short."}
︠2d2751cf-c65b-4190-b390-1c8af804380es︠
a = np.array([1,2,3,4])
b = np.array([5,10])
a+b
︡2f937fc8-8e54-4dab-b3b9-75db81cc8e80︡︡{"stderr":"Error in lines 3-3\nTraceback (most recent call last):\n File \"/projects/sage/sage-6.10/local/lib/python2.7/site-packages/smc_sagews/sage_server.py\", line 904, in execute\n exec compile(block+'\\n', '', 'single') in namespace, locals\n File \"\", line 1, in \nValueError: operands could not be broadcast together with shapes (4,) (2,) \n"}︡{"done":true}
︠506ec643-e702-4650-b58c-1de780477026i︠
%md
while this works in R
︡f77c83f9-71fc-4078-85f4-7f982deb125e︡︡{"done":true,"md":"\nwhile this works in R"}
︠ca20e925-b404-4e78-b282-7dcd804a4bf6s︠
%r
a <- c(1,2,3,4)
b <- c(5, 10)
a + b
︡2ef6e4f6-ae5f-40c5-a074-e41f946e494c︡︡{"stdout":"[1] 6 12 8 14"}︡{"done":true}
︠721c64a9-73b8-424a-bb24-d0f48607e634i︠
%md
### Explore
︡6ffee3c5-e27a-4a26-9a0b-55766ce9b515︡︡{"done":true,"md":"### Explore"}
︠2f2e2b85-748c-4d5d-8f64-32ac93f07747i︠
%md
You can explore broadcasting by generating arrays with different sizes performing, an operation with them, and observing the result using the code below.
np.random.randint(N,size=(d1,d2,...,dn)) generates an array with shape (d1,d2,...,dn) filled with random integers between 0 and N.
︡da6153d1-a472-4c1f-8eaf-5bb39e2569dd︡︡{"done":true,"md":"You can explore broadcasting by generating arrays with different sizes performing, an operation with them, and observing the result using the code below.\n\nnp.random.randint(N,size=(d1,d2,...,dn)) generates an array with shape (d1,d2,...,dn) filled with random integers between 0 and N."}
︠9cadc1ec-f7fa-4c29-85b0-6215e4030fe1s︠
a = np.random.randint(10,size=(4,1));
b = np.random.randint(10,size=(2,4,3));
a*b
︡05a47042-a9f9-4f89-820c-aff093f82994︡︡{"stdout":"array([[[42, 0, 36],\n [ 8, 40, 24],\n [ 0, 0, 0],\n [ 0, 63, 54]],\n\n [[ 6, 54, 0],\n [32, 16, 64],\n [ 0, 0, 0],\n [54, 0, 9]]])\n"}︡{"done":true}
︠fb731f74-75bb-4820-b6b8-9282d4cc750fi︠
%md
### Exercises
︡44aebb77-94fa-4c93-b51b-15daace239eb︡︡{"done":true,"md":"### Exercises"}
︠b04c80cd-7894-41f8-93e7-09fba3b78030i︠
%md
1. Using broadcasting add 100 to each entry in array a.
︡169c1cf6-d741-4369-8080-22b41f00589b︡︡{"done":true,"md":"1. Using broadcasting add 100 to each entry in array a."}
︠542ae6e4-9438-469e-82b4-571efc496078s︠
a = np.array([[1,2,3,4],[5,6,7,8]])
︡913f3621-17ef-4526-a294-3197210e19ea︡︡{"done":true}
︠1148292f-725f-4914-8fa7-2eefaaa1c7c0s︠
# Answer
b = 100;
a+b
︡5a25f51f-ec0b-4a9a-805b-2de8cb4a7159︡︡{"stdout":"array([[101, 102, 103, 104],\n [105, 106, 107, 108]])\n"}︡{"done":true}
︠c1e5cd74-acf9-4dd9-b88f-41860588c6a8i︠
%md
2. Create an array, b1, that when multiplied with array a will cause the first column of a to be multiplied by 10, the second column by 5, the third column by 2, and the fourth column by 1.
︡a01365f5-7580-42d4-94a2-e5aef8a89093︡︡{"done":true,"md":"2. Create an array, b1, that when multiplied with array a will cause the first column of a to be multiplied by 10, the second column by 5, the third column by 2, and the fourth column by 1."}
︠fc4bf58b-2d7c-420b-8f8d-68acd93a0e60s︠
a = np.array([[ 1, 2, 5, 10],
[ 1, 2, 5, 10],
[ 1, 2, 5, 10],
[ 1, 2, 5, 10]])
︡17d55c59-053c-4c8e-9fea-c4f140d5f914︡︡{"done":true}
︠aeb9d7e2-0e63-4a4f-b9bd-113ad3381b1ds︠
# Answer
b1 = np.array([10,5,2,1])
a*b1
︡9aa428f6-3d1d-4092-90e0-ddd851df3bdd︡︡{"stdout":"array([[10, 10, 10, 10],\n [10, 10, 10, 10],\n [10, 10, 10, 10],\n [10, 10, 10, 10]])\n"}︡{"done":true}
︠f1338ec7-13d8-4155-9bb7-24a8b1c59f57i︠
%md
3. Create and array, b2, that when multiplied with array a using np.newaxis will cause the first row of a to be multiplied by 1, the second row by 2, the third row by 3, and the fourth row by 4.
︡6a57dd2e-706e-42cd-958f-0d086621410d︡︡{"done":true,"md":"3. Create and array, b2, that when multiplied with array a using np.newaxis will cause the first row of a to be multiplied by 1, the second row by 2, the third row by 3, and the fourth row by 4."}
︠d7634d14-2253-4e36-92bb-3ff16489422ds︠
a = np.array([[ 1, 2, 5, 10],
[ 1, 2, 5, 10],
[ 1, 2, 5, 10],
[ 1, 2, 5, 10]])
︡08d70ee8-e903-45c2-988b-9f8119625bc6︡︡{"done":true}
︠7d7e5dd9-20b1-41ef-be10-08e2d9b4198cs︠
# Answer
b2 = np.array([1,2,3,4])
a*b2[:,np.newaxis]
︡1473eee9-2e73-49a3-a8a6-10a391c9af9e︡︡{"stdout":"array([[ 1, 2, 5, 10],\n [ 2, 4, 10, 20],\n [ 3, 6, 15, 30],\n [ 4, 8, 20, 40]])\n"}︡{"done":true}
︠6627ed55-53b3-4774-b078-e82a9bf6a2fci︠
%md
4. Using np.newaxis compute the outer product of the vectors [1,2,3,4,5] and [2,4,6,8,10].
︡8c3a4f9e-1e37-4bfe-b7a6-bde79b8bf00b︡︡{"done":true,"md":"4. Using np.newaxis compute the outer product of the vectors [1,2,3,4,5] and [2,4,6,8,10]."}
︠1b9c72c8-dd87-49d8-8725-f40a8ecd5fe9s︠
# Answer
a = np.array([1,2,3,4,5])
b = np.array([2,4,6,8,10])
a[:, np.newaxis] *b
︡bf88497e-4d55-4541-886b-b64e9d86d356︡︡{"stdout":"array([[ 2, 4, 6, 8, 10],\n [ 4, 8, 12, 16, 20],\n [ 6, 12, 18, 24, 30],\n [ 8, 16, 24, 32, 40],\n [10, 20, 30, 40, 50]])\n"}︡{"done":true}
︠dc68eb12-b0fe-496f-8713-97ea39dc3693s︠
2*a*a[:, np.newaxis]
︡82606d5a-d7b1-4a92-8914-308b540e129c︡︡{"stdout":"array([[ 2, 4, 6, 8, 10],\n [ 4, 8, 12, 16, 20],\n [ 6, 12, 18, 24, 30],\n [ 8, 16, 24, 32, 40],\n [10, 20, 30, 40, 50]])\n"}︡{"done":true}
︠533286e7-7bc8-4e48-8a3f-ecae88aa4f49s︠
︡8029f501-2e42-4ea3-b5bf-cf76bf79aeaa︡︡{"done":true}