Data in NumPy
Python is convenient, but it can also be slow. However, it does allow you to access libraries that execute faster code written in languages like C. NumPy is one such library: it provides fast alternatives to math operations in Python and is designed to work efficiently with groups of numbers - like matrices.
NumPy is a large library and we are only going to scratch the surface of it here. If you plan on doing much math with Python, you should definitely spend some time exploring its documentation to learn more.
import numpy as np
Now you can use the library by prefixing the names of functions and types with np., which you'll see in the following examples
Data Types and Shapes
The most common way to work with numbers in NumPy is through ndarray objects. They are similar to Python lists, but can have any number of dimensions. Also, ndarray supports fast math operations, which is just what we want.
Since it can store any number of dimensions, you can use ndarrays to represent any of the data types we covered before: scalars, vectors, matrices, or tensors.
Scalars
Scalars in NumPy are a bit more involved than in Python. Instead of Python’s basic types like int, float, etc., NumPy lets you specify signed and unsigned types, as well as different sizes. So instead of Python’s int, you have access to types like uint8, int8, uint16, int16, and so on.
These types are important because every object you make (vectors, matrices, tensors) eventually stores scalars. And when you create a NumPy array, you can specify the type - but every item in the array must have the same type. In this regard, NumPy arrays are more like C arrays than Python lists.
If you want to create a NumPy array that holds a scalar, you do so by passing the value to NumPy's array function, like so:
s = np.array(5)
s.shape
() means it has zero dimensions.
x = s + 3
x
v = np.array([1,2,3])
v.shape
x = v[1]
x
x = v[1:]
x
m = np.array([[1,2,3], [4,5,6], [7,8,9]])
m
m.shape
m[2][2]
t = np.array([[[[1],[2]],[[3],[4]],[[5],[6]]],[[[7],[8]],\
[[9],[10]],[[11],[12]]],[[[13],[14]],[[15],[16]],[[17],[17]]]])
t
t.shape
v = np.array([1,2,3,4])
v.shape
x = v.reshape(1,4)
x.shape
x = v.reshape(4,1)
x.shape
One more thing about reshaping NumPy arrays: if you see code from experienced NumPy users, you will often see them use a special slicing syntax instead of calling reshape. Using this syntax, the previous two examples would look like this:
x = v[None, :]
x
x = v[0:, None]
x
Those lines create a slice that looks at all of the items of v but asks NumPy to add a new dimension of size 1 for the associated axis. It may look strange to you now, but it's a common technique so it's good to be aware of it.
values = [1,2,3,4,5]
for i in range(len(values)):
values[i] += 5
values
values = [1,2,3,4,5]
values = np.array(values) + 5
values
Creating that array may seem odd, but normally you'll be storing your data in ndarrays anyway. So if you already had an ndarray named values, you could have just done:
values += 5
values
We should point out, NumPy actually has functions for things like adding, multiplying, etc. But it also supports using the standard math operators. So the following two lines are equivalent:
x = np.multiply(values, 5)
x = values * 5
x
a = np.array([[1,3],[5,7]])
a
b = np.array([[2,4],[6,8]])
b
a+b
Important Reminders About Matrix Multiplication
- The number of columns in the left matrix must equal the number of rows in the right matrix.
- The answer matrix always has the same number of rows as the left matrix and the same number of columns as the right matrix.
- Order matters. Multiplying A•B is not the same as multiplying B•A.
- Data in the left matrix should be arranged as rows., while data in the right matrix should be arranged as columns.
NumPy Matrix Multiplication
You've heard a lot about matrix multiplication in the last few videos – now you'll get to see how to do it with NumPy. However, it's important to know that NumPy supports several types of matrix multiplication.
Element-wise Multiplication You saw some element-wise multiplication already. You accomplish that with the multiply function or the * operator. Just to revisit, it would look like this:
m = np.array([[1,2,3],[4,5,6]])
m
n = m * 0.25
n
m * n
np.multiply(m, n)
a = np.array([[1,2,3,4],[5,6,7,8]])
a
a.shape
b = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
b
b.shape
c = np.matmul(a, b)
c
c.shape
If your matrices have incompatible shapes, you'll get an error, like the following:
np.matmul(b, a)
a = np.array([[1,2],[3,4]])
a
np.dot(a,a)
a.dot(a) # you can call `dot` directly on the `ndarray`
np.matmul(a,a)
While these functions return the same results for two dimensional data, you should be careful about which you choose when working with other data shapes. You can read more about the differences, and find links to other NumPy functions, in the matmul and dot documentation.
m = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
m
m.T
m.transpose()
m
NumPy does this without actually moving any data in memory - it simply changes the way it indexes the original matrix - so it’s quite efficient.
However, that also means you need to be careful with how you modify objects, because they are sharing the same data. For example, with the same matrix m from above, let's make a new variable m_t that stores m's transpose. Then look what happens if we modify a value in m_t:
m_t = m.T
m_t[3][1] = 200
m_t
m
Notice how it modified both the transpose and the original matrix, too! That's because they are sharing the same copy of data. So remember to consider the transpose just as a different view of your matrix, rather than a different matrix entirely.
inputs = np.array([[-0.27, 0.45, 0.64, 0.31]])
inputs
inputs.shape
weights = np.array([[0.02, 0.001, -0.03, 0.036], \
[0.04, -0.003, 0.025, 0.009], [0.012, -0.045, 0.28, -0.067]])
weights.shape
weights
I won't go into what they're for because you'll learn about them later, but you're going to end up wanting to find the matrix product of these two matrices.
If you try it like they are now, you get an error:
np.matmul(inputs, weights)
If you did the matrix multiplication lesson, then you've seen this error before. It's complaining of incompatible shapes because the number of columns in the left matrix, 4, does not equal the number of rows in the right matrix, 3.
So that doesn't work, but notice if you take the transpose of the weights matrix, it will:
np.matmul(inputs, weights.T).shape
np.matmul(weights, inputs.T)
The two answers are transposes of each other, so which multiplication you use really just depends on the shape you want for the output.