{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# \ud83d\ude80 NumPy Practice Exercise 2: Advanced Operations, Linear Algebra & Machine Learning\n", "\n", "This notebook contains **15 advanced problems** reflecting real-world mathematical and machine learning implementations in NumPy:\n", "- Pairwise Euclidean distance & Cosine similarity\n", "- Numerically stable Softmax & Cross-entropy loss\n", "- One-hot encoding & Z-score normalization\n", "- Linear regression via the Normal Equation\n", "- PCA from scratch via Eigendecomposition\n", "- Top-K partition selection & Mini-batch generator\n", "- 2D Convolutions & Tensor channel reshaping\n", "\n", "### \ud83d\udcdd Instructions:\n", "- Write your solutions in the designated code cells.\n", "- Avoid slow Python loops where vectorized NumPy operations can be applied!\n", "- Solutions and derivations are available in `05_numpy_exercise_2_solutions.ipynb`.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 1: Vectorized Pairwise Euclidean Distance Matrix\n", "\n", "Given two matrices $X$ of shape $(N, D)$ and $Y$ of shape $(M, D)$, compute the full pairwise distance matrix of shape $(N, M)$ without any Python loops using broadcasting.\n", "\n", "Test with:\n", "- $X$: 4 points in 3D\n", "- $Y$: 5 points in 3D\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 2: Numerically Stable Softmax Function\n", "\n", "Write a function `softmax(logits, axis=-1)` that computes the softmax probabilities across any specified axis.\n", "Make sure it is **numerically stable** against large numbers (e.g. logits like 1000.0) by subtracting the maximum logit before computing exponents.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 3: Vectorized One-Hot Encoding\n", "\n", "Write a function `one_hot_encode(labels, num_classes)` that converts a 1D vector of integer class labels into a 2D binary indicator matrix of shape $(N, num\\_classes)$ using NumPy indexing.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 4: Z-Score Feature Standardization with `keepdims=True`\n", "\n", "Write a function `standardize(X)` that takes a 2D dataset of shape $(N, D)$ and centers each column to mean 0 and scales each column to standard deviation 1. Use `keepdims=True` and guard against division by zero (if std is 0).\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 5: Linear Regression via the Normal Equation\n", "\n", "Given feature matrix $X$ and target vector $y$, find the optimal weight vector $\\theta = [\\theta_0, \\theta_1, \\dots]^T$ using the closed-form Normal Equation:\n", "$$\\theta = (X_{b}^T X_b)^{-1} X_b^T y$$\n", "Where $X_b$ includes an initial bias column of ones.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 6: 1D Moving Average Filter via Convolution\n", "\n", "Given a noisy 1D signal, compute its moving average with a window size of $w=5$ using `np.convolve` in `'valid'` mode.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 7: Find Nearest Neighbor (k-NN core step)\n", "\n", "Given a dataset of 50 2D points and a query point $q = [2.5, 3.5]$, find:\n", "1. The index of the nearest point.\n", "2. The coordinates of that nearest point.\n", "3. The exact Euclidean distance to that point.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 8: Binary Cross-Entropy Loss with Clipping\n", "\n", "Write a function `binary_cross_entropy(y_true, y_pred, eps=1e-15)` that calculates binary cross-entropy loss:\n", "$$L = -\\frac{1}{N} \\sum [y \\log(p) + (1-y) \\log(1 - p)]$$\n", "Clip `y_pred` to `[eps, 1 - eps]` using `np.clip` to prevent `log(0)` returning `NaN` or `-inf`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 9: Efficient Top-K Extraction with `argpartition`\n", "\n", "Given an array of 10,000 random floating numbers, find the indices and values of the **top 5 largest numbers** in $O(N)$ expected time using `np.argpartition` without performing a full $O(N \\log N)$ sort.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 10: Image Tensor Channel Transposition & Grayscale Conversion\n", "\n", "Simulate a batch of 8 RGB images of size 64x64 with shape `(B, H, W, C) = (8, 64, 64, 3)` with random pixel intensities between 0 and 255.\n", "1. Transpose the tensor into PyTorch format `(B, C, H, W)`.\n", "2. Convert the original RGB batch to Grayscale with shape `(8, 64, 64)` using the standard luminance formula: $Y = 0.299 R + 0.587 G + 0.114 B$ using matrix dot product or broadcasting.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 11: Vectorized Cosine Similarity Matrix\n", "\n", "Given two matrices $A$ of shape $(N, D)$ and $B$ of shape $(M, D)$ containing embeddings, compute the full $N \\times M$ pairwise cosine similarity matrix without any Python loops:\n", "$$\\text{cosine\\_sim}(u, v) = \\frac{u \\cdot v}{\\|u\\|_2 \\|v\\|_2}$$\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 12: Polynomial Feature Expansion\n", "\n", "Given a 1D input array $x$ of length $N$, generate the polynomial feature matrix up to degree $d=3$:\n", "$$[1, x, x^2, x^3]$$\n", "Do this two ways:\n", "1. Using column stacking with exponentiation.\n", "2. Using `np.vander(x, N=4, increasing=True)`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 13: Principal Component Analysis (PCA) From Scratch\n", "\n", "Perform PCA on an $N \\times 4$ dataset from scratch:\n", "1. Center the features to zero mean.\n", "2. Compute the sample covariance matrix: $\\Sigma = \\frac{1}{N-1} X_c^T X_c$.\n", "3. Compute eigenvalues and eigenvectors using `np.linalg.eigh`.\n", "4. Sort the eigenvectors in descending order of eigenvalues.\n", "5. Project the data onto the first 2 principal components.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 14: Mini-Batch Generator for Stochastic Gradient Descent\n", "\n", "Write a Python generator function `get_batches(X, y, batch_size, shuffle=True)` that yields batches $(X_{batch}, y_{batch})$ of size `batch_size`. Ensure the indices are randomly permuted without copying the entire dataset up front.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 15: 2D Image Edge Detection (Convolution)\n", "\n", "Given an $8 \\times 8$ grayscale image and a $3 \\times 3$ Laplacian edge-detection kernel:\n", "$$K = \\begin{pmatrix} 0 & 1 & 0 \\\\ 1 & -4 & 1 \\\\ 0 & 1 & 0 \\end{pmatrix}$$\n", "Compute the $6 \\times 6$ valid convolution output without external libraries using vectorization or a sliding window.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your solution below\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.11.0" } }, "nbformat": 4, "nbformat_minor": 4 }