{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Warm-up: numpy\n",
    "\n",
    "A third order polynomial, trained to predict $y=\\sin(x)$ from $-\\pi$ to\n",
    "$\\pi$ by minimizing squared Euclidean distance.\n",
    "\n",
    "This implementation uses numpy to manually compute the forward pass,\n",
    "loss, and backward pass.\n",
    "\n",
    "A numpy array is a generic n-dimensional array; it does not know\n",
    "anything about deep learning or gradients or computational graphs, and\n",
    "is just a way to perform generic numeric computations.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import math\n",
    "\n",
    "# Create random input and output data\n",
    "x = np.linspace(-math.pi, math.pi, 2000)\n",
    "y = np.sin(x)\n",
    "\n",
    "# Randomly initialize weights\n",
    "a = np.random.randn()\n",
    "b = np.random.randn()\n",
    "c = np.random.randn()\n",
    "d = np.random.randn()\n",
    "\n",
    "learning_rate = 1e-6\n",
    "for t in range(2000):\n",
    "    # Forward pass: compute predicted y\n",
    "    # y = a + b x + c x^2 + d x^3\n",
    "    y_pred = a + b * x + c * x ** 2 + d * x ** 3\n",
    "\n",
    "    # Compute and print loss\n",
    "    loss = np.square(y_pred - y).sum()\n",
    "    if t % 100 == 99:\n",
    "        print(t, loss)\n",
    "\n",
    "    # Backprop to compute gradients of a, b, c, d with respect to loss\n",
    "    grad_y_pred = 2.0 * (y_pred - y)\n",
    "    grad_a = grad_y_pred.sum()\n",
    "    grad_b = (grad_y_pred * x).sum()\n",
    "    grad_c = (grad_y_pred * x ** 2).sum()\n",
    "    grad_d = (grad_y_pred * x ** 3).sum()\n",
    "\n",
    "    # Update weights\n",
    "    a -= learning_rate * grad_a\n",
    "    b -= learning_rate * grad_b\n",
    "    c -= learning_rate * grad_c\n",
    "    d -= learning_rate * grad_d\n",
    "\n",
    "print(f'Result: y = {a} + {b} x + {c} x^2 + {d} x^3')"
   ]
  }
 ],
 "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.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
