Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

Vector and Matrix Operations

This lesson is built with resources from youtube.com, pabloinsente.github.io and 2 more sites.

Hello! Welcome to the first lesson in your journey to becoming an AI Engineer. We're starting with Module 1, "Mathematical Foundations for AI," to build the essential groundwork for everything that follows.

In this lesson, we'll dive into vectors and matrices, which are the fundamental data structures used to represent and manipulate data in AI. Your goal is to learn how to perform key operations on them: addition, multiplication, transpose, and inverse.

As a software engineer, you're used to working with data structures like arrays and lists. You can think of vectors and matrices as specialized, powerful versions of these, optimized for the mathematical operations that drive machine learning models. We'll cover both the mathematical concepts and their practical implementation in Python using the NumPy library.

1. What Are Vectors and Matrices?

At their core, vectors and matrices are simply collections of numbers arranged in a specific way.

  • A vector is a one-dimensional array of numbers. In AI, a vector can represent a single data point, like the features of a house (size, number of bedrooms, location) or the embedding of a word.
  • A matrix is a two-dimensional grid of numbers, arranged in rows and columns. Matrices are workhorses in AI, used to represent everything from a grayscale image (where each number is a pixel intensity) to the "weights" in a neural network that the model learns during training.

The "shape" of a matrix tells us its dimensions: a matrix with 3 rows and 4 columns has a shape of (3, 4).

The image below shows how these mathematical concepts translate directly into NumPy, the primary library for numerical computation in Python.

Visualizing Vectors, Matrices, and 3D Matrices with NumPy
This image illustrates how a vector (1D array), a matrix (2D array), and even higher-dimensional tensors are created as `numpy.ndarray` objects in code. This is how we'll represent them throughout the course.

To get started with creating these in code, I'd like you to read a short section from a tutorial on NumPy.

NumPy for Machine Learning: Complete Tutorial with Examples

This article, 'NumPy for Machine Learning', provides a great introduction to creating arrays. Please read the section on how to create 1D and 2D arrays.

Read the sections '2. Getting Started: Installation and the ndarray' and 'Creating a NumPy Array'. Focus on the code examples for creating vector_1d and matrix_2d.


2. Basic Matrix Operations

Now, let's look at the basic arithmetic operations you can perform on matrices. These are often performed element-wise, meaning the operation applies to corresponding elements in the matrices.

Addition, Subtraction, and Scalar Multiplication

  • Addition and Subtraction: To add or subtract two matrices, they must have the same shape. The operation is then performed on each corresponding element.
  • Scalar Multiplication: This involves multiplying a single number (a scalar) by every element in the matrix. The shape of the matrix does not change.

To see a conceptual walkthrough of these operations, please watch the following video.

Linear Algebra - Matrix Operations

The video 'Linear Algebra - Matrix Operations' from the Postcard Professor channel gives a clear, visual explanation of matrix addition and subtraction.

Watch the segment from 01:31 to 02:16, which covers matrix addition and subtraction, highlighting the element-wise nature of the operations.

Now, let's see how this is done in NumPy. The implementation is very intuitive.

Python Matrices with NumPy and SciPy

This article, 'Python Matrices with NumPy and SciPy', shows the code for these operations. Notice how Python's familiar +, -, and * operators are used.

Read the sections on 'Addition and Subtraction' and 'Scalar Multiplication'. Pay attention to the code blocks demonstrating A+B, A-B, and c*A. Note the error that occurs when trying to add matrices of different shapes.

As you saw, NumPy makes these operations straightforward. For example:

import numpy as np

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
c = 10

# Addition
C_add = A + B  
# [[1+5, 2+6], [3+7, 4+8]] -> [[6, 8], [10, 12]]

# Scalar Multiplication
C_scalar = c * A 
# [[10*1, 10*2], [10*3, 10*4]] -> [[10, 20], [30, 40]]

3. The Transpose Operation

The transpose of a matrix is what you get when you "flip" it along its main diagonal, swapping the rows and columns. If the original matrix had a shape of (m, n), its transpose will have a shape of (n, m).

For a quick conceptual overview, watch the first part of the "Linear Algebra - Matrix Operations" video.

Linear Algebra - Matrix Operations

This segment clearly demonstrates how the transpose operation works by flipping a matrix's rows and columns.

Watch from 00:46 to 01:31 to see the definition and a visual example of a matrix transpose.

In NumPy, transposing a matrix is incredibly simple—it's a property of the array object.

import numpy as np

A = np.array([[1, 2, 3], 
              [4, 5, 6]]) # A is a 2x3 matrix

A_T = A.T # A_T is the transpose of A

