Python & Data Science

Linear Algebra For Data Science Vectors And Matric

You have a spreadsheet of house prices. For each house, you know the square footage, the number of bedrooms, and the age in years. That’s three numbers per house. A single number — like just the square footage — can’t tell you the whole story. You need a way to keep all three numbers together and do something useful with them as a group.

How do you keep track of all these numbers at once, and more importantly, how do you transform them? That’s where vectors and matrices come in. They’re the data containers and data transformers that power every machine learning algorithm.

By the end of this article, you’ll see how vectors and matrices work — without a single proof. We’ll use one small dataset (3 houses, 3 features) as our running example. You’ll learn to think of vectors as lists of numbers (or arrows in space), and matrices as machines that transform those lists. Let’s get started.

What Even Is a Vector? (Three Ways to See It)

A vector is just a list of numbers that travel together as a unit. Think of it as a single row in your dataset: [2500, 3, 15] for one house — 2500 square feet, 3 bedrooms, 15 years old.

But there are three ways to see a vector, and each is useful in different situations. This framing comes from the brilliant 3Blue1Brown series on linear algebra.

  1. Physics view: A vector is an arrow with a length and a direction. It starts at the origin (0,0) and points to a location in space.
  2. Computer science view: A vector is an ordered list of numbers. That’s how you store it in Python.
  3. Math view: A vector is anything you can add to another vector and multiply by a number (a scalar), and still get a vector back.

Here’s the catch: the hardest part is switching between the list view and the arrow view. Both are valid — use whichever helps you in the moment.

Let’s create a vector in Python and see it as an arrow. We’ll use a 2D vector so we can plot it easily.

import numpy as np
import matplotlib.pyplot as plt

# A 2D vector: [square footage (in thousands), number of bedrooms]
house_vector = np.array([2.5, 3])

# Plot the vector as an arrow starting at the origin
plt.figure(figsize=(6, 6))
plt.quiver(0, 0, house_vector[0], house_vector[1], angles='xy', scale_units='xy', scale=1, color='blue', label='House vector')
plt.xlim(0, 4)
plt.ylim(0, 4)
plt.xlabel('Square footage (thousands)')
plt.ylabel('Number of bedrooms')
plt.title('A vector as an arrow')
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend()
plt.show()

The arrow points from the origin to the point (2.5, 3). The length of the arrow tells you something about the ‘size’ of the house — a bigger house has a longer arrow. The direction tells you the ratio of square footage to bedrooms.

Now here’s the interesting part: in data science, you almost never have just two features. You might have 50 or 500. You can’t visualize a 500-dimensional arrow. However, the math works exactly the same way. The list view becomes your best friend.

Vector Operations: What You Can Do With a List of Numbers

Vectors have two fundamental operations: addition and scalar multiplication. That’s it. Everything else in linear algebra builds on these two.

Vector addition: Add two vectors element-by-element. If you have one house with 2.5 (thousand) sqft and 3 bedrooms, and another with 1.0 sqft and 1 bedroom, adding them gives you a ‘combined’ house with 3.5 sqft and 4 bedrooms. In the arrow view, it’s like putting the tip of one arrow at the tail of the other (the triangle rule).

Scalar multiplication: Multiply every element of a vector by the same number. If you scale the house vector by 2, you get a house with 5.0 sqft and 6 bedrooms — the arrow gets twice as long in every direction.

Here’s both operations, stepped through element by element:

(2.53)+(1.01)\term{a}{\binom{2.5}{3}} + \term{b}{\binom{1.0}{1}}

Add corresponding entries — sqft to sqft, bedrooms to bedrooms.

(2.5+1.03+1)=(3.54)\term{a}{\binom{2.5 + 1.0}{3 + 1}} = \binom{3.5}{4}

Combined house: 3.5k sqft and 4 bedrooms.

2⋅(2.53)=(2⋅2.52⋅3)2 \cdot \term{a}{\binom{2.5}{3}} = \binom{2 \cdot 2.5}{2 \cdot 3}

