{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Automatic Differentiation" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2019-07-03T21:50:54.398998Z", "start_time": "2019-07-03T21:50:53.307986Z" }, "attributes": { "classes": [], "id": "", "n": "1" } }, "outputs": [ { "data": { "text/plain": [ "array([0., 1., 2., 3.])" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from mxnet import autograd, np, npx \n", "npx.set_np()\n", "\n", "x = np.arange(4)\n", "x" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "Allocate space to store the gradient with respect to ``x``." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2019-07-03T21:50:54.404851Z", "start_time": "2019-07-03T21:50:54.401388Z" }, "attributes": { "classes": [], "id": "", "n": "3" } }, "outputs": [], "source": [ "x.attach_grad()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Record the computation within the `record` scope." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2019-07-03T21:50:54.416246Z", "start_time": "2019-07-03T21:50:54.406690Z" }, "attributes": { "classes": [], "id": "", "n": "4" }, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "array(28.)" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "with autograd.record():\n", " y = 2.0 * np.dot(x, x)\n", "y" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "The gradient of the function $y = 2\\mathbf{x}^{\\top}\\mathbf{x}$ with respect to $\\mathbf{x}$ should be $4\\mathbf{x}$. " ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2019-07-03T21:50:54.435955Z", "start_time": "2019-07-03T21:50:54.418269Z" }, "attributes": { "classes": [], "id": "", "n": "5" } }, "outputs": [ { "data": { "text/plain": [ "array([0., 0., 0., 0.])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y.backward()\n", "x.grad - 4 * x" ] } ], "metadata": { "celltoolbar": "Slideshow", "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.7.1" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }