Linear Algebra Basics with NumPy (`np.linalg`)
8 min read
Course: NumPy
Topic: Linear Algebra Basics with NumPy (np.linalg)
Hey there! π Welcome to the fascinating world of linear algebra with NumPy. It might sound a bit intimidating, but trust me, it's a powerful tool that's more about solving puzzles than getting lost in complex math. We'll be using NumPy's linalg module, which is like a super-calculator for all things vectors and matrices.
Think of it this way: you're a video game developer. You need to calculate how a character moves, how light bounces off a wall, or how two objects collide. All of this is powered by the concepts we're about to explore. So, let's get you equipped with the skills to build your own virtual worlds! π
1. Vector Dot Products and Matrix Multiplication: np.dot() and @
The Problem: Imagine you're running a small bakery. π§ You sell three types of cupcakes: chocolate, vanilla, and red velvet. You have the number of each type you sold today, and you know the price of each. How do you quickly calculate your total revenue for the day?
This is where the dot product comes in. It's a way to multiply two vectors (which are just lists of numbers) and get a single number as a result.
The Solution: In NumPy, we can represent the number of cupcakes sold as one vector and the price of each as another.
import numpy as np
# Number of cupcakes sold
cupcakes_sold = np.array([50, 65, 42]) # [chocolate, vanilla, red velvet]
# Price per cupcake
cupcake_prices = np.array([3, 2.5, 3.5]) # [price for chocolate, vanilla, red velvet]
# Calculate total revenue using np.dot()
total_revenue = np.dot(cupcakes_sold, cupcake_prices)
print(f"Total Revenue: ${total_revenue}")What's happening under the hood?np.dot() performs the following calculation: (50 * 3) + (65 * 2.5) + (42 * 3.5). It multiplies the corresponding elements of the two vectors and then adds up the results.
Meet the @ Operator
Since Python 3.5, we have a cool new way to do matrix multiplication: the @ operator. For dot products of 1-D arrays (like our cupcake example), it works exactly the same as np.dot().
# Using the @ operator
total_revenue_with_at = cupcakes_sold @ cupcake_prices
print(f"Total Revenue with @: ${total_revenue_with_at}")So which one should you use? For the dot product of two vectors, it's a matter of style. However, when we get to multiplying matrices (2-D arrays), @ is often preferred for its readability.
Matrix Multiplication
The Problem: Now, let's say your bakery has two locations, and you want to calculate the total sales for each cupcake type across both locations.
- Location A Sales: [50 chocolate, 65 vanilla, 42 red velvet]
- Location B Sales: [45 chocolate, 70 vanilla, 38 red velvet]
And you want to calculate the total amount of each main ingredient (flour, sugar, eggs) you've used across all cupcakes sold.
Let's say each cupcake type requires the following units of ingredients:
- Chocolate: [2 flour, 1.5 sugar, 1 egg]
- Vanilla: [1.8 flour, 1.2 sugar, 1 egg]
- Red Velvet: [2.2 flour, 1.8 sugar, 1.2 eggs]
This is a perfect scenario for matrix multiplication.
The Solution:
import numpy as np
# Sales data for two locations (2x3 matrix)
sales = np.array([
[50, 65, 42], # Location A
[45, 70, 38] # Location B
])
# Ingredient requirements per cupcake type (3x3 matrix)
ingredients = np.array([
[2, 1.5, 1], # Flour, Sugar, Eggs for Chocolate
[1.8, 1.2, 1], # for Vanilla
[2.2, 1.8, 1.2] # for Red Velvet
])
# Calculate total ingredients used for each location
total_ingredients = sales @ ingredients
print("Total ingredients used per location:")
print(total_ingredients)What just happened? The @ operator multiplied the sales matrix by the ingredients matrix. The result is a new matrix where each row represents a location and each column represents the total amount of an ingredient used.
π§ Fun Fact: The choice between
np.dot()and@can sometimes feel like choosing between "GIF" with a hard G or a soft G. While both can often do the job, the community has leaned towards@for matrix multiplication because it looks cleaner and more like the math you see in textbooks.
2. Matrix Inverses and Determinants
Matrix Determinants
The Problem: Imagine you're designing a 2D video game. You have a character that you want to scale up or down. The determinant of a transformation matrix can tell you by how much the area of your character's sprite changes after the transformation. If the determinant is 2, the area doubles. If it's 0.5, it halves. If it's 0, your character has been squashed into a line β oops! π¬
The Solution: NumPy's np.linalg.det() calculates the determinant of a matrix.
import numpy as np
# A matrix that scales things up
scaling_matrix = np.array([
[2, 0],
[0, 3]
])
# Calculate the determinant
determinant = np.linalg.det(scaling_matrix)
print(f"The determinant is: {determinant}")A determinant of 6.0 means that any area transformed by this matrix will become 6 times larger.
π‘ A determinant of 0 is a big deal! It means the matrix is "singular," which has important implications, as we'll see next.
Matrix Inverses
The Problem: You've just applied a transformation to your game character (like rotating and scaling it). Now, you want to undo that transformation. How do you find the exact operation that reverses the original one? This is where the matrix inverse comes in.
The inverse of a matrix, when multiplied by the original matrix, gives you the identity matrix (which is like the number 1 for matrices β it doesn't change anything).
The Solution: np.linalg.inv() is your go-to function.
import numpy as np
# Our transformation matrix
transform = np.array([
[1, 2],
[3, 4]
])
# Calculate the inverse
inverse_transform = np.linalg.inv(transform)
print("Original Matrix:\n", transform)
print("\nInverse Matrix:\n", inverse_transform)
# Let's prove it!
identity_matrix = transform @ inverse_transform
print("\nOriginal @ Inverse:\n", np.round(identity_matrix)) # Rounding to handle tiny floating point errorsMultiplying a matrix by its inverse gives you the identity matrix ([[1., 0.], [0., 1.]]).
π¨ Important Note: You can only find the inverse of a square matrix that has a non-zero determinant. If the determinant is zero, it means the transformation is not reversible (you can't un-squash a flattened object back into its 2D form!), and NumPy will raise a
LinAlgError.
3. Solving Systems of Linear Equations
The Problem: You're at a farmer's market. ππ
- 2 apples and 3 bananas cost $8.
- 10 apples and 1 banana cost $13.
What is the price of one apple and one banana? This is a classic system of linear equations:
2x + 3y = 810x + 1y = 13
Where x is the price of an apple and y is the price of a banana. While you could solve this by hand, imagine having dozens of equations with dozens of variables. That would be a nightmare!
The Solution: NumPy can solve this in a flash with np.linalg.solve(). We need to represent the problem in the form Ax = B, where:
Ais a matrix of the coefficients of the variables.xis the vector of variables we want to solve for.Bis the vector of the results.
import numpy as np
# Coefficient matrix (A)
# [[2, 3],
# [10, 1]]
A = np.array([
[2, 3],
[10, 1]
])
# Results vector (B)
# [8, 13]
B = np.array([8, 13])
# Solve for x (the prices)
prices = np.linalg.solve(A, B)
print(f"The price of an apple is: ${prices[0]:.2f}")
print(f"The price of a banana is: ${prices[1]:.2f}")And there you have it! NumPy has figured out the prices for us. This is incredibly useful in fields like economics, engineering, and physics, where you often deal with large systems of interconnected variables.
4. Understanding Vector Norms: np.linalg.norm()
The Problem: You're creating a GPS application. You have the coordinates of two points, and you need to calculate the straight-line distance between them. This distance is a fundamental concept known as the "norm" of a vector.
In simpler terms, the norm of a vector is its length or magnitude.
The Solution: np.linalg.norm() calculates the norm of a vector.
Let's say you have a vector that represents a movement of 3 units to the east and 4 units to the north. What's the total distance traveled as the crow flies? π¦
import numpy as np
# A vector representing movement [3 units east, 4 units north]
movement = np.array([3, 4])
# Calculate the Euclidean norm (the straight-line distance)
distance = np.linalg.norm(movement)
print(f"The distance is: {distance} units")This is a direct application of the Pythagorean theorem (sqrt(3**2 + 4**2)), and it's the most common type of norm, also known as the L2 norm.
π§ Beyond Straight Lines: The concept of "norm" is more general. For instance, there's the L1 norm (or "Manhattan distance"), which is the distance you'd travel in a city grid where you can only move along the streets.
np.linalg.norm()can calculate this too!
# Calculate the Manhattan distance (L1 norm)
manhattan_distance = np.linalg.norm(movement, ord=1)
print(f"The Manhattan distance is: {manhattan_distance} units")In this case, you travel 3 units and then 4 units, for a total of 7 units. This is useful in scenarios where movement is restricted to a grid, like in some video games or city planning simulations.
π Extra Reading & References
- Official NumPy Linear Algebra Documentation: For a deep dive into all the functions available.
- A Visual Introduction to Linear Algebra: A great resource for understanding the concepts visually.
numpy.dot()documentation:numpy.linalg.solve()documentation:numpy.linalg.norm()documentation:
Challenge
You are a game developer building a 2D space shooter and need to implement several core mechanics using NumPy's linear algebra capabilities.
Your task is to perform the following calculations based on the initial data provided:
- A player's ship, defined by the
player_ship_coordsmatrix, undergoes a geometric transformation. Apply thetransformation_matrixto the ship's coordinates. Store the resulting new coordinates in a variable namedtransformed_ship_coords. - Determine the scaling factor of the area of the transformation by calculating the determinant of the
transformation_matrix. Store this value in a variable namedtransform_determinant. - A projectile's trajectory is modeled by the system of linear equations
Ax = B. Solve for the initial velocity vectorx. Store the resulting vector in a variable namedprojectile_velocity. - Calculate the straight-line (Euclidean or L2 norm) distance between the player's starting position (
player_origin) and theenemy_ship_coords. Store this distance in a variable nameddistance_to_enemy.
Expected result
Your final code should correctly calculate and assign values to the four placeholder variables.
transformed_ship_coords: A 2x3 NumPy array containing the new coordinates of the ship's vertices after matrix multiplication withtransformation_matrix.transform_determinant: A float representing the determinant oftransformation_matrix.projectile_velocity: A 1D NumPy array of shape(2,)containing the solution to the system of linear equationsAx = B.distance_to_enemy: A float representing the L2 norm (Euclidean distance) of the vector difference betweenenemy_ship_coordsandplayer_origin.