Scalar multiplication: scale every element the same way.

(5.06)\binom{5.0}{6}

Twice as big in every direction — the arrow doubles in length.

Let’s see this in code.

import numpy as np

# Two house vectors
house1 = np.array([2.5, 3])  # 2500 sqft, 3 bedrooms
house2 = np.array([1.0, 1])  # 1000 sqft, 1 bedroom

# Vector addition
combined = house1 + house2
print(f"House 1: {house1} (sqft: {house1[0]}k, bedrooms: {house1[1]})")
print(f"House 2: {house2} (sqft: {house2[0]}k, bedrooms: {house2[1]})")
print(f"Combined: {combined} (sqft: {combined[0]}k, bedrooms: {combined[1]})")
print("Interpretation: Adding two house vectors gives a 'bigger' house with more of each feature.")
print()

# Scalar multiplication
scaled = 2 * house1
print(f"House 1 scaled by 2: {scaled} (sqft: {scaled[0]}k, bedrooms: {scaled[1]})")
print("Interpretation: Scaling doubles both features — the arrow gets twice as long.")

What this actually means: when you add vectors, you’re combining their features. When you scale a vector, you’re making all its features bigger or smaller by the same factor. This is the foundation of every linear model — a prediction is just a weighted sum of features, which is a linear combination of vectors.

Basis Vectors: The ‘Units’ Your Coordinates Are Measured In

Every coordinate pair (x, y) secretly means x * î + y * ĵ. The vectors î (said as ‘eye-hat’) and ĵ (‘jay-hat’) are the basis vectors — they’re the ‘rulers’ of your coordinate system.

Think of î and ĵ as the inch marks on your ruler. The coordinates tell you how many inches to go in each direction. In 2D, î is [1, 0] (one step to the right) and ĵ is [0, 1] (one step up).

So the vector (3, -2) is really 3*î + (-2)*ĵ — a linear combination of the basis vectors. You go 3 steps right and 2 steps down.

Let’s connect this back to our house dataset. The features (sqft, bedrooms, age) are each measured in their own ‘units’. The basis vectors are the ‘feature axes’ — one axis for sqft, one for bedrooms, one for age. Every house is a combination of these three axes.

Here’s the trick: the basis vectors are invisible by default. We assume they’re î and ĵ, but we can change them — that’s what a matrix does.

Let’s visualize this with a diagram.

import numpy as np
import matplotlib.pyplot as plt

# Define basis vectors
i_hat = np.array([1, 0])  # unit vector along x-axis
j_hat = np.array([0, 1])  # unit vector along y-axis

# A vector decomposed into components
v = np.array([3, -2])

plt.figure(figsize=(8, 6))
# Plot basis vectors
plt.quiver(0, 0, i_hat[0], i_hat[1], angles='xy', scale_units='xy', scale=1, color='red', label='î (x-axis)')
plt.quiver(0, 0, j_hat[0], j_hat[1], angles='xy', scale_units='xy', scale=1, color='green', label='ĵ (y-axis)')
# Plot the vector
plt.quiver(0, 0, v[0], v[1], angles='xy', scale_units='xy', scale=1, color='blue', label='v = (3, -2)')
# Plot the components
plt.quiver(0, 0, v[0], 0, angles='xy', scale_units='xy', scale=1, color='orange', alpha=0.5, label='x-component (3*î)')
plt.quiver(v[0], 0, 0, v[1], angles='xy', scale_units='xy', scale=1, color='purple', alpha=0.5, label='y-component (-2*ĵ)')

plt.xlim(-1, 4)
plt.ylim(-3, 2)
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend()
plt.title('A vector decomposed into its basis components')
plt.show()

The blue arrow is the vector (3, -2). The orange arrow is 3*î (3 steps right), and the purple arrow is -2*ĵ (2 steps down). Together, they add up to the blue arrow. This is the core idea: every vector is a combination of its basis vectors.

