{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# For tips on running notebooks in Google Colab, see\n# https://pytorch.org/tutorials/beginner/colab\n%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Warm-up: numpy\n==============\n\nA third order polynomial, trained to predict $y=\\sin(x)$ from $-\\pi$ to\n$pi$ by minimizing squared Euclidean distance.\n\nThis implementation uses numpy to manually compute the forward pass,\nloss, and backward pass.\n\nA numpy array is a generic n-dimensional array; it does not know\nanything about deep learning or gradients or computational graphs, and\nis just a way to perform generic numeric computations.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nimport math\n\n# Create random input and output data\nx = np.linspace(-math.pi, math.pi, 2000)\ny = np.sin(x)\n\n# Randomly initialize weights\na = np.random.randn()\nb = np.random.randn()\nc = np.random.randn()\nd = np.random.randn()\n\nlearning_rate = 1e-6\nfor 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\nprint(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.10.12" } }, "nbformat": 4, "nbformat_minor": 0 }