{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\nBasic gradient descent (and reset)\n==================================\n\ndemonstration on how to compute a gradient and apply a basic gradient update\nrule to minimize some loss function\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import symjax\nimport symjax.tensor as T\nimport matplotlib.pyplot as plt\n\n# GRADIENT DESCENT\nz = T.Variable(3.0, dtype=\"float32\")\nloss = (z - 1) ** 2\ng_z = symjax.gradients(loss, [z])[0]\nsymjax.current_graph().add_updates({z: z - 0.1 * g_z})\n\ntrain = symjax.function(outputs=[loss, z], updates=symjax.get_updates())\n\nlosses = list()\nvalues = list()\nfor i in range(200):\n    if (i + 1) % 50 == 0:\n        symjax.reset_variables(\"*\")\n    a, b = train()\n    losses.append(a)\n    values.append(b)\n\nplt.figure()\n\nplt.subplot(121)\nplt.plot(losses, \"-x\")\nplt.ylabel(\"loss\")\nplt.xlabel(\"number of gradient updates\")\n\nplt.subplot(122)\nplt.plot(values, \"-x\")\nplt.axhline(1, c=\"red\")\nplt.ylabel(\"value\")\nplt.xlabel(\"number of gradient updates\")\n\nplt.tight_layout()"
      ]
    }
  ],
  "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.7.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}