Path: blob/master/section-2-data-science-and-ml-tools/numpy-exercises-solutions.ipynb
874 views
NumPy Practice (solutions)
This notebook offers a set of solutions to different tasks with NumPy.
It should be noted there may be more than one different way to answer a question or complete an exercise.
Exercises are based off (and directly taken from) the quick introduction to NumPy notebook.
Different tasks will be detailed by comments or text.
For further reference and resources, it's advised to check out the NumPy documentation.
Now we've you've created 3 different arrays, let's find details about them.
Find the shape, number of dimensions, data type, size and type of each array.
Run the cell above again, what happens?
Are the numbers in the array different or the same? Why do think this is?
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-20-c7305efdb212> in <module>
1 # Try add the array of ones and the other most recent array together
----> 2 a4 + ones
ValueError: operands could not be broadcast together with shapes (3,5) (5,3)
When you try the last cell, it produces an error. Why do think this is?
How would you fix it?
What does the transpose do?
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-36-ee8f632a580a> in <module>
1 # Perform a dot product on the two newest arrays you created
----> 2 np.dot(mat3, mat4)
<__array_function__ internals> in dot(*args, **kwargs)
ValueError: shapes (4,3) and (4,3) not aligned: 3 (dim 1) != 4 (dim 0)
It doesn't work. How would you fix it?
Notice how performing a transpose allows the dot product to happen.
Why is this?
Checking out the documentation on np.dot()
may help, as well as reading Math is Fun's guide on the dot product.
Let's now compare arrays.
What happens when you compare the arrays with >
?
Extensions
For more exercises, check out the NumPy quickstart tutorial. A good practice would be to read through it and for the parts you find interesting, add them into the end of this notebook.
Pay particular attention to the section on broadcasting. And most importantly, get hands-on with the code as much as possible. If in dobut, run the code, see what it does.
The next place you could go is the Stack Overflow page for the top questions and answers for NumPy. Often, you'll find some of the most common and useful NumPy functions here. Don't forget to play around with the filters! You'll likely find something helpful here.
Finally, as always, remember, the best way to learn something new is to try it. And try it relentlessly. If you get interested in some kind of NumPy function, asking yourself, "I wonder if NumPy could do that?", go and find out.