print("Original shape:", A.shape) # Output: (2, 3)
print("Transposed shape:", A_T.shape) # Output: (3, 2)
print("Transposed matrix:\n", A_T)
# Output:
# [[1, 4],
#  [2, 5],
#  [3, 6]]

4. Matrix Multiplication

Matrix multiplication is one of the most important operations in machine learning, but it's less intuitive than element-wise operations. It's the core calculation inside neural networks.

The key rule for matrix multiplication is that the number of columns in the first matrix must equal the number of rows in the second matrix.

If you multiply a matrix of shape (m, n) by a matrix of shape (n, p), the resulting matrix will have a shape of (m, p).

The calculation itself involves taking the dot product of the rows of the first matrix with the columns of the second. The following video provides an excellent step-by-step visualization of this process.

Linear Algebra - Matrix Operations

Understanding the mechanics of matrix multiplication is crucial. This part of the Postcard Professor video breaks it down clearly.

Watch carefully from 02:16 to 05:03. The video explains the dimension-matching rule and then walks through the calculation of each element in the resulting matrix.

In NumPy, you perform matrix multiplication using the @ operator. This is different from the * operator, which performs element-wise multiplication. Confusing the two is a very common beginner mistake!

NumPy for Machine Learning: Complete Tutorial with Examples

Now let's see the code. This article demonstrates how to use the @ operator for true matrix multiplication.

In section 'B. Linear Algebra', focus on the example under 'Matrix multiplication'. Notice the use of matrix_a @ matrix_b. The article also provides a great real-world use case related to image recognition.

Test your understanding!

You have two matrices, X with shape (50, 10) and Y with shape (20, 50).

  1. Can you compute X @ Y? If so, what will be the shape of the resulting matrix?
  2. Can you compute Y @ X? If so, what will be the shape of the resulting matrix?
Show answer
  1. No, you cannot compute X @ Y. The inner dimensions do not match. X has 10 columns, but Y has 50 rows (10 ≠ 50).
  2. Yes, you can compute Y @ X. The inner dimensions match. Y has 50 columns, and X has 50 rows. The resulting matrix will have a shape of (20, 10) (the outer dimensions).

5. The Matrix Inverse

In regular arithmetic, the inverse of a number x is 1/x, because x * (1/x) = 1. The matrix inverse is conceptually similar. For a square matrix A (i.e., shape n x n), its inverse, written as A⁻¹, is the matrix that when multiplied by A results in the identity matrix I.

The identity matrix I is a special square matrix with 1s on the main diagonal and 0s everywhere else. It's the matrix equivalent of the number 1.

A @ A⁻¹ = I

Not all square matrices have an inverse. A matrix that does not have an inverse is called a singular or degenerate matrix. In practice, we use libraries to calculate the inverse for us.

Linear Algebra - Matrix Operations

To understand the concept, this final clip from the Postcard Professor video explains what an inverse is and introduces the identity matrix.

Watch from 05:03 to 06:15. Focus on the definition of the inverse in relation to the identity matrix.

In NumPy, you can find the inverse using the linalg (linear algebra) module.

Python Matrices with NumPy and SciPy

This article demonstrates how to calculate an inverse using Python and also raises a very practical point about floating-point precision that's important for any developer.

Read the 'Inverse' section. It shows how to use linalg.inv(). Importantly, it explains why the result of A @ A_inv might not be a perfect identity matrix due to floating point errors and how to handle it.

Here is how you would do it in NumPy:

import numpy as np

A = np.array([[1, 2], [3, 4]])

# Calculate the inverse
A_inv = np.linalg.inv(A)

print("Inverse of A:\n", A_inv)

# Verify the result
# Due to floating point precision, the result is very close to, but not exactly, the identity matrix.
identity_approx = A @ A_inv
print("\nA @ A_inv:\n", identity_approx)

# We can round the result to see the perfect identity matrix
identity = np.round(identity_approx)
print("\nRounded result:\n", identity)


Conclusion

Congratulations on completing your first lesson! We've covered the essential vector and matrix operations that form the mathematical bedrock of AI.

Here are the key takeaways:

  • Vectors and Matrices are represented as numpy arrays in Python.
  • Addition, Subtraction, and Scalar Multiplication are intuitive, element-wise operations.
  • The Transpose (.T) flips a matrix's rows and columns.
  • Matrix Multiplication (@) has a strict rule about matching inner dimensions and is the computational engine of neural networks.
  • The Inverse (np.linalg.inv()) is the matrix equivalent of division and relies on the concept of the identity matrix.

In the next lesson, we will build directly on what you've learned. We'll explore how matrix-vector multiplication can be used to represent linear transformations, such as rotating, scaling, and shearing geometric shapes. This will give you a more visual and intuitive understanding of what these operations are actually doing to data.