{ "cells": [ { "cell_type": "markdown", "id": "65d980ab", "metadata": {}, "source": [ "# πŸš€ The Easy & Detailed NumPy Guide: From Zero to Machine Learning\n", "> **A Comprehensive, Visual, and Intuitive Reference Guide to Vectorized Computing**\n", "> \n", "> *Target Audience:* Beginners seeking crystal-clear clarity, Data Scientists looking for a thorough reference, and ML practitioners building fast algorithms without getting bogged down in dry mathematical proofs.\n", "\n", "---\n", "\n", "### 🌟 How to Use This Notebook\n", "1. **Detailed Explanations in Plain English:** Every concept is explained step-by-step with clear real-world intuition, analogies, and \"under-the-hood\" mechanicsβ€”easy to read, not deeper or mathematically dense.\n", "2. **Visual Mental Models:** Visual ASCII diagrams illustrate memory layouts, multidimensional slicing grids, axes directions, and broadcasting rules.\n", "3. **Pre-Executed & Verified:** Every code cell is pre-executed with real outputs so you can read this like an illustrated technical handbook or run each cell interactively.\n", "4. **Smooth Navigation:** Use the **Table of Contents** below or each chapter's `[⬆️ Back to Table of Contents]` link to jump directly to any section.\n", "\n", "---\n", "\n", "\n", "## πŸ“‘ Table of Contents\n", "\n", "| Part | Chapter | Key Topics Covered |\n", "| :---: | :--- | :--- |\n", "| **I** | [1. Why NumPy is Fast: The Core Mental Model](#ch1) | Python Lists vs ndarrays, Contiguous RAM, CPU Cache & SIMD, Vectorization |\n", "| **I** | [2. Creating NumPy Arrays](#ch2) | `np.array`, `zeros`, `ones`, `full`, `arange` vs `linspace`, identity & diagonals |\n", "| **I** | [3. Array Anatomy & Attributes](#ch3) | `shape`, `ndim`, `dtype`, `itemsize`, `nbytes`, `strides`, and memory flags |\n", "| **I** | [4. Modern Random Number Generation](#ch4) | `default_rng()`, Uniform, Normal (Gaussian), Integers, Choice, Shuffling |\n", "| **II** | [5. Indexing, Slicing & Striding](#ch5) | 1D & 2D slicing grids, negative indexing, step stride, ellipsis `...`, `newaxis` |\n", "| **II** | [6. Views vs Copies: Memory Mechanics](#ch6) | Shared memory buffers, `arr.base`, accidental mutations, `.copy()` best practices |\n", "| **II** | [7. Advanced Indexing & Filtering](#ch7) | Boolean masking, Bitwise operators (`&`, `\\|`, `~`), `np.where`, Fancy indexing |\n", "| **II** | [8. Reshaping & Structural Transforms](#ch8) | `reshape(-1)`, `flatten()` vs `ravel()`, Transpose `.T`, `squeeze`, `expand_dims` |\n", "| **III** | [9. Combining, Stacking & Splitting Arrays](#ch9) | `concatenate`, `vstack`, `hstack`, `stack`, `split`, `tile` vs `repeat` |\n", "| **III** | [10. Universal Functions (ufuncs)](#ch10) | Vectorized math, trigonometry, `reduce`, `accumulate`, `outer` operations |\n", "| **III** | [11. Broadcasting Demystified: The 3 Rules](#ch11) | Shape compatibility rules, dimension stretching, feature normalization |\n", "| **III** | [12. Aggregations & The Axis Model](#ch12) | Mental model for `axis=0` vs `axis=1`, `keepdims=True`, `nan`-safe functions |\n", "| **IV** | [13. Sorting, Searching & Ranking](#ch13) | `sort` vs `argsort`, fast $O(N)$ top-K selection with `argpartition`, `unique` |\n", "| **IV** | [14. Linear Algebra Made Intuitive](#ch14) | `@` vs `*`, Dot products, Matrix inverses, Solving $Ax=b$, Vector norms |\n", "| **IV** | [15. Practical Machine Learning Vectorization](#ch15) | Pairwise Euclidean distance, Stable Softmax, One-Hot Encoding, MSE Loss |\n", "| **IV** | [16. Performance Optimization & Anti-Patterns](#ch16) | Preallocation vs `np.append` anti-pattern, C-order vs Fortran cache lines, in-place math |\n", "| **V** | [Quick Reference Cheat Sheet](#summary) | High-frequency function reference table and companion practice exercises |" ] }, { "cell_type": "markdown", "id": "9f272689", "metadata": {}, "source": [ "\n", "---\n", "# Part I: Foundations & Memory Architecture\n", "\n", "## 1. Why NumPy is Fast: The Core Mental Model\n", "\n", "Standard Python is dynamic, flexible, and beginner-friendly, but it is notoriously slow for numerical computation.\n", "If you attempt to do scientific data processing, image manipulation, or machine learning using standard Python lists and `for` loops, your code will run **50x to 100x slower** than compiled languages like C or Fortran.\n", "\n", "**NumPy (Numerical Python)** solves this performance gap. It provides a specialized, high-performance data structure called the **`ndarray`** (N-dimensional array).\n", "\n", "---\n", "\n", "### 1.1 Python Lists vs. NumPy ndarrays: The Memory Layout\n", "To understand why NumPy is fundamentally faster, we have to look at how computer RAM stores data for both structures:\n", "\n", "```\n", "[Standard Python List]: Array of Pointers to Heap Objects\n", "List Container ---> [ Pointer 0 ] ---> PyObject (type=int, refcount=1, value=42)\n", " [ Pointer 1 ] ---> PyObject (type=int, refcount=1, value=18)\n", " [ Pointer 2 ] ---> PyObject (type=int, refcount=1, value=99)\n", " * Values are scattered randomly across system RAM -> High CPU Cache Misses!\n", " * Type-checking and dynamic dispatch happen on EVERY single loop iteration.\n", " * Enormous memory overhead (approx 28+ bytes per simple integer!).\n", "\n", "[NumPy ndarray]: One Contiguous C-Style Memory Buffer\n", "Array Header ---> [ 42 | 18 | 99 | 74 | 12 | ... ] (raw bytes packed side-by-side)\n", " * Sequential in RAM -> Hardware CPU L1/L2 cache pre-fetching loads data ahead of time.\n", " * Fixed, uniform data type -> Direct pointer arithmetic: Memory Address = Base + Index * ItemSize.\n", " * Bypasses the Python interpreter during loops -> Dispatches directly to compiled SIMD CPU vector instructions.\n", "```\n", "\n", "### 1.2 What is Vectorization?\n", "In standard Python, to add two lists element-by-element, you must write a `for` loop that unpacks each element, checks its type, computes the addition in Python bytecode, and packs the result into a new Python object.\n", "In NumPy, **Vectorization** allows you to express batch operations with simple syntax like `c = a + b`.\n", "Under the hood, NumPy delegates the entire loop down to pre-compiled C loops that use **SIMD (Single Instruction, Multiple Data)** instructions on your CPU processor. A single CPU instruction adds 4, 8, or 16 numbers simultaneously!" ] }, { "cell_type": "code", "execution_count": 1, "id": "35a6f8f9", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.408415Z", "iopub.status.busy": "2026-10-03T05:06:49.408129Z", "iopub.status.idle": "2026-10-03T05:06:49.502707Z", "shell.execute_reply": "2026-10-03T05:06:49.501141Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "NumPy Version: 2.5.3\n" ] } ], "source": [ "import numpy as np\n", "import sys\n", "import time\n", "\n", "print(f\"NumPy Version: {np.__version__}\")" ] }, { "cell_type": "markdown", "id": "76361984", "metadata": {}, "source": [ "### 1.3 Memory Footprint Benchmark: List vs ndarray\n", "Let's measure the actual memory consumed by a Python list of 10,000 integers versus a NumPy array of 10,000 integers.\n", "Notice how much leaner and compact NumPy is in RAM:" ] }, { "cell_type": "code", "execution_count": 2, "id": "880b842c", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.504801Z", "iopub.status.busy": "2026-10-03T05:06:49.504627Z", "iopub.status.idle": "2026-10-03T05:06:49.512882Z", "shell.execute_reply": "2026-10-03T05:06:49.509750Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "πŸ“¦ Python List Memory: 360,056 bytes\n", "⚑ NumPy Array Memory: 160,112 bytes\n", "πŸŽ‰ NumPy is 2.2x more memory-compact!\n" ] } ], "source": [ "# Create 10,000 integers in Python list vs NumPy array\n", "n_items = 10_000\n", "py_list = list(range(n_items))\n", "np_arr = np.arange(n_items, dtype=np.int64)\n", "\n", "# Memory of the list container + memory of each individual integer PyObject\n", "py_list_bytes = sys.getsizeof(py_list) + sum(sys.getsizeof(x) for x in py_list)\n", "# Memory of the NumPy array buffer + array header\n", "np_arr_bytes = np_arr.nbytes + sys.getsizeof(np_arr)\n", "\n", "print(f\"πŸ“¦ Python List Memory: {py_list_bytes:>8,} bytes\")\n", "print(f\"⚑ NumPy Array Memory: {np_arr_bytes:>8,} bytes\")\n", "print(f\"πŸŽ‰ NumPy is {py_list_bytes / np_arr_bytes:.1f}x more memory-compact!\")" ] }, { "cell_type": "markdown", "id": "69e038f0", "metadata": {}, "source": [ "### 1.4 Execution Speed Benchmark: Vectorization vs Python Loop\n", "Now let's compute element-wise addition on two arrays of **5,000,000 numbers**.\n", "Notice the massive speedup when running NumPy's compiled C code versus interpreted Python loops:" ] }, { "cell_type": "code", "execution_count": 3, "id": "3e659d77", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.514965Z", "iopub.status.busy": "2026-10-03T05:06:49.514813Z", "iopub.status.idle": "2026-10-03T05:06:49.748855Z", "shell.execute_reply": "2026-10-03T05:06:49.748488Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "🐒 Python Loop (extrapolated 5M): 0.2575 seconds\n", "πŸš€ NumPy Vectorized (5M): 0.0188 seconds\n", "⚑ Speedup: 13.7x faster!\n" ] } ], "source": [ "N = 5_000_000\n", "list_a = list(range(N))\n", "list_b = list(range(N))\n", "arr_a = np.arange(N, dtype=np.float64)\n", "arr_b = np.arange(N, dtype=np.float64)\n", "\n", "# 1. Pure Python Loop (benchmarked on 500k and scaled for timing responsiveness)\n", "t0 = time.perf_counter()\n", "_ = [a + b for a, b in zip(list_a[:500_000], list_b[:500_000])]\n", "t1 = time.perf_counter()\n", "py_time = (t1 - t0) * 10 # Extrapolated to 5M\n", "\n", "# 2. NumPy Vectorized C-Speed Addition\n", "t0 = time.perf_counter()\n", "_ = arr_a + arr_b\n", "t1 = time.perf_counter()\n", "np_time = t1 - t0\n", "\n", "print(f\"🐒 Python Loop (extrapolated 5M): {py_time:.4f} seconds\")\n", "print(f\"πŸš€ NumPy Vectorized (5M): {np_time:.4f} seconds\")\n", "print(f\"⚑ Speedup: {py_time / np_time:.1f}x faster!\")" ] }, { "cell_type": "markdown", "id": "fea4dabf", "metadata": {}, "source": [ "> πŸ’‘ **Key Takeaway:**\n", "> Never write `for` loops in Python to do math on arrays. NumPy's vectorization executes directly on CPU vector hardware at native C speed!\n", ">\n", "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "0ad045bc", "metadata": {}, "source": [ "\n", "---\n", "## 2. Creating NumPy Arrays\n", "\n", "NumPy provides built-in constructors to create arrays of any dimension, shape, and data type without writing loops.\n", "\n", "### 2.1 From Python Sequences (`np.array`)\n", "You can convert any standard Python list or nested list into an `ndarray`.\n", "Specifying the `dtype` explicitly prevents unintended automatic type conversions." ] }, { "cell_type": "code", "execution_count": 4, "id": "ea218f10", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.750195Z", "iopub.status.busy": "2026-10-03T05:06:49.750080Z", "iopub.status.idle": "2026-10-03T05:06:49.754058Z", "shell.execute_reply": "2026-10-03T05:06:49.753714Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1D Array (float32): [10. 20. 30. 40.]\n", "\n", "2D Matrix (2x3):\n", " [[1 2 3]\n", " [4 5 6]]\n" ] } ], "source": [ "# 1D Array (Vector) with explicit 32-bit float\n", "a_1d = np.array([10, 20, 30, 40], dtype=np.float32)\n", "\n", "# 2D Matrix (2 rows x 3 columns)\n", "a_2d = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)\n", "\n", "print(\"1D Array (float32):\", a_1d)\n", "print(\"\\n2D Matrix (2x3):\\n\", a_2d)" ] }, { "cell_type": "markdown", "id": "c5fd8705", "metadata": {}, "source": [ "### 2.2 Constant Initializers: Zeros, Ones, Full, Empty\n", "These initializers pre-allocate memory buffers before running computations (e.g. allocating arrays for model weights, image masks, or accumulators):\n", "- **`np.zeros(shape)`**: Fills all elements with `0`.\n", "- **`np.ones(shape)`**: Fills all elements with `1`.\n", "- **`np.full(shape, fill_value)`**: Fills all elements with a chosen constant value.\n", "- **`np.empty(shape)`**: Allocates memory without clearing it (fastest, but contains whatever random junk bytes were in RAM!)." ] }, { "cell_type": "code", "execution_count": 5, "id": "d1fdbd3a", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.755347Z", "iopub.status.busy": "2026-10-03T05:06:49.755239Z", "iopub.status.idle": "2026-10-03T05:06:49.758178Z", "shell.execute_reply": "2026-10-03T05:06:49.757887Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Zeros (2x4):\n", " [[0. 0. 0. 0.]\n", " [0. 0. 0. 0.]]\n", "\n", "Ones (2x3):\n", " [[1 1 1]\n", " [1 1 1]]\n", "\n", "Full with 99.0 (2x3):\n", " [[99. 99. 99.]\n", " [99. 99. 99.]]\n" ] } ], "source": [ "# Zeros array of shape (2, 4)\n", "zeros = np.zeros(shape=(2, 4), dtype=np.float64)\n", "\n", "# Ones array of shape (2, 3)\n", "ones = np.ones(shape=(2, 3), dtype=np.int16)\n", "\n", "# Full array with a custom scalar (e.g., 99.0)\n", "filled = np.full(shape=(2, 3), fill_value=99.0)\n", "\n", "# Empty array (uninitialized buffer)\n", "empty = np.empty(shape=(2, 2))\n", "\n", "print(\"Zeros (2x4):\\n\", zeros)\n", "print(\"\\nOnes (2x3):\\n\", ones)\n", "print(\"\\nFull with 99.0 (2x3):\\n\", filled)" ] }, { "cell_type": "markdown", "id": "bdc417c4", "metadata": {}, "source": [ "### 2.3 Like-Constructors: Matching Shape & Dtype\n", "When you already have an existing array and want another array with the identical shape and data type without manually typing out the dimensions:\n", "- `np.zeros_like(template)`\n", "- `np.ones_like(template)`\n", "- `np.full_like(template, fill_value)`" ] }, { "cell_type": "code", "execution_count": 6, "id": "cb032ed1", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.759413Z", "iopub.status.busy": "2026-10-03T05:06:49.759313Z", "iopub.status.idle": "2026-10-03T05:06:49.761871Z", "shell.execute_reply": "2026-10-03T05:06:49.761604Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Template shape: (2, 3) dtype: float64\n", "\n", "Zeros like template:\n", " [[0. 0. 0.]\n", " [0. 0. 0.]]\n", "\n", "Full like template:\n", " [[-1. -1. -1.]\n", " [-1. -1. -1.]]\n" ] } ], "source": [ "template = np.array([[1.5, 2.5, 3.5], [4.5, 5.5, 6.5]])\n", "\n", "zeros_like = np.zeros_like(template)\n", "full_like = np.full_like(template, fill_value=-1.0)\n", "\n", "print(\"Template shape:\", template.shape, \"dtype:\", template.dtype)\n", "print(\"\\nZeros like template:\\n\", zeros_like)\n", "print(\"\\nFull like template:\\n\", full_like)" ] }, { "cell_type": "markdown", "id": "257731d6", "metadata": {}, "source": [ "### 2.4 Numerical Ranges: `arange` vs `linspace`\n", "This is one of the most critical distinctions in scientific Python:\n", "\n", "| Function | Signature | Use When... | End-point Included? |\n", "| :--- | :--- | :--- | :---: |\n", "| `np.arange(start, stop, step)` | Specify **step size** | You care about the step interval between elements | ❌ No (stop is exclusive) |\n", "| `np.linspace(start, stop, num)` | Specify **number of points** | You care about exact sample count | βœ… Yes (stop is inclusive) |\n", "\n", "> ⚠️ **Pro-Tip on Floating Point:**\n", "> Avoid using `np.arange` with floating-point step sizes like `np.arange(0, 1, 0.1)` because floating-point rounding errors can result in unexpected array lengths. Always prefer `np.linspace(0, 1, 11)` for float ranges!" ] }, { "cell_type": "code", "execution_count": 7, "id": "9e3915c4", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.763010Z", "iopub.status.busy": "2026-10-03T05:06:49.762910Z", "iopub.status.idle": "2026-10-03T05:06:49.765675Z", "shell.execute_reply": "2026-10-03T05:06:49.765416Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "np.arange(0, 10, 2): [0 2 4 6 8]\n", "np.linspace(0, 1, num=5): [0. 0.25 0.5 0.75 1. ]\n", "np.logspace(1, 4, num=4): [ 10. 100. 1000. 10000.]\n" ] } ], "source": [ "# arange: step is 2 (stop is exclusive)\n", "r_arange = np.arange(start=0, stop=10, step=2)\n", "\n", "# linspace: exactly 5 points evenly spaced between 0 and 1 (inclusive)\n", "r_linspace = np.linspace(start=0.0, stop=1.0, num=5)\n", "\n", "# logspace: 4 points logarithmically spaced from 10^1 to 10^4\n", "r_logspace = np.logspace(start=1, stop=4, num=4, base=10.0)\n", "\n", "print(\"np.arange(0, 10, 2): \", r_arange)\n", "print(\"np.linspace(0, 1, num=5):\", r_linspace)\n", "print(\"np.logspace(1, 4, num=4):\", r_logspace)" ] }, { "cell_type": "markdown", "id": "8ebcdcca", "metadata": {}, "source": [ "### 2.5 Identity & Diagonal Matrices\n", "Essential for linear transformations, baseline weights, and one-hot encoding:\n", "- **`np.eye(N)`**: Creates an $N \\times N$ identity matrix with 1s on the main diagonal and 0s elsewhere.\n", "- **`np.diag(v)`**: If $v$ is a 1D vector, creates a 2D matrix with $v$ along the diagonal. If $v$ is a 2D matrix, extracts the diagonal elements." ] }, { "cell_type": "code", "execution_count": 8, "id": "849cc576", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.766723Z", "iopub.status.busy": "2026-10-03T05:06:49.766631Z", "iopub.status.idle": "2026-10-03T05:06:49.769209Z", "shell.execute_reply": "2026-10-03T05:06:49.768972Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Identity Matrix (3x3):\n", " [[1. 0. 0.]\n", " [0. 1. 0.]\n", " [0. 0. 1.]]\n", "\n", "Diagonal Matrix:\n", " [[10 0 0]\n", " [ 0 20 0]\n", " [ 0 0 30]]\n", "\n", "Upper Triangular Matrix:\n", " [[1 1 1]\n", " [0 1 1]\n", " [0 0 1]]\n" ] } ], "source": [ "# 3x3 Identity matrix\n", "identity = np.eye(3)\n", "\n", "# Construct a diagonal matrix from a list of diagonal values\n", "diag_matrix = np.diag([10, 20, 30])\n", "\n", "# Upper and Lower triangular matrices\n", "mat = np.ones((3, 3), dtype=int)\n", "upper = np.triu(mat)\n", "lower = np.tril(mat)\n", "\n", "print(\"Identity Matrix (3x3):\\n\", identity)\n", "print(\"\\nDiagonal Matrix:\\n\", diag_matrix)\n", "print(\"\\nUpper Triangular Matrix:\\n\", upper)" ] }, { "cell_type": "markdown", "id": "c33075fe", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "545aaedc", "metadata": {}, "source": [ "\n", "---\n", "## 3. Array Anatomy, Attributes & Memory\n", "\n", "Every NumPy array consists of two components:\n", "1. **The Data Buffer**: Raw bytes stored in contiguous system RAM.\n", "2. **The Array Header (Metadata)**: A lightweight Python object storing structural descriptors: `shape`, `ndim`, `dtype`, `itemsize`, `nbytes`, and `strides`.\n", "\n", "```\n", " ARRAY HEADER (Metadata in Python)\n", " shape : (3, 4) -> 3 rows, 4 columns\n", " ndim : 2 -> 2 dimensions\n", " dtype : int32 -> 4 bytes per integer\n", " itemsize: 4 -> size of 1 item\n", " nbytes : 48 -> total bytes (12 * 4)\n", " strides : (16, 4) -> jump 16 bytes for next row, 4 for next col\n", " |\n", " v\n", " DATA BUFFER (Raw contiguous bytes in RAM)\n", " [ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 ]\n", "```" ] }, { "cell_type": "code", "execution_count": 9, "id": "7aae1e69", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.770397Z", "iopub.status.busy": "2026-10-03T05:06:49.770302Z", "iopub.status.idle": "2026-10-03T05:06:49.772836Z", "shell.execute_reply": "2026-10-03T05:06:49.772600Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "--- Array Structural Attributes ---\n", "Array:\n", " [[ 0 1 2 3]\n", " [ 4 5 6 7]\n", " [ 8 9 10 11]]\n", "ndim (dimensions): 2\n", "shape (rows, cols): (3, 4)\n", "size (total elements): 12\n", "dtype (data type): int32\n", "itemsize (bytes/item): 4 bytes\n", "nbytes (total memory): 48 bytes (12 * 4)\n" ] } ], "source": [ "# Create a 3x4 array of 32-bit integers\n", "arr = np.arange(12, dtype=np.int32).reshape(3, 4)\n", "\n", "print(\"--- Array Structural Attributes ---\")\n", "print(\"Array:\\n\", arr)\n", "print(f\"ndim (dimensions): {arr.ndim}\")\n", "print(f\"shape (rows, cols): {arr.shape}\")\n", "print(f\"size (total elements): {arr.size}\")\n", "print(f\"dtype (data type): {arr.dtype}\")\n", "print(f\"itemsize (bytes/item): {arr.itemsize} bytes\")\n", "print(f\"nbytes (total memory): {arr.nbytes} bytes ({arr.size} * {arr.itemsize})\")" ] }, { "cell_type": "markdown", "id": "1b147b95", "metadata": {}, "source": [ "### 3.2 Demystifying `strides`\n", "**Strides** is one of NumPy's most brilliant features. It tells the CPU how many bytes it must step forward in RAM to advance by 1 index in each dimension:\n", "- To advance to the next column: step **4 bytes** (the size of one 32-bit integer).\n", "- To advance to the next row: step 4 columns $\\times$ 4 bytes = **16 bytes**.\n", "\n", "```\n", "Row 0: [ 0 (byte 0) | 1 (byte 4) | 2 (byte 8) | 3 (byte 12) ]\n", "Row 1: [ 4 (byte 16) | 5 (byte 20) | 6 (byte 24) | 7 (byte 28) ]\n", "Row 2: [ 8 (byte 32) | 9 (byte 36) | 10 (byte 40) | 11 (byte 44) ]\n", "```\n", "\n", "> 🧠 **Why Strides Matter (Under the Hood):**\n", "> When you transpose an array (`arr.T`), NumPy **does not copy a single byte of data**!\n", "> Instead, it simply swaps the strides tuple from `(16, 4)` to `(4, 16)`. The CPU navigates the exact same memory buffer in reverse order. This is why transposing a 10 GB matrix in NumPy executes in $0.000001$ seconds!" ] }, { "cell_type": "code", "execution_count": 10, "id": "713cc020", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.773934Z", "iopub.status.busy": "2026-10-03T05:06:49.773849Z", "iopub.status.idle": "2026-10-03T05:06:49.775911Z", "shell.execute_reply": "2026-10-03T05:06:49.775669Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Strides tuple (row_bytes, col_bytes): (16, 4)\n", "\n", "Memory Flags:\n", "C-Contiguous (Row-major): True\n", "Fortran (Column-major): False\n", "Owns its memory buffer: False\n" ] } ], "source": [ "print(\"Strides tuple (row_bytes, col_bytes):\", arr.strides)\n", "\n", "# Inspect memory flags: is it C-contiguous? Does it own its memory?\n", "print(\"\\nMemory Flags:\")\n", "print(\"C-Contiguous (Row-major):\", arr.flags['C_CONTIGUOUS'])\n", "print(\"Fortran (Column-major): \", arr.flags['F_CONTIGUOUS'])\n", "print(\"Owns its memory buffer: \", arr.flags['OWNDATA'])" ] }, { "cell_type": "markdown", "id": "5e97736f", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "f73659f7", "metadata": {}, "source": [ "\n", "---\n", "## 4. Modern Random Number Generation (`np.random.default_rng`)\n", "\n", "In older NumPy tutorials, you will see `np.random.seed(42)` and `np.random.rand()`.\n", "**NumPy 1.17+ officially deprecated that legacy API.**\n", "The modern standard is the **Generator API** initialized via `np.random.default_rng()`, which uses the high-performance **PCG64** pseudo-random number generator algorithm. It is faster, statistically superior, and thread-safe.\n", "\n", "### 4.1 Common Distributions\n", "- **`rng.random(size)`**: Uniform floats in $[0.0, 1.0)$.\n", "- **`rng.integers(low, high, size)`**: Uniform integers in $[\\text{low}, \\text{high})$.\n", "- **`rng.standard_normal(size)`**: Standard Normal (Gaussian) distribution ($\\mu=0, \\sigma=1$).\n", "- **`rng.normal(loc, scale, size)`**: Gaussian with custom mean (`loc`) and standard deviation (`scale`)." ] }, { "cell_type": "code", "execution_count": 11, "id": "f5941f6c", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.776977Z", "iopub.status.busy": "2026-10-03T05:06:49.776893Z", "iopub.status.idle": "2026-10-03T05:06:49.809128Z", "shell.execute_reply": "2026-10-03T05:06:49.808850Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Floats [0, 1):\n", " [[0.774 0.439 0.859]\n", " [0.697 0.094 0.976]]\n", "\n", "Integers [1, 100):\n", " [[73 76 72]\n", " [78 51 13]]\n", "\n", "Standard Normal (Gaussian):\n", " [[-0.853 0.879 0.778]\n", " [ 0.066 1.127 0.468]]\n", "\n", "Normal(mu=10, sigma=2.5):\n", " [ 7.85 10.92 7.6 12.2 ]\n" ] } ], "source": [ "# Initialize modern generator with a fixed seed for reproducibility\n", "rng = np.random.default_rng(seed=42)\n", "\n", "# 1. Random floats in [0.0, 1.0)\n", "floats = rng.random(size=(2, 3))\n", "\n", "# 2. Random integers between 1 and 100\n", "ints = rng.integers(low=1, high=100, size=(2, 3))\n", "\n", "# 3. Standard Normal distribution (mean=0, std=1)\n", "std_norm = rng.standard_normal(size=(2, 3))\n", "\n", "# 4. Custom Normal distribution (mean=10.0, std=2.5)\n", "custom_norm = rng.normal(loc=10.0, scale=2.5, size=4)\n", "\n", "print(\"Floats [0, 1):\\n\", floats.round(3))\n", "print(\"\\nIntegers [1, 100):\\n\", ints)\n", "print(\"\\nStandard Normal (Gaussian):\\n\", std_norm.round(3))\n", "print(\"\\nNormal(mu=10, sigma=2.5):\\n\", custom_norm.round(2))" ] }, { "cell_type": "markdown", "id": "a8e7d909", "metadata": {}, "source": [ "### 4.2 Shuffling and Random Sampling\n", "Used constantly in machine learning for creating train/validation splits, mini-batch shuffling, and bootstrapping:\n", "- **`rng.choice(a, size, replace, p)`**: Sample elements with or without replacement.\n", "- **`rng.shuffle(arr)`**: Shuffles the array **in-place** along the first axis.\n", "- **`rng.permutation(arr)`**: Returns a **new shuffled copy** without mutating the original." ] }, { "cell_type": "code", "execution_count": 12, "id": "7ef106a8", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.810402Z", "iopub.status.busy": "2026-10-03T05:06:49.810273Z", "iopub.status.idle": "2026-10-03T05:06:49.813363Z", "shell.execute_reply": "2026-10-03T05:06:49.813116Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample with replacement: ['Banana' 'Date' 'Apple']\n", "Sample without replacement: ['Banana' 'Date' 'Cherry']\n", "Shuffled copy: ['Cherry' 'Banana' 'Apple' 'Date' 'Elderberry']\n", "Original unchanged: ['Apple' 'Banana' 'Cherry' 'Date' 'Elderberry']\n" ] } ], "source": [ "items = np.array(['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'])\n", "\n", "# Randomly sample 3 items with replacement\n", "sample_replace = rng.choice(items, size=3, replace=True)\n", "\n", "# Randomly sample 3 items without replacement (all unique)\n", "sample_unique = rng.choice(items, size=3, replace=False)\n", "\n", "# Random permutation (creates a shuffled copy)\n", "shuffled_items = rng.permutation(items)\n", "\n", "print(\"Sample with replacement: \", sample_replace)\n", "print(\"Sample without replacement:\", sample_unique)\n", "print(\"Shuffled copy: \", shuffled_items)\n", "print(\"Original unchanged: \", items)" ] }, { "cell_type": "markdown", "id": "4adf75fb", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "4b9628da", "metadata": {}, "source": [ "\n", "---\n", "# Part II: Slicing, Indexing & Views\n", "\n", "## 5. Indexing, Slicing & Striding\n", "\n", "Indexing allows you to extract individual elements, sub-matrices, or multidimensional slices.\n", "NumPy slicing follows standard Python syntax: `start:stop:step`, where:\n", "- `start` is inclusive (default is 0).\n", "- `stop` is exclusive (default is end).\n", "- `step` is the stride interval (can be negative to reverse!).\n", "\n", "### 5.1 1D Array Slicing" ] }, { "cell_type": "code", "execution_count": 13, "id": "e3656981", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.814532Z", "iopub.status.busy": "2026-10-03T05:06:49.814418Z", "iopub.status.idle": "2026-10-03T05:06:49.816651Z", "shell.execute_reply": "2026-10-03T05:06:49.816416Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original: [10 20 30 40 50 60 70 80]\n", "Slice [2:6]: [30 40 50 60]\n", "Every 2nd item [::2]: [10 30 50 70]\n", "Reverse array [::-1]: [80 70 60 50 40 30 20 10]\n" ] } ], "source": [ "a = np.array([10, 20, 30, 40, 50, 60, 70, 80])\n", "\n", "print(\"Original: \", a)\n", "print(\"Slice [2:6]: \", a[2:6]) # Elements from index 2 to 5\n", "print(\"Every 2nd item [::2]: \", a[::2]) # Stride of 2\n", "print(\"Reverse array [::-1]: \", a[::-1]) # Negative step reverses array!" ] }, { "cell_type": "markdown", "id": "8d566423", "metadata": {}, "source": [ "### 5.2 2D Matrix Indexing & Slicing: `[row_slice, col_slice]`\n", "In standard Python lists, 2D access requires chained brackets `list_2d[row][col]`.\n", "In NumPy, you use a single pair of brackets with a comma separating dimensions: **`matrix[row_slice, col_slice]`**.\n", "\n", "```\n", " Matrix shape (4, 5)\n", " Col 0 Col 1 Col 2 Col 3 Col 4\n", " +-------+-------+-------+-------+-------+\n", " Row 0 | 0 | 1 | 2 | 3 | 4 |\n", " +-------+-------+-------+-------+-------+\n", " Row 1 | 10 | 11 | 12 | 13 | 14 | <- Row 1:3, Col 1:4\n", " +-------+-------+-------+-------+-------+ extracts the subgrid\n", " Row 2 | 20 | 21 | 22 | 23 | 24 | [[11, 12, 13],\n", " +-------+-------+-------+-------+-------+ [21, 22, 23]]\n", " Row 3 | 30 | 31 | 32 | 33 | 34 |\n", " +-------+-------+-------+-------+-------+\n", "```" ] }, { "cell_type": "code", "execution_count": 14, "id": "dfe7f9d2", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.817769Z", "iopub.status.busy": "2026-10-03T05:06:49.817660Z", "iopub.status.idle": "2026-10-03T05:06:49.820070Z", "shell.execute_reply": "2026-10-03T05:06:49.819815Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Full 4x5 Grid:\n", " [[ 0 1 2 3 4]\n", " [ 5 6 7 8 9]\n", " [10 11 12 13 14]\n", " [15 16 17 18 19]]\n", "\n", "Element at (row 1, col 3): 8\n", "\n", "Row 2 (all columns): [10 11 12 13 14]\n", "\n", "Column 1 (all rows): [ 1 6 11 16]\n", "\n", "Subgrid [1:3, 1:4]:\n", " [[ 6 7 8]\n", " [11 12 13]]\n" ] } ], "source": [ "grid = np.arange(20).reshape(4, 5)\n", "print(\"Full 4x5 Grid:\\n\", grid)\n", "\n", "# 1. Single scalar element: Row 1, Column 3\n", "print(\"\\nElement at (row 1, col 3):\", grid[1, 3])\n", "\n", "# 2. Entire Row 2: (use ':' for all columns)\n", "print(\"\\nRow 2 (all columns):\", grid[2, :])\n", "\n", "# 3. Entire Column 1: (all rows)\n", "print(\"\\nColumn 1 (all rows):\", grid[:, 1])\n", "\n", "# 4. Sub-matrix: Rows 1 to 3, Columns 1 to 4\n", "print(\"\\nSubgrid [1:3, 1:4]:\\n\", grid[1:3, 1:4])" ] }, { "cell_type": "markdown", "id": "0086bfa3", "metadata": {}, "source": [ "### 5.3 3D Tensor Slicing & The Ellipsis (`...`)\n", "When working with higher-dimensional tensors (e.g., images of shape `(batch, height, width, channels)`), typing multiple colons `[:, :, :, 0]` gets tedious.\n", "The **ellipsis (`...`)** automatically expands to cover as many full `:` slices as needed!\n", "`tensor[..., 0]` means: select the first channel across all preceding dimensions." ] }, { "cell_type": "code", "execution_count": 15, "id": "fbaf2fb7", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.821123Z", "iopub.status.busy": "2026-10-03T05:06:49.821024Z", "iopub.status.idle": "2026-10-03T05:06:49.823061Z", "shell.execute_reply": "2026-10-03T05:06:49.822848Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Tensor Shape: (2, 3, 4)\n", "Slice tensor[..., 0] shape: (2, 3)\n", "Values:\n", " [[ 0 4 8]\n", " [12 16 20]]\n" ] } ], "source": [ "# 3D Tensor of shape (batch=2, rows=3, cols=4)\n", "tensor = np.arange(24).reshape(2, 3, 4)\n", "\n", "print(\"Tensor Shape:\", tensor.shape)\n", "# Extract the first slice along the last dimension using ellipsis\n", "last_dim_first_col = tensor[..., 0]\n", "print(\"Slice tensor[..., 0] shape:\", last_dim_first_col.shape)\n", "print(\"Values:\\n\", last_dim_first_col)" ] }, { "cell_type": "markdown", "id": "ee9c8ea3", "metadata": {}, "source": [ "### 5.4 Adding Dimensions: `np.newaxis` / `None`\n", "Often you need to convert a 1D vector of shape `(N,)` into a 2D column vector `(N, 1)` or row vector `(1, N)` for matrix multiplication and broadcasting.\n", "Inserting `np.newaxis` (or `None`) creates a new axis of length 1:" ] }, { "cell_type": "code", "execution_count": 16, "id": "9e5f0749", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.824173Z", "iopub.status.busy": "2026-10-03T05:06:49.824077Z", "iopub.status.idle": "2026-10-03T05:06:49.826118Z", "shell.execute_reply": "2026-10-03T05:06:49.825852Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original 1D Vector shape: (4,)\n", "Row Vector shape (1, 4): (1, 4)\n", "Column Vector shape (4, 1): (4, 1)\n", "Column Vector values:\n", " [[1]\n", " [2]\n", " [3]\n", " [4]]\n" ] } ], "source": [ "vec = np.array([1, 2, 3, 4])\n", "print(\"Original 1D Vector shape:\", vec.shape)\n", "\n", "# Convert to 2D Row Vector: shape (1, 4)\n", "row_vec = vec[np.newaxis, :]\n", "print(\"Row Vector shape (1, 4): \", row_vec.shape)\n", "\n", "# Convert to 2D Column Vector: shape (4, 1)\n", "col_vec = vec[:, np.newaxis]\n", "print(\"Column Vector shape (4, 1):\", col_vec.shape)\n", "print(\"Column Vector values:\\n\", col_vec)" ] }, { "cell_type": "markdown", "id": "6f377f9f", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "5f608d79", "metadata": {}, "source": [ "\n", "---\n", "## 6. Views vs Copies: Memory Mechanics\n", "\n", "This is the **#1 source of silent bugs** for Python programmers transitioning to NumPy.\n", "\n", "- **In Standard Python:** Slicing a list `sub = my_list[0:3]` creates a **copy**. Modifying `sub` does NOT alter `my_list`.\n", "- **In NumPy:** Slicing an array `sub = my_arr[0:3]` returns a **VIEW**! It shares the exact same memory buffer. Modifying `sub` **MUTATES THE ORIGINAL ARRAY**!\n", "\n", "### 6.1 Accidental Mutation via Views\n", "Let's see this in action:" ] }, { "cell_type": "code", "execution_count": 17, "id": "afa254cb", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.827260Z", "iopub.status.busy": "2026-10-03T05:06:49.827162Z", "iopub.status.idle": "2026-10-03T05:06:49.829442Z", "shell.execute_reply": "2026-10-03T05:06:49.829206Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before mutation:\n", "Original: [10 20 30 40 50]\n", "View Slice: [20 30 40]\n", "\n", "After mutating view_slice[0] = 999:\n", "View Slice: [999 30 40]\n", "Original: [ 10 999 30 40 50]\n" ] } ], "source": [ "original = np.array([10, 20, 30, 40, 50])\n", "\n", "# Slice returns a VIEW, not a copy!\n", "view_slice = original[1:4]\n", "print(\"Before mutation:\")\n", "print(\"Original: \", original)\n", "print(\"View Slice:\", view_slice)\n", "\n", "# Modify the view\n", "view_slice[0] = 999\n", "\n", "print(\"\\nAfter mutating view_slice[0] = 999:\")\n", "print(\"View Slice:\", view_slice)\n", "print(\"Original: \", original) # ORIGINAL HAS BEEN MUTATED!" ] }, { "cell_type": "markdown", "id": "a3ee6c7b", "metadata": {}, "source": [ "### 6.2 Checking Memory Ownership with `.base`\n", "How can you programmatically verify whether an array owns its memory or is merely a view into another array?\n", "Check the **`.base`** attribute:\n", "- If `arr.base is None`: The array **owns its memory** (it is a standalone copy).\n", "- If `arr.base is not None`: The array is a **view** pointing to the parent buffer stored in `.base`." ] }, { "cell_type": "code", "execution_count": 18, "id": "33d15085", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.830543Z", "iopub.status.busy": "2026-10-03T05:06:49.830446Z", "iopub.status.idle": "2026-10-03T05:06:49.832516Z", "shell.execute_reply": "2026-10-03T05:06:49.832277Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "view_slice.base is original? True\n", "\n", "safe_copy.base is None? True\n", "Safe Copy: [-777 30 40]\n", "Original remains untouched: [ 10 999 30 40 50]\n" ] } ], "source": [ "# Check .base\n", "print(\"view_slice.base is original?\", view_slice.base is original)\n", "\n", "# Creating an explicit, safe copy\n", "safe_copy = original[1:4].copy()\n", "safe_copy[0] = -777\n", "\n", "print(\"\\nsafe_copy.base is None?\", safe_copy.base is None)\n", "print(\"Safe Copy:\", safe_copy)\n", "print(\"Original remains untouched:\", original)" ] }, { "cell_type": "markdown", "id": "a17bcd39", "metadata": {}, "source": [ "> πŸ’‘ **The Golden Rule:**\n", "> Basic slicing (`arr[1:4]`, `arr[:, 2]`) always returns a **view** for maximum speed.\n", "> If you want an independent object, always explicitly call **`.copy()`**!\n", ">\n", "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "ce3772e1", "metadata": {}, "source": [ "\n", "---\n", "## 7. Advanced Indexing & Filtering\n", "\n", "Advanced indexing allows you to query, filter, and extract elements based on conditions or arbitrary index coordinate lists.\n", "\n", "### 7.1 Boolean Masking\n", "You can pass a boolean condition directly inside brackets: `arr[condition]`.\n", "NumPy evaluates the condition element-wise and returns a 1D array of only the elements where the condition is `True`." ] }, { "cell_type": "code", "execution_count": 19, "id": "5fc57bd2", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.833617Z", "iopub.status.busy": "2026-10-03T05:06:49.833520Z", "iopub.status.idle": "2026-10-03T05:06:49.835553Z", "shell.execute_reply": "2026-10-03T05:06:49.835304Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Boolean Mask:\n", " [ True False True False False True True False]\n", "\n", "Positive values only:\n", " [12 8 25 4]\n" ] } ], "source": [ "data = np.array([12, -5, 8, 0, -19, 25, 4, -2])\n", "\n", "# Create a boolean condition\n", "is_positive = data > 0\n", "print(\"Boolean Mask:\\n\", is_positive)\n", "\n", "# Filter values using the mask\n", "positive_values = data[is_positive]\n", "print(\"\\nPositive values only:\\n\", positive_values)" ] }, { "cell_type": "markdown", "id": "b844ff10", "metadata": {}, "source": [ "### 7.2 Combining Conditions: Bitwise `&`, `|`, `~`\n", "Just like in Pandas, you **cannot** use Python's `and`, `or`, and `not` on NumPy arrays. You must use:\n", "- **`&`** for AND\n", "- **`|`** for OR\n", "- **`~`** for NOT\n", "- **Parentheses `()` around every condition** are mandatory!" ] }, { "cell_type": "code", "execution_count": 20, "id": "36787ee5", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.836628Z", "iopub.status.busy": "2026-10-03T05:06:49.836532Z", "iopub.status.idle": "2026-10-03T05:06:49.838561Z", "shell.execute_reply": "2026-10-03T05:06:49.838325Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Positive AND Even: [12 8 4]\n", "Negative OR Greater than 20: [ -5 -19 25 -2]\n" ] } ], "source": [ "# Find numbers that are positive AND even\n", "pos_and_even = data[(data > 0) & (data % 2 == 0)]\n", "\n", "# Find numbers that are negative OR greater than 20\n", "neg_or_large = data[(data < 0) | (data > 20)]\n", "\n", "print(\"Positive AND Even: \", pos_and_even)\n", "print(\"Negative OR Greater than 20:\", neg_or_large)" ] }, { "cell_type": "markdown", "id": "11fb1404", "metadata": {}, "source": [ "### 7.3 Vectorized Conditional Choice: `np.where`\n", "`np.where(condition, value_if_true, value_if_false)` works like Excel's `IF()` or SQL's `CASE WHEN`:" ] }, { "cell_type": "code", "execution_count": 21, "id": "deb75a51", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.839592Z", "iopub.status.busy": "2026-10-03T05:06:49.839510Z", "iopub.status.idle": "2026-10-03T05:06:49.841941Z", "shell.execute_reply": "2026-10-03T05:06:49.841713Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Scores: [85 42 91 68 74]\n", "Status: ['Pass' 'Fail' 'Pass' 'Fail' 'Pass']\n", "\n", "Original Data: [ 12 -5 8 0 -19 25 4 -2]\n", "Clamped (>=0): [12 0 8 0 0 25 4 0]\n" ] } ], "source": [ "scores = np.array([85, 42, 91, 68, 74])\n", "\n", "# If score >= 70 return 'Pass', else return 'Fail'\n", "status = np.where(scores >= 70, 'Pass', 'Fail')\n", "\n", "# Clamp negative values to zero (ReLU activation logic!)\n", "clamped = np.where(data > 0, data, 0)\n", "\n", "print(\"Scores: \", scores)\n", "print(\"Status: \", status)\n", "print(\"\\nOriginal Data: \", data)\n", "print(\"Clamped (>=0): \", clamped)" ] }, { "cell_type": "markdown", "id": "ee0812da", "metadata": {}, "source": [ "### 7.4 Fancy (Integer Array) Indexing\n", "Fancy indexing means passing a list or array of integer indices: `arr[[0, 3, 4]]`.\n", "**Important Rule:** Unlike slicing which produces a view, **fancy indexing always returns a brand new COPY**!" ] }, { "cell_type": "code", "execution_count": 22, "id": "b3594837", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.843015Z", "iopub.status.busy": "2026-10-03T05:06:49.842915Z", "iopub.status.idle": "2026-10-03T05:06:49.844881Z", "shell.execute_reply": "2026-10-03T05:06:49.844641Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected elements via fancy indexing: [100 300 600]\n", "Original pool remains unchanged: [100 200 300 400 500 600]\n" ] } ], "source": [ "arr_pool = np.array([100, 200, 300, 400, 500, 600])\n", "\n", "# Select indices 0, 2, and 5\n", "selected = arr_pool[[0, 2, 5]]\n", "print(\"Selected elements via fancy indexing:\", selected)\n", "\n", "# Modifying selected does NOT mutate arr_pool because it is a copy!\n", "selected[0] = 9999\n", "print(\"Original pool remains unchanged:\", arr_pool)" ] }, { "cell_type": "markdown", "id": "8323434c", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "ad454679", "metadata": {}, "source": [ "\n", "---\n", "## 8. Reshaping & Structural Transforms\n", "\n", "Reshaping changes the dimensions of an array without modifying its data values.\n", "\n", "### 8.1 The `.reshape()` Method & `-1` Auto-Inference\n", "When reshaping, the total number of elements must stay identical (`rows * cols == total elements`).\n", "NumPy allows you to pass `-1` for **one dimension**, and it will automatically calculate the correct size!" ] }, { "cell_type": "code", "execution_count": 23, "id": "0eea89bf", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.845955Z", "iopub.status.busy": "2026-10-03T05:06:49.845870Z", "iopub.status.idle": "2026-10-03T05:06:49.847933Z", "shell.execute_reply": "2026-10-03T05:06:49.847708Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original 1D shape: (12,)\n", "\n", "Reshaped to (3, 4):\n", " [[ 0 1 2 3]\n", " [ 4 5 6 7]\n", " [ 8 9 10 11]]\n", "\n", "Reshaped to (2, -1) -> inferred shape: (2, 6)\n" ] } ], "source": [ "a = np.arange(12)\n", "print(\"Original 1D shape:\", a.shape)\n", "\n", "# Reshape into 3 rows and 4 columns\n", "matrix_3x4 = a.reshape(3, 4)\n", "print(\"\\nReshaped to (3, 4):\\n\", matrix_3x4)\n", "\n", "# Use -1 to let NumPy infer columns: 2 rows -> auto-computes 6 columns\n", "matrix_2x6 = a.reshape(2, -1)\n", "print(\"\\nReshaped to (2, -1) -> inferred shape:\", matrix_2x6.shape)" ] }, { "cell_type": "markdown", "id": "8052a9c1", "metadata": {}, "source": [ "### 8.2 Flattening: `flatten()` vs `ravel()`\n", "Both collapse a multi-dimensional array into a 1D vector, but their memory behavior is different:\n", "- **`arr.ravel()`**: Returns a **view** whenever possible (zero memory overhead, ultra fast).\n", "- **`arr.flatten()`**: Always allocates and returns a brand-new **copy** in memory." ] }, { "cell_type": "code", "execution_count": 24, "id": "fe1888f7", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.848998Z", "iopub.status.busy": "2026-10-03T05:06:49.848920Z", "iopub.status.idle": "2026-10-03T05:06:49.850848Z", "shell.execute_reply": "2026-10-03T05:06:49.850617Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "flat_view.base is mat? True\n", "flat_copy.base is None? True\n" ] } ], "source": [ "mat = np.array([[1, 2], [3, 4]])\n", "\n", "flat_view = mat.ravel() # View\n", "flat_copy = mat.flatten() # Copy\n", "\n", "print(\"flat_view.base is mat? \", flat_view.base is mat)\n", "print(\"flat_copy.base is None?\", flat_copy.base is None)" ] }, { "cell_type": "markdown", "id": "effc4208", "metadata": {}, "source": [ "### 8.3 Transpose (`.T`) & Squeezing Extra Dimensions\n", "- **`.T`**: Swaps axes (rows become columns).\n", "- **`np.squeeze(arr)`**: Drops any redundant dimensions of length 1 (e.g. transforms shape `(1, 4, 1)` into `(4,)`)." ] }, { "cell_type": "code", "execution_count": 25, "id": "ae2f8f6b", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.851923Z", "iopub.status.busy": "2026-10-03T05:06:49.851848Z", "iopub.status.idle": "2026-10-03T05:06:49.853907Z", "shell.execute_reply": "2026-10-03T05:06:49.853679Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix:\n", " [[ 0 1 2 3]\n", " [ 4 5 6 7]\n", " [ 8 9 10 11]]\n", "\n", "Transposed (4x3):\n", " [[ 0 4 8]\n", " [ 1 5 9]\n", " [ 2 6 10]\n", " [ 3 7 11]]\n", "\n", "Before squeeze shape: (1, 5, 1)\n", "After squeeze shape: (5,)\n" ] } ], "source": [ "# Transpose\n", "print(\"Matrix:\\n\", matrix_3x4)\n", "print(\"\\nTransposed (4x3):\\n\", matrix_3x4.T)\n", "\n", "# Squeeze redundant dimensions\n", "redundant = np.zeros((1, 5, 1))\n", "print(\"\\nBefore squeeze shape:\", redundant.shape)\n", "squeezed = np.squeeze(redundant)\n", "print(\"After squeeze shape: \", squeezed.shape)" ] }, { "cell_type": "markdown", "id": "19ca5399", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "f79a47cf", "metadata": {}, "source": [ "\n", "---\n", "# Part III: Mathematical Operations & Broadcasting\n", "\n", "## 9. Combining, Stacking & Splitting Arrays\n", "\n", "### 9.1 Stacking Arrays: `vstack`, `hstack`, `concatenate`\n", "- **`np.vstack([a, b])`**: Stacks arrays **vertically** (row on top of row; increases rows).\n", "- **`np.hstack([a, b])`**: Stacks arrays **horizontally** (side-by-side; increases columns).\n", "- **`np.concatenate([a, b], axis=0)`**: General concatenation along any specified axis." ] }, { "cell_type": "code", "execution_count": 26, "id": "5c6c6255", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.854997Z", "iopub.status.busy": "2026-10-03T05:06:49.854906Z", "iopub.status.idle": "2026-10-03T05:06:49.857122Z", "shell.execute_reply": "2026-10-03T05:06:49.856899Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Vertical Stack (rows added):\n", " [[1 2]\n", " [3 4]\n", " [5 6]\n", " [7 8]]\n", "\n", "Horizontal Stack (columns added):\n", " [[1 2 5 6]\n", " [3 4 7 8]]\n" ] } ], "source": [ "a = np.array([[1, 2], [3, 4]])\n", "b = np.array([[5, 6], [7, 8]])\n", "\n", "# Vertical stack\n", "v_stacked = np.vstack([a, b])\n", "\n", "# Horizontal stack\n", "h_stacked = np.hstack([a, b])\n", "\n", "print(\"Vertical Stack (rows added):\\n\", v_stacked)\n", "print(\"\\nHorizontal Stack (columns added):\\n\", h_stacked)" ] }, { "cell_type": "markdown", "id": "a47f889f", "metadata": {}, "source": [ "### 9.2 Splitting Arrays\n", "Use `np.split(arr, indices_or_sections, axis=...)` to cut an array into sub-arrays:" ] }, { "cell_type": "code", "execution_count": 27, "id": "776683c9", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.858219Z", "iopub.status.busy": "2026-10-03T05:06:49.858136Z", "iopub.status.idle": "2026-10-03T05:06:49.860222Z", "shell.execute_reply": "2026-10-03T05:06:49.859990Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Part 0: [0 1 2 3]\n", "Part 1: [4 5 6 7]\n", "Part 2: [ 8 9 10 11]\n" ] } ], "source": [ "big_arr = np.arange(12)\n", "\n", "# Split into 3 equal portions\n", "parts = np.split(big_arr, 3)\n", "for idx, part in enumerate(parts):\n", " print(f\"Part {idx}: {part}\")" ] }, { "cell_type": "markdown", "id": "98c91411", "metadata": {}, "source": [ "### 9.3 Tiling vs Repeating\n", "- **`np.repeat(arr, repeats)`**: Duplicates individual elements consecutively `[1, 1, 2, 2]`.\n", "- **`np.tile(arr, reps)`**: Tiles the entire block like floor tiles `[1, 2, 1, 2]`." ] }, { "cell_type": "code", "execution_count": 28, "id": "5b616446", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.861289Z", "iopub.status.busy": "2026-10-03T05:06:49.861201Z", "iopub.status.idle": "2026-10-03T05:06:49.863321Z", "shell.execute_reply": "2026-10-03T05:06:49.863095Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Base: [1 2 3]\n", "Repeated: [1 1 2 2 3 3]\n", "Tiled: [1 2 3 1 2 3]\n" ] } ], "source": [ "base = np.array([1, 2, 3])\n", "\n", "repeated = np.repeat(base, 2)\n", "tiled = np.tile(base, 2)\n", "\n", "print(\"Base: \", base)\n", "print(\"Repeated:\", repeated)\n", "print(\"Tiled: \", tiled)" ] }, { "cell_type": "markdown", "id": "dbef9e22", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "da7971e5", "metadata": {}, "source": [ "\n", "---\n", "## 10. Universal Functions (ufuncs)\n", "\n", "A **universal function (ufunc)** is a function that operates on ndarrays element-by-element at compiled C speed.\n", "\n", "### 10.1 Element-Wise Arithmetic & Math Functions\n", "All standard operators (`+`, `-`, `*`, `/`, `**`, `//`, `%`) map directly to optimized ufuncs:" ] }, { "cell_type": "code", "execution_count": 29, "id": "8517e1ca", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:49.864377Z", "iopub.status.busy": "2026-10-03T05:06:49.864297Z", "iopub.status.idle": "2026-10-03T05:06:50.007911Z", "shell.execute_reply": "2026-10-03T05:06:50.007562Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Square root: [1. 2. 3. 4.]\n", "Exponential: [ 2.71828183 7.3890561 20.08553692]\n", "Natural log: [0. 1.38629436 2.19722458 2.77258872]\n", "Sine: [0. 1. 0.]\n" ] } ], "source": [ "x = np.array([1.0, 4.0, 9.0, 16.0])\n", "\n", "print(\"Square root: \", np.sqrt(x))\n", "print(\"Exponential: \", np.exp(np.array([1, 2, 3])))\n", "print(\"Natural log: \", np.log(x))\n", "print(\"Sine: \", np.sin(np.array([0, np.pi/2, np.pi])).round(2))" ] }, { "cell_type": "markdown", "id": "161833fa", "metadata": {}, "source": [ "### 10.2 Special ufunc Methods: `reduce`, `accumulate`, `outer`\n", "Built-in ufuncs have superpower methods:\n", "- **`.reduce()`**: Applies the operation sequentially across the array (e.g. `np.add.reduce(arr)` is equivalent to `arr.sum()`).\n", "- **`.accumulate()`**: Keeps running running totals (e.g. `np.add.accumulate(arr)` is `cumsum()`).\n", "- **`.outer()`**: Computes the pairwise operation between all pairs of two vectors to create a matrix (e.g. a multiplication table!)." ] }, { "cell_type": "code", "execution_count": 30, "id": "6c566dc7", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.009218Z", "iopub.status.busy": "2026-10-03T05:06:50.009122Z", "iopub.status.idle": "2026-10-03T05:06:50.011491Z", "shell.execute_reply": "2026-10-03T05:06:50.011246Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running cumulative sum: [ 1 3 6 10 15]\n", "\n", "5x5 Multiplication Table:\n", " [[ 1 2 3 4 5]\n", " [ 2 4 6 8 10]\n", " [ 3 6 9 12 15]\n", " [ 4 8 12 16 20]\n", " [ 5 10 15 20 25]]\n" ] } ], "source": [ "nums = np.array([1, 2, 3, 4, 5])\n", "\n", "# Running cumulative sum\n", "running_sum = np.add.accumulate(nums)\n", "print(\"Running cumulative sum:\", running_sum)\n", "\n", "# Outer multiplication table (1 to 5 times 1 to 5)\n", "mult_table = np.multiply.outer(nums, nums)\n", "print(\"\\n5x5 Multiplication Table:\\n\", mult_table)" ] }, { "cell_type": "markdown", "id": "d5d7de32", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "f139e8a2", "metadata": {}, "source": [ "\n", "---\n", "## 11. Broadcasting Demystified: The 3 Rules\n", "\n", "Broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations without making unnecessary copies of data in RAM.\n", "\n", "### 11.1 The 3 Broadcasting Rules\n", "When operating on two arrays, NumPy compares their shapes **element-wise from right to left** (trailing dimensions first):\n", "1. **Rule 1:** If the two arrays have a different number of dimensions, pad the shape of the smaller array with `1`s on its **left** side.\n", "2. **Rule 2:** Two dimensions are **compatible** if they are equal, or if one of them is `1`.\n", "3. **Rule 3:** If a dimension has size `1`, that dimension is virtually stretched to match the larger dimension!\n", "\n", "```\n", " VISUAL EXAMPLE OF BROADCASTING\n", " \n", " Matrix A: shape (3, 3) Vector B: shape (3,)\n", " +----+----+----+ Padded to: shape (1, 3)\n", " | 10 | 10 | 10 | +----+----+----+\n", " +----+----+----+ | 1 | 2 | 3 |\n", " | 20 | 20 | 20 | +----+----+----+\n", " +----+----+----+ |\n", " | 30 | 30 | 30 | Virtually stretched down\n", " +----+----+----+ +----+----+----+\n", " + | 1 | 2 | 3 |\n", " +----+----+----+\n", " | 1 | 2 | 3 |\n", " +----+----+----+\n", " | 1 | 2 | 3 |\n", " +----+----+----+\n", " =\n", " +----+----+----+\n", " | 11 | 12 | 13 |\n", " +----+----+----+\n", " | 21 | 22 | 23 |\n", " +----+----+----+\n", " | 31 | 32 | 33 |\n", " +----+----+----+\n", "```" ] }, { "cell_type": "code", "execution_count": 31, "id": "2ad97494", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.012641Z", "iopub.status.busy": "2026-10-03T05:06:50.012557Z", "iopub.status.idle": "2026-10-03T05:06:50.014649Z", "shell.execute_reply": "2026-10-03T05:06:50.014401Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A (3x3) + B (3,) =\n", " [[11 12 13]\n", " [21 22 23]\n", " [31 32 33]]\n" ] } ], "source": [ "# Matrix shape (3, 3)\n", "A = np.array([[10, 10, 10], [20, 20, 20], [30, 30, 30]])\n", "\n", "# 1D Vector shape (3,) -> broadcasts seamlessly across rows!\n", "B = np.array([1, 2, 3])\n", "\n", "result = A + B\n", "print(\"A (3x3) + B (3,) =\\n\", result)" ] }, { "cell_type": "markdown", "id": "2cf85a6e", "metadata": {}, "source": [ "### 11.2 Practical Example: Feature Standardization (Z-score Normalization)\n", "In Machine Learning, we standardize features by subtracting the column mean and dividing by the column standard deviation:\n", "$$Z = \\frac{X - \\mu}{\\sigma}$$\n", "Broadcasting performs this entire matrix calculation in one clean line!" ] }, { "cell_type": "code", "execution_count": 32, "id": "7628997d", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.015764Z", "iopub.status.busy": "2026-10-03T05:06:50.015673Z", "iopub.status.idle": "2026-10-03T05:06:50.018519Z", "shell.execute_reply": "2026-10-03T05:06:50.018220Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Feature Means: [ 10.5 207.5 1.52]\n", "Feature Std Devs: [ 1.12 21.65 0.22]\n", "\n", "Standardized Matrix (Zero mean, unit variance):\n", " [[-0.45 -0.35 -0.12]\n", " [ 1.34 1.5 1.27]\n", " [-1.34 -1.27 -1.5 ]\n", " [ 0.45 0.12 0.35]]\n" ] } ], "source": [ "# 4 samples with 3 features each: shape (4, 3)\n", "X = np.array([\n", " [10.0, 200.0, 1.5],\n", " [12.0, 240.0, 1.8],\n", " [9.0, 180.0, 1.2],\n", " [11.0, 210.0, 1.6]\n", "])\n", "\n", "# Mean and std computed along rows (axis=0): shape (3,)\n", "mean = np.mean(X, axis=0)\n", "std = np.std(X, axis=0)\n", "\n", "# Broadcasted Z-score standardization!\n", "X_standardized = (X - mean) / std\n", "\n", "print(\"Feature Means: \", mean.round(2))\n", "print(\"Feature Std Devs: \", std.round(2))\n", "print(\"\\nStandardized Matrix (Zero mean, unit variance):\\n\", X_standardized.round(2))" ] }, { "cell_type": "markdown", "id": "ae023005", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "7ef9ede9", "metadata": {}, "source": [ "\n", "---\n", "## 12. Aggregations & The Axis Model\n", "\n", "Aggregations collapse multi-dimensional data into summary statistics (e.g. `sum`, `mean`, `std`, `min`, `max`).\n", "\n", "### 12.1 The Axis Direction Mental Model\n", "Beginners frequently confuse `axis=0` and `axis=1`. Here is the easiest way to remember:\n", "- **`axis=0`**: Collapse **downward across rows** (computes column-wise summaries).\n", "- **`axis=1`**: Collapse **horizontally across columns** (computes row-wise summaries).\n", "\n", "```\n", " axis=1 (Horizontal collapse -> row summaries)\n", " -------->\n", " Col 0 Col 1 Col 2\n", " +-------+-------+-------+\n", " axis=0 Row 0 | 1 | 2 | 3 | -> sum(Row 0) = 6\n", "(Vertical Row 1 | 4 | 5 | 6 | -> sum(Row 1) = 15\n", "collapse) Row 2 | 7 | 8 | 9 | -> sum(Row 2) = 24\n", " | +-------+-------+-------+\n", " v | | |\n", " sum(Cols) = 12 15 18\n", "```" ] }, { "cell_type": "code", "execution_count": 33, "id": "ebffe8d1", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.019697Z", "iopub.status.busy": "2026-10-03T05:06:50.019599Z", "iopub.status.idle": "2026-10-03T05:06:50.023106Z", "shell.execute_reply": "2026-10-03T05:06:50.022868Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overall Matrix Sum: 45\n", "Column-wise Sums (axis=0): [12 15 18]\n", "Row-wise Sums (axis=1): [ 6 15 24]\n", "Row-wise Max Values (axis=1): [3 6 9]\n", "Index of Max in each row: [2 2 2]\n" ] } ], "source": [ "mat = np.array([\n", " [1, 2, 3],\n", " [4, 5, 6],\n", " [7, 8, 9]\n", "])\n", "\n", "print(\"Overall Matrix Sum: \", np.sum(mat))\n", "print(\"Column-wise Sums (axis=0): \", np.sum(mat, axis=0))\n", "print(\"Row-wise Sums (axis=1): \", np.sum(mat, axis=1))\n", "print(\"Row-wise Max Values (axis=1): \", np.max(mat, axis=1))\n", "print(\"Index of Max in each row: \", np.argmax(mat, axis=1))" ] }, { "cell_type": "markdown", "id": "05f7ecc4", "metadata": {}, "source": [ "### 12.2 The Power of `keepdims=True`\n", "When you aggregate an axis, NumPy removes that dimension by default: shape `(3, 4)` becomes `(3,)`.\n", "If you want to subtract row means from the original matrix, the shapes won't align for broadcasting!\n", "Setting `keepdims=True` retains the reduced axis as length 1: shape `(3, 1)`. This allows instant broadcasting!" ] }, { "cell_type": "code", "execution_count": 34, "id": "506664ef", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.024225Z", "iopub.status.busy": "2026-10-03T05:06:50.024120Z", "iopub.status.idle": "2026-10-03T05:06:50.026251Z", "shell.execute_reply": "2026-10-03T05:06:50.026014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Row means with keepdims=True shape: (3, 1)\n", "\n", "Mean-centered rows:\n", " [[-1. 0. 1.]\n", " [-1. 0. 1.]\n", " [-1. 0. 1.]]\n" ] } ], "source": [ "# Subtract row means from matrix\n", "row_means = np.mean(mat, axis=1, keepdims=True)\n", "print(\"Row means with keepdims=True shape:\", row_means.shape)\n", "\n", "# Broadcast subtraction works smoothly!\n", "centered_mat = mat - row_means\n", "print(\"\\nMean-centered rows:\\n\", centered_mat)" ] }, { "cell_type": "markdown", "id": "e4210381", "metadata": {}, "source": [ "### 12.3 NaN-Safe Aggregations\n", "If an array contains even a single `np.nan`, standard functions like `np.mean()` return `NaN`.\n", "NumPy provides `nan`-safe alternatives that ignore missing values: `np.nansum()`, `np.nanmean()`, `np.nanstd()`, `np.nanmedian()`." ] }, { "cell_type": "code", "execution_count": 35, "id": "03873c14", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.027419Z", "iopub.status.busy": "2026-10-03T05:06:50.027312Z", "iopub.status.idle": "2026-10-03T05:06:50.029225Z", "shell.execute_reply": "2026-10-03T05:06:50.028984Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Standard mean (fails on NaN): nan\n", "NaN-safe mean (ignores NaN): 23.333333333333332\n" ] } ], "source": [ "messy = np.array([10.0, 20.0, np.nan, 40.0])\n", "\n", "print(\"Standard mean (fails on NaN):\", np.mean(messy))\n", "print(\"NaN-safe mean (ignores NaN): \", np.nanmean(messy))" ] }, { "cell_type": "markdown", "id": "d0655359", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "5bf00c65", "metadata": {}, "source": [ "\n", "---\n", "# Part IV: Linear Algebra, ML & Optimization\n", "\n", "## 13. Sorting, Searching & Ranking\n", "\n", "### 13.1 `sort()` vs `argsort()`\n", "- **`np.sort(arr)`**: Returns the sorted values.\n", "- **`np.argsort(arr)`**: Returns the **integer indices** that would sort the array.\n", "`argsort` is essential whenever you need to sort multiple aligned arrays simultaneously (e.g., sorting student names based on their exam scores)." ] }, { "cell_type": "code", "execution_count": 36, "id": "d2c12c77", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.030282Z", "iopub.status.busy": "2026-10-03T05:06:50.030202Z", "iopub.status.idle": "2026-10-03T05:06:50.032971Z", "shell.execute_reply": "2026-10-03T05:06:50.032719Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Score sort order indices: [2 0 3 1]\n", "\n", "Ranked Leaderboard:\n", "Rank 1: Bob with score 95\n", "Rank 2: Diana with score 88\n", "Rank 3: Alice with score 78\n", "Rank 4: Charlie with score 62\n" ] } ], "source": [ "students = np.array(['Alice', 'Bob', 'Charlie', 'Diana'])\n", "scores = np.array([78, 95, 62, 88])\n", "\n", "# argsort gives indices of lowest to highest scores\n", "sort_order = np.argsort(scores)\n", "print(\"Score sort order indices:\", sort_order)\n", "\n", "# Reorder both arrays from highest to lowest score\n", "descending_order = sort_order[::-1]\n", "print(\"\\nRanked Leaderboard:\")\n", "for rank, idx in enumerate(descending_order, start=1):\n", " print(f\"Rank {rank}: {students[idx]} with score {scores[idx]}\")" ] }, { "cell_type": "markdown", "id": "d5f4d3fb", "metadata": {}, "source": [ "### 13.2 Fast $O(N)$ Top-K Selection: `argpartition`\n", "Sorting an array of 1,000,000 elements takes $O(N \\log N)$ time.\n", "If you only need the **top 5 largest elements**, full sorting is wasteful.\n", "`np.argpartition(arr, -k)` finds the top $k$ elements in blazing fast **linear time $O(N)$**!" ] }, { "cell_type": "code", "execution_count": 37, "id": "e6ab4703", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.034081Z", "iopub.status.busy": "2026-10-03T05:06:50.033998Z", "iopub.status.idle": "2026-10-03T05:06:50.036140Z", "shell.execute_reply": "2026-10-03T05:06:50.035871Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Top 3 values: [85 89 99]\n" ] } ], "source": [ "data_pool = np.array([45, 12, 89, 34, 99, 23, 77, 85, 10, 64])\n", "\n", "# Find indices of top 3 largest elements without sorting entire array\n", "top3_indices = np.argpartition(data_pool, -3)[-3:]\n", "print(\"Top 3 values:\", data_pool[top3_indices])" ] }, { "cell_type": "markdown", "id": "70dc8d6a", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "dc91d9f9", "metadata": {}, "source": [ "\n", "---\n", "## 14. Linear Algebra Made Intuitive (`np.linalg`)\n", "\n", "Linear algebra is the mathematical language of Machine Learning, Neural Networks, and Computer Vision.\n", "\n", "### 14.1 Element-Wise Multiplication (`*`) vs Matrix Product (`@`)\n", "- **`A * B`**: Multiplies elements at matching positions.\n", "- **`A @ B`** or **`np.matmul(A, B)`**: Performs real matrix multiplication (dot product of rows and columns)." ] }, { "cell_type": "code", "execution_count": 38, "id": "e750f8bd", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.037168Z", "iopub.status.busy": "2026-10-03T05:06:50.037087Z", "iopub.status.idle": "2026-10-03T05:06:50.039137Z", "shell.execute_reply": "2026-10-03T05:06:50.038927Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Element-wise multiplication (A * B):\n", " [[2 0]\n", " [3 8]]\n", "\n", "Matrix multiplication (A @ B):\n", " [[ 4 4]\n", " [10 8]]\n" ] } ], "source": [ "A = np.array([[1, 2], [3, 4]])\n", "B = np.array([[2, 0], [1, 2]])\n", "\n", "print(\"Element-wise multiplication (A * B):\\n\", A * B)\n", "print(\"\\nMatrix multiplication (A @ B):\\n\", A @ B)" ] }, { "cell_type": "markdown", "id": "b7bc374d", "metadata": {}, "source": [ "### 14.2 Vector Norms: Measuring Vector Magnitude\n", "- **L1 Norm (Manhattan distance):** Sum of absolute values $\\sum |x_i|$.\n", "- **L2 Norm (Euclidean distance):** Straight-line geometric distance $\\sqrt{\\sum x_i^2}$." ] }, { "cell_type": "code", "execution_count": 39, "id": "f25af4e7", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.040197Z", "iopub.status.busy": "2026-10-03T05:06:50.040108Z", "iopub.status.idle": "2026-10-03T05:06:50.042354Z", "shell.execute_reply": "2026-10-03T05:06:50.042127Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Vector: [ 3. -4.]\n", "L1 Norm (Manhattan, |3| + |-4|): 7.0\n", "L2 Norm (Euclidean, sqrt(3^2 + 4^2)): 5.0\n" ] } ], "source": [ "v = np.array([3.0, -4.0])\n", "\n", "norm_l1 = np.linalg.norm(v, ord=1)\n", "norm_l2 = np.linalg.norm(v, ord=2)\n", "\n", "print(\"Vector:\", v)\n", "print(f\"L1 Norm (Manhattan, |3| + |-4|): {norm_l1}\")\n", "print(f\"L2 Norm (Euclidean, sqrt(3^2 + 4^2)): {norm_l2}\")" ] }, { "cell_type": "markdown", "id": "a229ec01", "metadata": {}, "source": [ "### 14.3 Solving Linear Equation Systems ($Ax = b$)\n", "Suppose you want to solve this system of linear equations:\n", "$$2x + y = 8$$\n", "$$x + 3y = 14$$\n", "\n", "In matrix form: $Ax = b$.\n", "Never calculate $x = A^{-1}b$ directly (inverting matrices is numerically unstable and slow). Always use **`np.linalg.solve(A, b)`**!" ] }, { "cell_type": "code", "execution_count": 40, "id": "3e345702", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.043375Z", "iopub.status.busy": "2026-10-03T05:06:50.043294Z", "iopub.status.idle": "2026-10-03T05:06:50.045583Z", "shell.execute_reply": "2026-10-03T05:06:50.045366Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Solution: x = 2.0, y = 4.0\n" ] } ], "source": [ "# Coefficient matrix A and target vector b\n", "A = np.array([[2, 1], [1, 3]])\n", "b = np.array([8, 14])\n", "\n", "# Solve for x\n", "solution = np.linalg.solve(A, b)\n", "print(f\"Solution: x = {solution[0]}, y = {solution[1]}\")" ] }, { "cell_type": "markdown", "id": "e6bb2256", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "6f3d30d9", "metadata": {}, "source": [ "\n", "---\n", "## 15. Practical Machine Learning Vectorization\n", "\n", "Here we look at essential Machine Learning building blocks written in pure, vectorized NumPy without any Python `for` loops.\n", "\n", "### 15.1 Pairwise Euclidean Distance Matrix\n", "Given $N$ points in $D$ dimensions, calculate the distance between every pair of points.\n", "Using broadcasting and the algebraic identity:\n", "$$\\|a - b\\|^2 = \\|a\\|^2 + \\|b\\|^2 - 2(a \\cdot b)$$" ] }, { "cell_type": "code", "execution_count": 41, "id": "a15ec170", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.046586Z", "iopub.status.busy": "2026-10-03T05:06:50.046506Z", "iopub.status.idle": "2026-10-03T05:06:50.048890Z", "shell.execute_reply": "2026-10-03T05:06:50.048661Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Pairwise Euclidean Distance Matrix (4x4):\n", " [[0. 3. 4. 5.]\n", " [3. 0. 5. 4.]\n", " [4. 5. 0. 3.]\n", " [5. 4. 3. 0.]]\n" ] } ], "source": [ "# 4 points in 2D space\n", "points = np.array([\n", " [0.0, 0.0],\n", " [3.0, 0.0],\n", " [0.0, 4.0],\n", " [3.0, 4.0]\n", "])\n", "\n", "# Sum of squares along rows: shape (4, 1)\n", "sq_norms = np.sum(points ** 2, axis=1, keepdims=True)\n", "\n", "# Pairwise squared distances via broadcasting\n", "dists_sq = sq_norms + sq_norms.T - 2 * (points @ points.T)\n", "dists_sq = np.maximum(dists_sq, 0.0) # Guard against tiny floating point precision artifacts\n", "distance_matrix = np.sqrt(dists_sq)\n", "\n", "print(\"Pairwise Euclidean Distance Matrix (4x4):\\n\", distance_matrix.round(2))" ] }, { "cell_type": "markdown", "id": "a505da25", "metadata": {}, "source": [ "### 15.2 Numerically Stable Softmax\n", "Softmax turns raw model scores (logits) into class probabilities summing to 1:\n", "$$\\text{Softmax}(z_i) = \\frac{e^{z_i}}{\\sum_j e^{z_j}}$$\n", "If $z_i = 1000$, $e^{1000}$ triggers floating-point overflow (`inf`), giving `NaN`!\n", "**The Stable Trick:** Subtract the row maximum $\\max(z)$ before exponentiating:" ] }, { "cell_type": "code", "execution_count": 42, "id": "dc78a0ab", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.049910Z", "iopub.status.busy": "2026-10-03T05:06:50.049830Z", "iopub.status.idle": "2026-10-03T05:06:50.052399Z", "shell.execute_reply": "2026-10-03T05:06:50.052134Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Softmax Probabilities:\n", " [[0.09 0.2447 0.6652]\n", " [0.09 0.2447 0.6652]]\n", "Row sums verify to 1.0: [1. 1.]\n" ] } ], "source": [ "def stable_softmax(logits):\n", " # Subtract row max for stability\n", " shifted = logits - np.max(logits, axis=-1, keepdims=True)\n", " exp_scores = np.exp(shifted)\n", " return exp_scores / np.sum(exp_scores, axis=-1, keepdims=True)\n", "\n", "# Test with huge logits that would normally crash standard softmax\n", "raw_logits = np.array([\n", " [1000.0, 1001.0, 1002.0],\n", " [1.0, 2.0, 3.0]\n", "])\n", "\n", "probabilities = stable_softmax(raw_logits)\n", "print(\"Softmax Probabilities:\\n\", probabilities.round(4))\n", "print(\"Row sums verify to 1.0:\", np.sum(probabilities, axis=1))" ] }, { "cell_type": "markdown", "id": "b4b83b8a", "metadata": {}, "source": [ "### 15.3 Vectorized One-Hot Encoding\n", "Convert category integer indices into binary vectors in one single line of code using `np.eye`:" ] }, { "cell_type": "code", "execution_count": 43, "id": "08b8aa7c", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.053414Z", "iopub.status.busy": "2026-10-03T05:06:50.053329Z", "iopub.status.idle": "2026-10-03T05:06:50.055499Z", "shell.execute_reply": "2026-10-03T05:06:50.055264Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Integer Labels: [0 2 1 0 3]\n", "One-Hot Encoded Matrix:\n", " [[1. 0. 0. 0.]\n", " [0. 0. 1. 0.]\n", " [0. 1. 0. 0.]\n", " [1. 0. 0. 0.]\n", " [0. 0. 0. 1.]]\n" ] } ], "source": [ "labels = np.array([0, 2, 1, 0, 3])\n", "num_classes = 4\n", "\n", "# One-hot encoding via identity matrix indexing!\n", "one_hot_matrix = np.eye(num_classes)[labels]\n", "\n", "print(\"Integer Labels: \", labels)\n", "print(\"One-Hot Encoded Matrix:\\n\", one_hot_matrix)" ] }, { "cell_type": "markdown", "id": "492d4342", "metadata": {}, "source": [ "### 15.4 Mean Squared Error (MSE) Loss\n", "The standard loss function for regression:\n", "$$\\text{MSE} = \\frac{1}{N} \\sum_{i=1}^N (y_{\\text{true}} - y_{\\text{pred}})^2$$" ] }, { "cell_type": "code", "execution_count": 44, "id": "043e2461", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.056580Z", "iopub.status.busy": "2026-10-03T05:06:50.056497Z", "iopub.status.idle": "2026-10-03T05:06:50.058610Z", "shell.execute_reply": "2026-10-03T05:06:50.058376Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mean Squared Error (MSE): 0.4240\n", "Root Mean Squared (RMSE): 0.6512\n" ] } ], "source": [ "y_true = np.array([10.5, 14.2, 18.0, 22.1, 30.5])\n", "y_pred = np.array([11.0, 13.8, 18.5, 21.0, 31.0])\n", "\n", "mse_loss = np.mean((y_true - y_pred) ** 2)\n", "rmse_loss = np.sqrt(mse_loss)\n", "\n", "print(f\"Mean Squared Error (MSE): {mse_loss:.4f}\")\n", "print(f\"Root Mean Squared (RMSE): {rmse_loss:.4f}\")" ] }, { "cell_type": "markdown", "id": "70766bb5", "metadata": {}, "source": [ "> [⬆️ Back to Table of Contents](#table-of-contents)" ] }, { "cell_type": "markdown", "id": "921e8684", "metadata": {}, "source": [ "\n", "---\n", "## 16. Performance Optimization & Anti-Patterns\n", "\n", "### 16.1 The `#1` NumPy Anti-Pattern: `np.append()` Inside a Loop\n", "In Python lists, `list.append()` takes $O(1)$ amortized time.\n", "In NumPy, `np.append()` **allocates a brand-new array and copies all existing data into it!**\n", "Running `np.append()` inside a loop of $N$ iterations runs in **$O(N^2)$ time** and destroys performance.\n", "\n", "**The Fix:** Always **preallocate** an empty array of the final size using `np.empty()` or `np.zeros()`!" ] }, { "cell_type": "code", "execution_count": 45, "id": "1e9d2655", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.059693Z", "iopub.status.busy": "2026-10-03T05:06:50.059599Z", "iopub.status.idle": "2026-10-03T05:06:50.181313Z", "shell.execute_reply": "2026-10-03T05:06:50.181053Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "❌ np.append loop: 0.1224 seconds\n", "βœ… Preallocation: 0.0024 seconds\n", "⚑ Preallocation is 50.1x faster!\n" ] } ], "source": [ "N = 25_000\n", "\n", "# ❌ The Anti-Pattern: np.append inside loop\n", "t0 = time.perf_counter()\n", "bad_arr = np.array([])\n", "for i in range(N):\n", " bad_arr = np.append(bad_arr, i)\n", "t1 = time.perf_counter()\n", "time_bad = t1 - t0\n", "\n", "# βœ… The Best Practice: Preallocate memory once!\n", "t0 = time.perf_counter()\n", "good_arr = np.empty(N, dtype=np.float64)\n", "for i in range(N):\n", " good_arr[i] = i\n", "t1 = time.perf_counter()\n", "time_good = t1 - t0\n", "\n", "print(f\"❌ np.append loop: {time_bad:.4f} seconds\")\n", "print(f\"βœ… Preallocation: {time_good:.4f} seconds\")\n", "print(f\"⚑ Preallocation is {time_bad / time_good:.1f}x faster!\")" ] }, { "cell_type": "markdown", "id": "e4d46003", "metadata": {}, "source": [ "### 16.2 In-Place Operations to Save Memory\n", "Expressions like `a = a + b` allocate a temporary intermediate array before reassigning.\n", "Using in-place operators (`+=`, `*=`) modifies data directly in RAM without allocating new memory:" ] }, { "cell_type": "code", "execution_count": 46, "id": "ea19dabd", "metadata": { "execution": { "iopub.execute_input": "2026-10-03T05:06:50.182475Z", "iopub.status.busy": "2026-10-03T05:06:50.182385Z", "iopub.status.idle": "2026-10-03T05:06:50.187513Z", "shell.execute_reply": "2026-10-03T05:06:50.187252Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Same memory buffer maintained? True\n" ] } ], "source": [ "big_a = np.ones((1000, 1000), dtype=np.float64)\n", "big_b = np.ones((1000, 1000), dtype=np.float64)\n", "\n", "# Memory address before\n", "id_before = id(big_a)\n", "\n", "# In-place operation modifies existing buffer in RAM\n", "big_a += big_b\n", "id_after = id(big_a)\n", "\n", "print(\"Same memory buffer maintained?\", id_before == id_after)" ] }, { "cell_type": "markdown", "id": "9fc23100", "metadata": {}, "source": [ "---\n", "\n", "## πŸ† Comprehensive NumPy Quick Reference Cheat Sheet\n", "\n", "| Category | High-Frequency Function | Quick Example |\n", "| :--- | :--- | :--- |\n", "| **Creation** | `np.array`, `np.zeros`, `np.ones`, `np.full`, `np.arange`, `np.linspace`, `np.eye` | `np.linspace(0, 1, 10)` |\n", "| **Inspection** | `arr.shape`, `arr.ndim`, `arr.dtype`, `arr.size`, `arr.nbytes` | `arr.shape` -> `(3, 4)` |\n", "| **Reshaping** | `arr.reshape(-1)`, `arr.ravel()`, `arr.flatten()`, `arr.T`, `np.squeeze` | `arr.reshape(2, -1)` |\n", "| **Slicing** | `arr[start:stop:step]`, `arr[row_slice, col_slice]` | `arr[1:3, :]` |\n", "| **Filtering** | `arr[condition]`, `np.where(cond, x, y)`, `&`, `\\|`, `~` | `np.where(x > 0, x, 0)` |\n", "| **Math** | `np.exp`, `np.log`, `np.sqrt`, `np.sin`, `np.abs`, `np.clip` | `np.clip(arr, 0, 1)` |\n", "| **Aggregations** | `arr.sum(axis=...)`, `arr.mean()`, `arr.std()`, `arr.argmax()`, `keepdims=True` | `np.mean(mat, axis=0)` |\n", "| **Broadcasting** | Automatic dimension expansion from right to left | `(3, 4) + (4,) -> (3, 4)` |\n", "| **Stacking** | `np.vstack`, `np.hstack`, `np.concatenate(axis=...)` | `np.vstack([a, b])` |\n", "| **Linear Algebra** | `A @ B`, `np.linalg.solve(A, b)`, `np.linalg.norm(v)` | `A @ B` |\n", "| **Random (`rng`)** | `rng.random()`, `rng.integers()`, `rng.normal()`, `rng.choice()`, `rng.shuffle()`| `rng.normal(0, 1, 10)` |\n", "\n", "---\n", "### 🎯 Next Steps: Put Knowledge Into Practice!\n", "Deepen your understanding with our companion practice notebooks:\n", "- πŸ‹οΈ [02_numpy_exercise_1.ipynb](file:///Users/Inz_mac/Developer/ML/my-note/numpy/02_numpy_exercise_1.ipynb): 20 Hands-on exercises covering Array Creation, Slicing, and Reshaping.\n", "- πŸ’‘ [03_numpy_exercise_1_solutions.ipynb](file:///Users/Inz_mac/Developer/ML/my-note/numpy/03_numpy_exercise_1_solutions.ipynb): Complete worked solutions for Exercise 1.\n", "- πŸš€ [04_numpy_exercise_2.ipynb](file:///Users/Inz_mac/Developer/ML/my-note/numpy/04_numpy_exercise_2.ipynb): 15 Advanced problems covering Linear Algebra and ML Vectorization.\n", "- πŸ’‘ [05_numpy_exercise_2_solutions.ipynb](file:///Users/Inz_mac/Developer/ML/my-note/numpy/05_numpy_exercise_2_solutions.ipynb): Detailed solutions and vectorization derivations for Exercise 2." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.16" } }, "nbformat": 4, "nbformat_minor": 5 }