Free sample
Chapter 1: The Geometry of Existence...--Every pattern recognition journey begins with a single, deceptively simple question: How do you know when two things are alike?Ask this to a child, and they might say, "They look the same." Ask an artist, and they might speak of color and form. Ask a poet, and they might talk about feeling. But ask a mathematician, and they will reach for a ruler. Not a physical ruler made of wood and metal, but an abstract ruler calibrated in the units of distance, angle, and similarity. This chapter is about building that ruler. It is about understanding that every piece of data—whether it is a customer's purchase history, a medical scan, a handwritten digit, or a sensor reading from a Mars rover—can be represented as a point in space. And the act of finding patterns is simply the act of measuring the geometric relationships between those points.If you internalize nothing else from this workbook, internalize this: Pattern recognition is geometry. The algorithms you will learn—k-nearest neighbors, support vector machines, neural networks, clustering—are all, at their core, different ways of measuring and exploiting the arrangement of points in high-dimensional space. Master the geometry, and the algorithms become intuitive. Ignore the geometry, and they remain a collection of opaque formulas.This first chapter lays the foundation for everything that follows. You will learn to see data as vectors. You will implement three essential distance metrics from scratch. You will build your first classifier—a brute-force nearest neighbor—using nothing but distances. And you will run an experiment that should genuinely shock you: an experiment demonstrating that in very high dimensions, all points become equally far apart, rendering naive distance measurements useless. That shock will motivate the dimensionality reduction techniques of Chapter 2 and the more sophisticated models throughout the rest of the book.Let us begin.1.1 Data as Vectors: The World in ℝᵈClose your eyes and imagine a spreadsheet. Rows are observations—customers, images, sensor readings, stock market days. Columns are features—age, income, pixel intensity, temperature, closing price. Each cell contains a number. That spreadsheet is your universe.Now imagine each row as an arrow pointing from the origin of a coordinate system to a specific location in space. That arrow is a vector. The number of columns is the dimensionality of that space. A dataset with four features lives in a four-dimensional space, denoted ℝ⁴. A dataset with 784 features (like a flattened 28×28 MNIST digit image) lives in ℝ⁷⁸⁴—a space so vast that human intuition cannot directly perceive it.But here is the secret: even though we cannot see in 784 dimensions, the same geometric principles that work in 2D and 3D—distance, angle, volume, projection—extend mathematically to any number of dimensions. The patterns we seek are geometric structures hidden in these high-dimensional spaces. Our job is to find them.Code Example 1.1: From Data Frame to Vector Let us make this concrete. We will use the classic Iris dataset—150 flowers, four measurements (sepal length, sepal width, petal length, petal width), three species. Each flower becomes a point in ℝ⁴.python Copy Downloadimport numpy as np
import pandas as pd from sklearn.datasets import load_iris import matplotlib.pyplot as plt
# Load the Iris dataset iris = load_iris() X = iris.data # Shape: (150, 4) — 150 vectors in 4D space y = iris.target # Species labels: 0, 1, 2
# Convert to Data Frame for inspection df = pd.Data Frame(X, columns=iris.feature_names) df['species'] = y print(df.head())
# Let's examine the first flower (first row) as a vector first_flower = X[0] print(f"\n First flower vector: {first_flower}") print(f"Vector norm (magnitude): {np.linalg.norm(first_flower):.3f}") print(f"Number of dimensions: {len(first_flower)}")The output shows a vector [5.1, 3.5, 1.4, 0.2]. This is not just a list of numbers—it is a directed line segment from the origin to the point (5.1, 3.5, 1.4, 0.2) in a four-dimensional coordinate system.Why Vectors?Representing data as vectors unlocks three powerful capabilities:Measuring similarity: The closer two vectors are in space, the more similar their corresponding observations.Finding directions: Certain directions in space may correspond to meaningful patterns (e.g., the direction that best separates different species).Linear algebra: We can use matrix operations to process thousands of vectors simultaneously, enabling the computational efficiency that makes modern machine learning possible.Before we can measure similarity, we need to answer a more fundamental question: What does "close" mean?1.2 Three Essential Distance Metrics Distance is not absolute. The best way to measure distance depends on the nature of your data, the types of patterns you expect, and the robustness you need. This section introduces the three most important distance metrics in pattern recognition. You will implement each one from scratch, first with explicit loops (to understand the mechanics) and then with vectorized Num Py (to appreciate the performance).1.2.1 Euclidean Distance: The Straight Line The Euclidean distance is what most people think of as "ordinary" distance. It is the length of the straight line between two points. In 2D, it is the familiar √[(x₁-x₂)² + (y₁-y₂)²]. In d dimensions, the formula generalizes naturally:deuclidean(a,b)=∑i=1d(ai−bi)2d_{\text{euclidean}}(\mathbf{a}, \mathbf{b}) = \sqrt{\sum_{i=1}^{d} (a_i - b_i)^2}deuclidean(a,b)=∑i=1d(ai−bi)2When to use it: Euclidean distance works best when features are continuous measurements on the same scale—temperatures, lengths, weights, concentrations. It assumes that the space is isotropic (the same in all directions) and that differences in each dimension are equally important.The sensitivity problem: Because Euclidean distance squares the differences, it is highly sensitive to outliers. One extreme value in a single dimension can dominate the entire distance calculation. If you are measuring distances between cities, a single erroneous coordinate (e.g., 10,000 km instead of 100 km) will corrupt the result.Code Example 1.2: Euclidean Distance with Loopspython Copy Downloaddef euclidean_loop(a, b): """Compute Euclidean distance using explicit loops.""" squared_sum = 0 for i in range(len(a)): diff = a[i] - b[i] squared_sum += diff * diff return np.sqrt(squared_sum)
# Test on two Iris flowers flower1 = X[0] # First flower flower2 = X[1] # Second flower dist = euclidean_loop(flower1, flower2) print(f"Euclidean distance between flower 0 and flower 1: {dist:.4f}")This loop-based implementation is instructive but slow. For large datasets, we need vectorization.Vectorized Version:python Copy Downloaddef euclidean_vectorized(a, b): """Compute Euclidean distance using vectorized Num Py.""" return np.sqrt(np.sum((a - b) ** 2))
# Even better: pairwise distance matrix for many points def pairwise_euclidean(X): """Compute all pairwise Euclidean distances using broadcasting.""" # X shape: (N, d) # Compute squared norms of each row squared_norms = np.sum(X ** 2, axis=1).reshape(-1, 1) # Use identity: ||a-b||^2 = ||a||^2 + ||b||^2 - 2 a·b distances_sq = squared_norms + squared_norms.T - 2 * np.dot(X, X.T) # Ensure numerical stability (diagonals should be zero) np.fill_diagonal(distances_sq, 0) return np.sqrt(np.maximum(distances_sq, 0))
# Compute all pairwise distances in Iris (150 points) dist_matrix = pairwise_euclidean(X) print(f"Distance matrix shape: {dist_matrix.shape}") print(f"Distance between flower 0 and flower 1: {dist_matrix[0, 1]:.4f}")The broadcasting trick—using ||a-b||² = ||a||² + ||b||² - 2a·b—turns an O(N²d) triple-loop into an O(N² + Nd) matrix multiplication, a massive speedup for large N.1.2.2…
This is the end of the free sample. Get the eBook to keep going. Buy now
About this book
Details
- Author
- Leroy Justina
- Publisher
- SamEnrico
- Language
- English
- Genre
- Non-Fiction, Self-Help / Interactive
- Released
- 2026-06-06
- Pages (approx.)
- 156
- Available as
- eBook, Audiobook
Read better in the ZLOADR app
Your eBooks on your phone or tablet. Sign in with your SamEnrico account and start reading.
More by Leroy Justina
Gacy's Jury SelectionLeroy Justina$11.99
Meth Paranoia Recovery GuideLeroy Justina$11.99
TM And TelomeresLeroy Justina$11.99
FCPA State Owned Enterprise CasesLeroy Justina$11.99
LTC Insurance For Attorneys GuideLeroy Justina$11.99
The Protestant Pulpit FireLeroy Justina$11.99
Sexual Addiction and BipolarLeroy Justina$11.99
Bereavement at Work GuideLeroy Justina$11.99
The Shadow of the White Rose: The Unseen Hand Behind the Fall of a DictatorLeroy Justina$11.99
The Silent Coup: How a Teenage Queen Outmaneuvered EuropeLeroy Justina$11.99
Frozen in Time: The Last Love of the Woolly MammothsLeroy Justina$11.99
The Dancer's Guide to GiddhaLeroy Justina$11.99You may also like
Hong Kong Handover 1997Dunn Johnnie$11.99
Zumba For Postnatal Recovery CourseNeal Christian$11.99
Zumba for BeginnersLadner Nikia$11.99
YouTube Comment Mining GuideHumes Pandora$12.99
Worry Box MeditationCarlin Rudy$11.99
Workplace Stress MeditationNguyen Lynn$11.99
Workplace Stress and Sleep RepairHawley Ivory$11.99
Workplace Perfectionism CureDelaney Jeffry$11.99
Workplace Injustice Anger GuideWallen Isabelle$11.99
Work Addiction and Burnout LinkGreenwood Ester$11.99
Women in Yoga and WellnessBeattie Galina$11.99
Women in Stand Up ComedyChun Evangeline$11.99