Matrices: A Machine That Transforms Vectors

A matrix is just a set of instructions: ‘Take the input vector’s coordinates and recombine them using these new basis vectors.’

Think of a matrix as a function — it takes a vector in and spits a new vector out. The columns of the matrix tell you where the original basis vectors (î and ĵ) land after the transformation.

For a 2x2 matrix [[a, b], [c, d]]:

  • The first column [a, c] is where î lands.
  • The second column [b, d] is where ĵ lands.

So when you multiply the matrix by a vector [x, y], you get x * (first column) + y * (second column). That’s a linear combination of the new basis vectors, weighted by the original coordinates.

Let’s work through a concrete example. Suppose we have a system of equations:

2x + y = 5
x - y = 1

The matrix form is:

[[2, 1], [1, -1]] @ [x, y] = [5, 1]

The solution is x = 2, y = 1. Let’s verify this in code and interpret the result.

import numpy as np

# Define the matrix and the vector
A = np.array([[2, 1],
              [1, -1]])
v = np.array([2, 1])  # the solution vector

# Compute A @ v
result = A @ v
print(f"Matrix A:")
print(A)
print(f"Vector v: {v}")
print(f"A @ v = {result}")
print()
print("Interpretation:")
print(f"  The first column of A is [2, 1] — that's where î lands.")
print(f"  The second column of A is [1, -1] — that's where ĵ lands.")
print(f"  v = (2, 1) means: 2 copies of the first column + 1 copy of the second column.")
print(f"  2 * [2, 1] + 1 * [1, -1] = [4 + 1, 2 - 1] = [5, 1] — which is the right-hand side!")

What this actually means: the matrix A transforms the vector v into a new vector [5, 1]. The columns of A are the new basis vectors. The original coordinates (2, 1) tell you how much of each new basis vector to use.

Matrix Multiplication as Composition: Doing Two Things at Once

Multiplying two matrices is like applying one transformation, then another. The order matters — and that’s where the power (and the confusion) lies.

Here’s the key property: (A @ B) @ v is the same as A @ (B @ v) — associativity holds. But A @ B is NOT the same as B @ A — order matters.

Think of it this way: if you rotate then shear, you get a different result than if you shear then rotate. Matrix multiplication captures the combined effect.

Let’s see this with two simple transformations: a rotation and a scaling.

import numpy as np

# Define two matrices
# Rotation by 90 degrees counterclockwise
R = np.array([[0, -1],
              [1, 0]])

# Scaling: double x, triple y
S = np.array([[2, 0],
              [0, 3]])

# Compute the compositions
RS = R @ S  # First scale, then rotate
SR = S @ R  # First rotate, then scale

print("Rotation matrix R:")
print(R)
print()
print("Scaling matrix S:")
print(S)
print()
print("R @ S (scale then rotate):")
print(RS)
print()
print("S @ R (rotate then scale):")
print(SR)
print()

# Test on a vector
v = np.array([1, 0])
print(f"Test vector v = {v}")
print(f"(R @ S) @ v = {RS @ v} — first scale [1,0] to [2,0], then rotate to [0,2]")
print(f"(S @ R) @ v = {SR @ v} — first rotate [1,0] to [0,1], then scale to [0,3]")
print()
print("Interpretation: The order of transformations changes the final result.")
print("  R @ S means: apply S first, then R.")
print("  S @ R means: apply R first, then S.")

This is the hardest part of matrix multiplication — keeping track of which matrix goes on which side. The rule is: the matrix on the right acts first. So R @ S means ‘apply S, then R’.

In data science, you might have one matrix that normalizes your features (scaling) and another that projects them onto new axes (like PCA). The order of operations changes the final data.

The Identity Matrix: The ‘Do Nothing’ Machine

The identity matrix is the matrix equivalent of multiplying by 1 — it leaves the vector unchanged. It’s the starting point for understanding inverses and eigenvalues.

