Path: blob/master/1 - Natural Language Processing with Classification and Vector Spaces/Week 3/C1W3_L1_Linear algebra in Python with Numpy.ipynb
65 views
Linear algebra in Python with NumPy
In this lab, you will have the opportunity to remember some basic concepts about linear algebra and how to use them in Python.
Numpy is one of the most used libraries in Python for arrays manipulation. It adds to Python a set of functions that allows us to operate on large multidimensional arrays with just a few lines. So forget about writing nested loops for adding matrices! With NumPy, this is as simple as adding numbers.
Let us import the numpy library and assign the alias np for it. We will follow this convention in almost every notebook in this course, and you'll see this in many resources outside this course as well.
Defining lists and numpy arrays
Note the difference between a Python list and a NumPy array.
Algebraic operators on NumPy arrays vs. Python lists
One of the common beginner mistakes is to mix up the concepts of NumPy arrays and Python lists. Just observe the next example, where we add two objects of the two mentioned types. Note that the '+' operator on NumPy arrays perform an element-wise addition, while the same operation on Python lists results in a list concatenation. Be careful while coding. Knowing this can save many headaches.
It is the same as with the product operator, *. In the first case, we scale the vector, while in the second case, we concatenate three times the same list.
Be aware of the difference because, within the same function, both types of arrays can appear. Numpy arrays are designed for numerical and matrix operations, while lists are for more general purposes.
Matrix or Array of Arrays
In linear algebra, a matrix is a structure composed of n rows by m columns. That means each row must have the same number of columns. With NumPy, we have two ways to create a matrix:
Creating an array of arrays using
np.array(recommended).Creating a matrix using
np.matrix(still available but might be removed soon).
NumPy arrays or lists can be used to initialize a matrix, but the resulting matrix will be composed of NumPy arrays only.
However, when defining a matrix, be sure that all the rows contain the same number of elements. Otherwise, the linear algebra operations could lead to unexpected results.
Analyze the following two examples:
Scaling and translating matrices
Now that you know how to build correct NumPy arrays and matrices, let us see how easy it is to operate with them in Python using the regular algebraic operators like + and -.
Operations can be performed between arrays and arrays or between arrays and scalars.
The product operator * when used on arrays or matrices indicates element-wise multiplications. Do not confuse it with the dot product.
Transpose a matrix
In linear algebra, the transpose of a matrix is an operator that flips a matrix over its diagonal, i.e., the transpose operator switches the row and column indices of the matrix producing another matrix. If the original matrix dimension is n by m, the resulting transposed matrix will be m by n.
T denotes the transpose operations with NumPy matrices.
However, note that the transpose operation does not affect 1D arrays.
perhaps in this case you wanted to do:
Get the norm of a nparray or matrix
In linear algebra, the norm of an n-dimensional vector is defined as:
Calculating the norm of vector or even of a matrix is a general operation when dealing with data. Numpy has a set of functions for linear algebra in the subpackage linalg, including the norm function. Let us see how to get the norm a given array or matrix:
Note that without any other parameter, the norm function treats the matrix as being just an array of numbers. However, it is possible to get the norm by rows or by columns. The axis parameter controls the form of the operation:
axis=0 means get the norm of each column
axis=1 means get the norm of each row.
However, there are more ways to get the norm of a matrix in Python. For that, let us see all the different ways of defining the dot product between 2 arrays.
The dot product between arrays: All the flavors
The dot product or scalar product or inner product between two vectors and of the same size is defined as:
The dot product takes two vectors and returns a single number.
We strongly recommend using np.dot, since it is the only method that accepts arrays and lists without problems
Finally, note that the norm is the square root of the dot product of the vector with itself. That gives many options to write that function:
Sums by rows or columns
Another general operation performed on matrices is the sum by rows or columns. Just as we did for the function norm, the axis parameter controls the form of the operation:
axis=0 means to sum the elements of each column together.
axis=1 means to sum the elements of each row together.
Get the mean by rows or columns
As with the sums, one can get the mean by rows or columns using the axis parameter. Just remember that the mean is the sum of the elements divided by the length of the vector
Center the columns of a matrix
Centering the attributes of a data matrix is another essential preprocessing step. Centering a matrix means to remove the column mean to each element inside the column. The sum by columns of a centered matrix is always 0.
With NumPy, this process is as simple as this:
Warning: This process does not apply for row centering. In such cases, consider transposing the matrix, centering by columns, and then transpose back the result.
See the example below:
Note that some operations can be performed using static functions like np.sum() or np.mean(), or by using the inner functions of the array
Even if they are equivalent, we recommend the use of the static way always.
Congratulations! You have successfully reviewed vector and matrix operations with Numpy!