The identity matrix I has 1s on the diagonal and 0s everywhere else. For a 2x2 identity:

I = [[1, 0],
     [0, 1]]

The identity matrix says: the new basis vectors are exactly the old basis vectors. Nothing changed.

Let’s verify this in code.

import numpy as np

# Create a 3x3 identity matrix
I = np.eye(3)
print("3x3 Identity matrix:")
print(I)
print()

# Create a random vector
v = np.array([2.5, 3, 15])
print(f"Vector v: {v}")
print(f"I @ v = {I @ v}")
print(f"Are they equal? {np.allclose(I @ v, v)}")
print()
print("Interpretation: The identity matrix leaves the vector unchanged.")
print("It's the 'do nothing' transformation.")

The identity is the baseline. When a matrix doesn’t change a vector’s direction (only its length), that vector is an eigenvector — and that’s the next article in this series.

Recap: What You Just Learned

Let’s summarize the key ideas:

  • A vector is a list of numbers (or an arrow) that you can add and scale. It’s how you represent a single data point.
  • Basis vectors are the ‘rulers’ — coordinates are just scalars on those rulers. Every vector is a combination of its basis vectors.
  • A matrix is a machine that transforms vectors by moving the basis vectors. The columns of the matrix tell you where the original basis vectors land.
  • Matrix multiplication is composing two transformations — order matters. The matrix on the right acts first.
  • The identity matrix is the ‘do nothing’ transformation. It’s the starting point for understanding inverses and eigenvalues.

You’re now ready for the next part of this series: Matrix Multiplication as Composition — the deep intuition behind why we multiply matrices the way we do.

Check Your Understanding

Test yourself with these questions, organized by Bloom’s taxonomy.

Remember: What are the three perspectives on a vector?

Understand: Explain in your own words why (3, -2) can be written as 3*î + (-2)*ĵ.

Apply: Given a 2x2 matrix [[2, 0], [0, 3]] and a vector [1, 1], compute the output and describe what the matrix does geometrically.

Analyze: Why does A @ B differ from B @ A? Give a geometric example.

Evaluate: Is it always true that (A @ B) @ v = A @ (B @ v)? Why or why not?

Create: Design a 2x2 matrix that, when applied to any vector, doubles the x-component and leaves the y-component unchanged. Write it in numpy and test it.

  • Matrix Multiplication as Composition (Part 2 of this series) — dives deeper into why we multiply matrices the way we do, with the same running example.
  • Eigenvectors and Eigenvalues: The Directions a Matrix Doesn’t Rotate (Part 3) — builds directly on the ‘matrix as transformation’ view from this article.
  • Principal Component Analysis (PCA) from Scratch — uses the change-of-basis intuition from this article to explain dimensionality reduction.

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans
  • Python Engineering Under review

    Sqlite For Data Science A Zero Setup Database For

    Think of SQLite not as a replacement for PostgreSQL or MySQL, but as a replacement for `fopen()`. That's the framing from the official SQLite documentation. You don't install a database server — you just open a file.

  • Python Engineering Under review

    A Data Science Glossary 100 Terms Explained In Pla

    Before we talk about models or metrics, we need to agree on what “data” actually looks like in Python. When you load a CSV file, you’re not staring at raw numbers — you’re staring at a carefully labeled structure.

  • Python Engineering Under review

    Dask for Out-of-Core Data: When Your Dataset Doesn't Fit in Memory

    You’ve just received a 20GB CSV file. Your laptop has 8GB of RAM. You fire up a Jupyter notebook and type `pd.read_csv('huge_file.csv')`. The kernel churns for a few seconds, then you see it: `MemoryError`.

  • Python Engineering Under review

    Sending Automated Emails And Reports From A Python

    You just spent three hours building a beautiful pandas report. You cleaned the data, created a summary table, made a chart, and exported everything to a CSV file.

Looking for something else?

Search every article by title, summary or topic.