<commit_before>{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Working with the python DyNet package\n",
    "\n",
    "The DyNet package is intended for training and using neural networks, and is particularly suited for applications with dynamically changing network structures. It is a python-wrapper for the DyNet C++ package.\n",
    "\n",
    "In neural network packages there are generally two modes of operation:\n",
    "\n",
    "* __Static networks__, in which a network is built and then being fed with different inputs/outputs. Most NN packages work this way.\n",
    "* __Dynamic networks__, in which a new network is built for each training example (sharing parameters with the networks of other training examples).  This approach is what makes DyNet unique, and where most of its power comes from.\n",
    "\n",
    "We will describe both of these modes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Package Fundamentals\n",
    "\n",
    "The main piece of DyNet is the `ComputationGraph`, which is what essentially defines a neural network.\n",
    "The `ComputationGraph` is composed of expressions, which relate to the inputs and outputs of the network,\n",
    "as well as the `Parameters` of the network. The parameters are the things in the network that are optimized over time, and all of the parameters sit inside a `ParameterCollection`. There are `trainers` (for example `SimpleSGDTrainer`) that are in charge of setting the parameter values.\n",
    "\n",
    "We will not be using the `ComputationGraph` directly, but it is there in the background, as a singleton object.\n",
    "When `dynet` is imported, a new `ComputationGraph` is created. We can then reset the computation graph to a new state\n",
    "by calling `renew_cg()`.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Static Networks\n",
    "\n",
    "The life-cycle of a DyNet program is:\n",
    "1. Create a `ParameterCollection`, and populate it with `Parameters`.\n",
    "2. Renew the computation graph, and create `Expression` representing the network\n",
    "      (the network will include the `Expression`s for the `Parameters` defined in the parameter collection).\n",
    "3. Optimize the model for the objective of the network.\n",
    "\n",
    "As an example, consider a model for solving the \"xor\" problem. The network has two inputs, which can be 0 or 1, and a single output which should be the xor of the two inputs.\n",
    "We will model this as a multi-layer perceptron with a single hidden node.\n",
    "\n",
    "Let $x = x_1, x_2$ be our input. We will have a hidden layer of 8 nodes, and an output layer of a single node. The activation on the hidden layer will be a $\\tanh$. Our network will then be:\n",
    "\n",
    "$\\sigma(V(\\tanh(Wx+b)))$\n",
    "\n",
    "Where $W$ is a $8 \\times 2$ matrix, $V$ is an $8 \\times 1$ matrix, and $b$ is an 8-dim vector.\n",
    "\n",
    "We want the output to be either 0 or 1, so we take the output layer to be the logistic-sigmoid function, $\\sigma(x)$, that takes values between $-\\infty$ and $+\\infty$ and returns numbers in $[0,1]$.\n",
    "\n",
    "We will begin by defining the model and the computation graph.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# we assume that we have the dynet module in your path.\n",
    "# OUTDATED: we also assume that LD_LIBRARY_PATH includes a pointer to where libcnn_shared.so is.\n",
    "import dynet as dy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# create a parameter collection and add the parameters.\n",
    "m = dy.ParameterCollection()\n",
    "pW = m.add_parameters((8,2))\n",
    "pV = m.add_parameters((1,8))\n",
    "pb = m.add_parameters((8))\n",
    "\n",
    "renew_cg() # new computation graph. not strictly needed here, but good practice.\n",
    "\n",
    "# associate the parameters with cg Expressions\n",
    "W = parameter(pW)\n",
    "V = parameter(pV)\n",
    "b = parameter(pb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[-0.5920619964599609,\n",
       " -0.4818088114261627,\n",
       " -0.011437613517045975,\n",
       " -0.7547096610069275,\n",
       " 0.2887613773345947,\n",
       " -0.39806437492370605,\n",
       " -0.8494511246681213,\n",
       " 0.295582115650177]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#b[1:-1].value()\n",
    "b.value()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first block creates a parameter collection and populates it with parameters.\n",
    "The second block creates a computation graph and adds the parameters to it, transforming them into `Expression`s.\n",
    "The need to distinguish model parameters from \"expressions\" will become clearer later.\n",
    "\n",
    "We now make use of the W and V expressions, in order to create the complete expression for the network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = vecInput(2) # an input vector of size 2. Also an expression.\n",
    "output = logistic(V*(tanh((W*x)+b)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.706532895565033"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# we can now query our network\n",
    "x.set([0,0])\n",
    "output.value()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# we want to be able to define a loss, so we need an input expression to work against.\n",
    "y = scalarInput(0) # this will hold the correct answer\n",
    "loss = binary_log_loss(output, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.25551486015\n",
      "0.335373580456\n"
     ]
    }
   ],
   "source": [
    "x.set([1,0])\n",
    "y.set(0)\n",
    "print loss.value()\n",
    "\n",
    "y.set(1)\n",
    "print loss.value()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training\n",
    "We now want to set the parameter weights such that the loss is minimized. \n",
    "\n",
    "For this, we will use a trainer object. A trainer is constructed with respect to the parameters of a given model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "trainer = SimpleSGDTrainer(m)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To use the trainer, we need to:\n",
    "* **call the `forward_scalar`** method of `ComputationGraph`. This will run a forward pass through the network, calculating all the intermediate values until the last one (`loss`, in our case), and then convert the value to a scalar. The final output of our network **must** be a single scalar value. However, if we do not care about the value, we can just use `cg.forward()` instead of `cg.forward_sclar()`.\n",
    "* **call the `backward`** method of `ComputationGraph`. This will run a backward pass from the last node, calculating the gradients with respect to minimizing the last expression (in our case we want to minimize the loss). The gradients are stored in the parameter collection, and we can now let the `trainer` take care of the optimization step.\n",
    "* **call `trainer.update()`** to optimize the values with respect to the latest gradients."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "the loss before step is: 0.335373580456\n",
      "the loss after step is: 0.296859383583\n"
     ]
    }
   ],
   "source": [
    "x.set([1,0])\n",
    "y.set(1)\n",
    "loss_value = loss.value() # this performs a forward through the network.\n",
    "print \"the loss before step is:\",loss_value\n",
    "\n",
    "# now do an optimization step\n",
    "loss.backward()  # compute the gradients\n",
    "trainer.update()\n",
    "\n",
    "# see how it affected the loss:\n",
    "loss_value = loss.value(recalculate=True) # recalculate=True means \"don't use precomputed value\"\n",
    "print \"the loss after step is:\",loss_value\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The optimization step indeed made the loss decrease. We now need to run this in a loop.\n",
    "To this end, we will create a `training set`, and iterate over it.\n",
    "\n",
    "For the xor problem, the training instances are easy to create."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def create_xor_instances(num_rounds=2000):\n",
    "    questions = []\n",
    "    answers = []\n",
    "    for round in xrange(num_rounds):\n",
    "        for x1 in 0,1:\n",
    "            for x2 in 0,1:\n",
    "                answer = 0 if x1==x2 else 1\n",
    "                questions.append((x1,x2))\n",
    "                answers.append(answer)\n",
    "    return questions, answers \n",
    "\n",
    "questions, answers = create_xor_instances()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now feed each question / answer pair to the network, and try to minimize the loss.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "average loss is: 0.730996069312\n",
      "average loss is: 0.686455376148\n",
      "average loss is: 0.614968097508\n",
      "average loss is: 0.529396591447\n",
      "average loss is: 0.454356552631\n",
      "average loss is: 0.39492503399\n",
      "average loss is: 0.348310606687\n",
      "average loss is: 0.311234809482\n",
      "average loss is: 0.281200638587\n",
      "average loss is: 0.256437818106\n",
      "average loss is: 0.235696636033\n",
      "average loss is: 0.218082525641\n",
      "average loss is: 0.202943060785\n",
      "average loss is: 0.189793206944\n",
      "average loss is: 0.178265773896\n",
      "average loss is: 0.168078109015\n",
      "average loss is: 0.15900931143\n",
      "average loss is: 0.150884356805\n",
      "average loss is: 0.143562835396\n",
      "average loss is: 0.136930837112\n",
      "average loss is: 0.130894997159\n",
      "average loss is: 0.125378077089\n",
      "average loss is: 0.120315633187\n",
      "average loss is: 0.115653475622\n",
      "average loss is: 0.111345707807\n",
      "average loss is: 0.107353201057\n",
      "average loss is: 0.103642390902\n",
      "average loss is: 0.100184321725\n",
      "average loss is: 0.0969538828368\n",
      "average loss is: 0.0939291894056\n",
      "average loss is: 0.0910910811149\n",
      "average loss is: 0.0884227104994\n",
      "average loss is: 0.0859092032744\n",
      "average loss is: 0.0835373785728\n",
      "average loss is: 0.0812955136038\n",
      "average loss is: 0.0791731475857\n",
      "average loss is: 0.0771609158713\n",
      "average loss is: 0.0752504101568\n",
      "average loss is: 0.0734340592178\n",
      "average loss is: 0.0717050271845\n",
      "average loss is: 0.0700571256665\n",
      "average loss is: 0.0684847396141\n",
      "average loss is: 0.0669827620572\n",
      "average loss is: 0.0655465372522\n",
      "average loss is: 0.0641718128339\n",
      "average loss is: 0.0628546962203\n",
      "average loss is: 0.0615916178524\n",
      "average loss is: 0.0603792975615\n",
      "average loss is: 0.0592147165184\n",
      "average loss is: 0.0580950913344\n",
      "average loss is: 0.0570178513814\n",
      "average loss is: 0.0559806190546\n",
      "average loss is: 0.0549811920022\n",
      "average loss is: 0.0540175269391\n",
      "average loss is: 0.0530877257938\n",
      "average loss is: 0.0521900229302\n",
      "average loss is: 0.0513227736969\n",
      "average loss is: 0.0504844442235\n",
      "average loss is: 0.0496736022536\n",
      "average loss is: 0.0488889090025\n",
      "average loss is: 0.0481291114653\n",
      "average loss is: 0.0473930355647\n",
      "average loss is: 0.0466795804093\n",
      "average loss is: 0.0459877123818\n",
      "average loss is: 0.0453164599289\n",
      "average loss is: 0.0446649091876\n",
      "average loss is: 0.0440321997496\n",
      "average loss is: 0.0434175205679\n",
      "average loss is: 0.0428201068594\n",
      "average loss is: 0.042239236579\n",
      "average loss is: 0.041674227424\n",
      "average loss is: 0.0411244342562\n",
      "average loss is: 0.0405892467939\n",
      "average loss is: 0.0400680867989\n",
      "average loss is: 0.0395604063634\n",
      "average loss is: 0.0390656857708\n",
      "average loss is: 0.0385834318376\n",
      "average loss is: 0.0381131761705\n",
      "average loss is: 0.037654473684\n",
      "average loss is: 0.0372069010154\n"
     ]
    }
   ],
   "source": [
    "total_loss = 0\n",
    "seen_instances = 0\n",
    "for question, answer in zip(questions, answers):\n",
    "    x.set(question)\n",
    "    y.set(answer)\n",
    "    seen_instances += 1\n",
    "    total_loss += loss.value()\n",
    "    loss.backward()\n",
    "    trainer.update()\n",
    "    if (seen_instances > 1 and seen_instances % 100 == 0):\n",
    "        print \"average loss is:\",total_loss / seen_instances\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our network is now trained. Let's verify that it indeed learned the xor function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0,1 0.998090803623\n",
      "1,0 0.998076915741\n",
      "0,0 0.00135990511626\n",
      "1,1 0.00213058013469\n"
     ]
    }
   ],
   "source": [
    "x.set([0,1])\n",
    "print \"0,1\",output.value()\n",
    "\n",
    "x.set([1,0])\n",
    "print \"1,0\",output.value()\n",
    "\n",
    "x.set([0,0])\n",
    "print \"0,0\",output.value()\n",
    "\n",
    "x.set([1,1])\n",
    "print \"1,1\",output.value()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In case we are curious about the parameter values, we can query them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.26847982,  1.25287616],\n",
       "       [ 0.91610891,  0.80253637],\n",
       "       [ 3.18741179, -2.58643913],\n",
       "       [-0.82472938, -0.68830448],\n",
       "       [-2.74162889,  3.30151606],\n",
       "       [ 0.2677069 ,  0.46926948],\n",
       "       [-2.60197234, -2.61786079],\n",
       "       [ 0.89582258, -0.44721049]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "W.value()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-2.33788562, -1.54022419, -4.58266163, -0.91096258, -4.88002253,\n",
       "        -0.70912606, -4.09791088, -0.61150461]])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "V.value()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[-1.9798537492752075,\n",
       " -1.3854612112045288,\n",
       " 1.2350027561187744,\n",
       " -0.8094932436943054,\n",
       " 1.3227168321609497,\n",
       " -0.5688062906265259,\n",
       " 0.9074684381484985,\n",
       " 0.21831640601158142]"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b.value()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### To summarize\n",
    "Here is a complete program:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "average loss is: 0.725458401442\n",
      "average loss is: 0.656036808193\n",
      "average loss is: 0.563800293456\n",
      "average loss is: 0.473188629244\n",
      "average loss is: 0.401578919515\n",
      "average loss is: 0.347210133697\n",
      "average loss is: 0.30537398648\n",
      "average loss is: 0.27243115149\n",
      "average loss is: 0.245902155418\n",
      "average loss is: 0.22411154042\n",
      "average loss is: 0.205906257995\n",
      "average loss is: 0.190473453378\n",
      "average loss is: 0.177226172269\n",
      "average loss is: 0.165731058566\n",
      "average loss is: 0.155661680364\n",
      "average loss is: 0.146767699362\n",
      "average loss is: 0.138854031509\n",
      "average loss is: 0.131766459678\n",
      "average loss is: 0.125381493949\n",
      "average loss is: 0.119599098227\n",
      "average loss is: 0.114337381247\n",
      "average loss is: 0.109528665657\n",
      "average loss is: 0.105116533384\n",
      "average loss is: 0.101053577985\n",
      "average loss is: 0.0972996741069\n",
      "average loss is: 0.093820632044\n",
      "average loss is: 0.0905871372991\n",
      "average loss is: 0.0875739114509\n",
      "average loss is: 0.0847590394488\n",
      "average loss is: 0.0821234288742\n",
      "average loss is: 0.079650368163\n",
      "average loss is: 0.0773251660003\n",
      "average loss is: 0.0751348558335\n",
      "average loss is: 0.0730679483965\n",
      "average loss is: 0.0711142273374\n",
      "average loss is: 0.0692645774255\n",
      "average loss is: 0.0675108397355\n",
      "average loss is: 0.0658456894337\n",
      "average loss is: 0.0642625315812\n",
      "average loss is: 0.0627554119665\n",
      "average loss is: 0.0613189413034\n",
      "average loss is: 0.059948229676\n",
      "average loss is: 0.0586388300699\n",
      "average loss is: 0.05738668844\n",
      "average loss is: 0.0561881021362\n",
      "average loss is: 0.0550396820511\n",
      "average loss is: 0.0539383201534\n",
      "average loss is: 0.0528811609025\n",
      "average loss is: 0.0518655761557\n",
      "average loss is: 0.0508891425877\n",
      "average loss is: 0.0499496224367\n",
      "average loss is: 0.0490449456893\n",
      "average loss is: 0.0481731953563\n",
      "average loss is: 0.0473325925335\n",
      "average loss is: 0.0465214848134\n",
      "average loss is: 0.0457383351514\n",
      "average loss is: 0.0449817118815\n",
      "average loss is: 0.0442502796927\n",
      "average loss is: 0.0435427918518\n",
      "average loss is: 0.0428580828441\n",
      "average loss is: 0.0421950617608\n",
      "average loss is: 0.0415527067172\n",
      "average loss is: 0.0409300591527\n",
      "average loss is: 0.0403262192239\n",
      "average loss is: 0.0397403411381\n",
      "average loss is: 0.0391716292271\n",
      "average loss is: 0.0386193343495\n",
      "average loss is: 0.0380827505725\n",
      "average loss is: 0.0375612118193\n",
      "average loss is: 0.0370540894219\n",
      "average loss is: 0.0365607894682\n",
      "average loss is: 0.0360807502221\n",
      "average loss is: 0.0356134402267\n",
      "average loss is: 0.0351583559568\n",
      "average loss is: 0.0347150203697\n",
      "average loss is: 0.0342829808685\n",
      "average loss is: 0.0338618080745\n",
      "average loss is: 0.0334510939502\n",
      "average loss is: 0.0330504509121\n",
      "average loss is: 0.0326595103741\n"
     ]
    }
   ],
   "source": [
    "# define the parameters\n",
    "m = ParameterCollection()\n",
    "pW = m.add_parameters((8,2))\n",
    "pV = m.add_parameters((1,8))\n",
    "pb = m.add_parameters((8))\n",
    "\n",
    "# renew the computation graph\n",
    "renew_cg()\n",
    "\n",
    "# add the parameters to the graph\n",
    "W = parameter(pW)\n",
    "V = parameter(pV)\n",
    "b = parameter(pb)\n",
    "\n",
    "# create the network\n",
    "x = vecInput(2) # an input vector of size 2.\n",
    "output = logistic(V*(tanh((W*x)+b)))\n",
    "# define the loss with respect to an output y.\n",
    "y = scalarInput(0) # this will hold the correct answer\n",
    "loss = binary_log_loss(output, y)\n",
    "\n",
    "# create training instances\n",
    "def create_xor_instances(num_rounds=2000):\n",
    "    questions = []\n",
    "    answers = []\n",
    "    for round in xrange(num_rounds):\n",
    "        for x1 in 0,1:\n",
    "            for x2 in 0,1:\n",
    "                answer = 0 if x1==x2 else 1\n",
    "                questions.append((x1,x2))\n",
    "                answers.append(answer)\n",
    "    return questions, answers \n",
    "\n",
    "questions, answers = create_xor_instances()\n",
    "\n",
    "# train the network\n",
    "trainer = SimpleSGDTrainer(m)\n",
    "\n",
    "total_loss = 0\n",
    "seen_instances = 0\n",
    "for question, answer in zip(questions, answers):\n",
    "    x.set(question)\n",
    "    y.set(answer)\n",
    "    seen_instances += 1\n",
    "    total_loss += loss.value()\n",
    "    loss.backward()\n",
    "    trainer.update()\n",
    "    if (seen_instances > 1 and seen_instances % 100 == 0):\n",
    "        print \"average loss is:\",total_loss / seen_instances\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dynamic Networks\n",
    "\n",
    "Dynamic networks are very similar to static ones, but instead of creating the network once and then calling \"set\" in each training example to change the inputs, we just create a new network for each training example.\n",
    "\n",
    "We present an example below. While the value of this may not be clear in the `xor` example, the dynamic approach\n",
    "is very convenient for networks for which the structure is not fixed, such as recurrent or recursive networks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "average loss is: 0.736730417013\n",
      "average loss is: 0.725369692743\n",
      "average loss is: 0.715208243926\n",
      "average loss is: 0.698906037733\n",
      "average loss is: 0.667973376453\n",
      "average loss is: 0.620016210104\n",
      "average loss is: 0.564173455558\n",
      "average loss is: 0.511108190748\n",
      "average loss is: 0.464656613212\n",
      "average loss is: 0.424903827408\n",
      "average loss is: 0.390944672838\n",
      "average loss is: 0.361782596097\n",
      "average loss is: 0.336552875967\n",
      "average loss is: 0.314552738269\n",
      "average loss is: 0.295221981726\n",
      "average loss is: 0.27811523865\n",
      "average loss is: 0.262876965393\n",
      "average loss is: 0.249221329002\n",
      "average loss is: 0.236916671552\n",
      "average loss is: 0.225773662324\n",
      "average loss is: 0.215636288271\n",
      "average loss is: 0.206374970573\n",
      "average loss is: 0.197881278039\n",
      "average loss is: 0.190063834667\n",
      "average loss is: 0.182845127269\n",
      "average loss is: 0.176158992879\n",
      "average loss is: 0.16994863152\n",
      "average loss is: 0.164165015582\n",
      "average loss is: 0.158765610311\n",
      "average loss is: 0.153713339384\n",
      "average loss is: 0.148975738776\n",
      "average loss is: 0.14452426397\n",
      "average loss is: 0.140333718062\n",
      "average loss is: 0.13638177571\n",
      "average loss is: 0.132648585576\n",
      "average loss is: 0.129116437846\n",
      "average loss is: 0.125769484215\n",
      "average loss is: 0.122593499324\n",
      "average loss is: 0.119575678358\n",
      "average loss is: 0.116704463887\n",
      "average loss is: 0.113969398874\n",
      "average loss is: 0.111360997359\n",
      "average loss is: 0.108870635643\n",
      "average loss is: 0.106490455879\n",
      "average loss is: 0.104213282756\n",
      "average loss is: 0.102032551605\n",
      "average loss is: 0.0999422444205\n",
      "average loss is: 0.0979368338955\n",
      "average loss is: 0.0960112348951\n",
      "average loss is: 0.094160760665\n",
      "average loss is: 0.0923810851444\n",
      "average loss is: 0.0906682085468\n",
      "average loss is: 0.0890184267577\n",
      "average loss is: 0.0874283051604\n",
      "average loss is: 0.0858946543594\n",
      "average loss is: 0.0844145084265\n",
      "average loss is: 0.0829851059784\n",
      "average loss is: 0.0816038727351\n",
      "average loss is: 0.0802684055211\n",
      "average loss is: 0.0789764590814\n",
      "average loss is: 0.0777259325812\n",
      "average loss is: 0.0765148587798\n",
      "average loss is: 0.0753413928689\n",
      "average loss is: 0.0742038039022\n",
      "average loss is: 0.073100465403\n",
      "average loss is: 0.072029847966\n",
      "average loss is: 0.0709905121502\n",
      "average loss is: 0.0699811016467\n",
      "average loss is: 0.0690003377412\n",
      "average loss is: 0.0680470136383\n",
      "average loss is: 0.0671199895066\n",
      "average loss is: 0.0662181878878\n",
      "average loss is: 0.0653405894968\n",
      "average loss is: 0.0644862291951\n",
      "average loss is: 0.0636541927901\n",
      "average loss is: 0.0628436133573\n",
      "average loss is: 0.062053668331\n",
      "average loss is: 0.0612835769022\n",
      "average loss is: 0.0605325971122\n",
      "average loss is: 0.0598000235481\n"
     ]
    }
   ],
   "source": [
    "import dynet as dy\n",
    "# create training instances, as before\n",
    "def create_xor_instances(num_rounds=2000):\n",
    "    questions = []\n",
    "    answers = []\n",
    "    for round in xrange(num_rounds):\n",
    "        for x1 in 0,1:\n",
    "            for x2 in 0,1:\n",
    "                answer = 0 if x1==x2 else 1\n",
    "                questions.append((x1,x2))\n",
    "                answers.append(answer)\n",
    "    return questions, answers \n",
    "\n",
    "questions, answers = create_xor_instances()\n",
    "\n",
    "# create a network for the xor problem given input and output\n",
    "def create_xor_network(pW, pV, pb, inputs, expected_answer):\n",
    "    dy.renew_cg() # new computation graph\n",
    "    W = dy.parameter(pW) # add parameters to graph as expressions\n",
    "    V = dy.parameter(pV)\n",
    "    b = dy.parameter(pb)\n",
    "    x = dy.vecInput(len(inputs))\n",
    "    x.set(inputs)\n",
    "    y = dy.scalarInput(expected_answer)\n",
    "    output = dy.logistic(V*(dy.tanh((W*x)+b)))\n",
    "    loss =  dy.binary_log_loss(output, y)\n",
    "    return loss\n",
    "\n",
    "m2 = dy.ParameterCollection()\n",
    "pW = m2.add_parameters((8,2))\n",
    "pV = m2.add_parameters((1,8))\n",
    "pb = m2.add_parameters((8))\n",
    "trainer = dy.SimpleSGDTrainer(m2)\n",
    "\n",
    "seen_instances = 0\n",
    "total_loss = 0\n",
    "for question, answer in zip(questions, answers):\n",
    "    loss = create_xor_network(pW, pV, pb, question, answer)\n",
    "    seen_instances += 1\n",
    "    total_loss += loss.value()\n",
    "    loss.backward()\n",
    "    trainer.update()\n",
    "    if (seen_instances > 1 and seen_instances % 100 == 0):\n",
    "        print \"average loss is:\",total_loss / seen_instances\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
<commit_msg>Fix typo in tutorial-1-xor.ipynb (#946)<commit_after>{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Working with the python DyNet package\n",
    "\n",
    "The DyNet package is intended for training and using neural networks, and is particularly suited for applications with dynamically changing network structures. It is a python-wrapper for the DyNet C++ package.\n",
    "\n",
    "In neural network packages there are generally two modes of operation:\n",
    "\n",
    "* __Static networks__, in which a network is built and then being fed with different inputs/outputs. Most NN packages work this way.\n",
    "* __Dynamic networks__, in which a new network is built for each training example (sharing parameters with the networks of other training examples).  This approach is what makes DyNet unique, and where most of its power comes from.\n",
    "\n",
    "We will describe both of these modes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Package Fundamentals\n",
    "\n",
    "The main piece of DyNet is the `ComputationGraph`, which is what essentially defines a neural network.\n",
    "The `ComputationGraph` is composed of expressions, which relate to the inputs and outputs of the network,\n",
    "as well as the `Parameters` of the network. The parameters are the things in the network that are optimized over time, and all of the parameters sit inside a `ParameterCollection`. There are `trainers` (for example `SimpleSGDTrainer`) that are in charge of setting the parameter values.\n",
    "\n",
    "We will not be using the `ComputationGraph` directly, but it is there in the background, as a singleton object.\n",
    "When `dynet` is imported, a new `ComputationGraph` is created. We can then reset the computation graph to a new state\n",
    "by calling `renew_cg()`.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Static Networks\n",
    "\n",
    "The life-cycle of a DyNet program is:\n",
    "1. Create a `ParameterCollection`, and populate it with `Parameters`.\n",
    "2. Renew the computation graph, and create `Expression` representing the network\n",
    "      (the network will include the `Expression`s for the `Parameters` defined in the parameter collection).\n",
    "3. Optimize the model for the objective of the network.\n",
    "\n",
    "As an example, consider a model for solving the \"xor\" problem. The network has two inputs, which can be 0 or 1, and a single output which should be the xor of the two inputs.\n",
    "We will model this as a multi-layer perceptron with a single hidden layer.\n",
    "\n",
    "Let $x = x_1, x_2$ be our input. We will have a hidden layer of 8 nodes, and an output layer of a single node. The activation on the hidden layer will be a $\\tanh$. Our network will then be:\n",
    "\n",
    "$\\sigma(V(\\tanh(Wx+b)))$\n",
    "\n",
    "Where $W$ is a $8 \\times 2$ matrix, $V$ is an $8 \\times 1$ matrix, and $b$ is an 8-dim vector.\n",
    "\n",
    "We want the output to be either 0 or 1, so we take the output layer to be the logistic-sigmoid function, $\\sigma(x)$, that takes values between $-\\infty$ and $+\\infty$ and returns numbers in $[0,1]$.\n",
    "\n",
    "We will begin by defining the model and the computation graph.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# we assume that we have the dynet module in your path.\n",
    "# OUTDATED: we also assume that LD_LIBRARY_PATH includes a pointer to where libcnn_shared.so is.\n",
    "import dynet as dy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# create a parameter collection and add the parameters.\n",
    "m = dy.ParameterCollection()\n",
    "pW = m.add_parameters((8,2))\n",
    "pV = m.add_parameters((1,8))\n",
    "pb = m.add_parameters((8))\n",
    "\n",
    "renew_cg() # new computation graph. not strictly needed here, but good practice.\n",
    "\n",
    "# associate the parameters with cg Expressions\n",
    "W = parameter(pW)\n",
    "V = parameter(pV)\n",
    "b = parameter(pb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[-0.5920619964599609,\n",
       " -0.4818088114261627,\n",
       " -0.011437613517045975,\n",
       " -0.7547096610069275,\n",
       " 0.2887613773345947,\n",
       " -0.39806437492370605,\n",
       " -0.8494511246681213,\n",
       " 0.295582115650177]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#b[1:-1].value()\n",
    "b.value()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first block creates a parameter collection and populates it with parameters.\n",
    "The second block creates a computation graph and adds the parameters to it, transforming them into `Expression`s.\n",
    "The need to distinguish model parameters from \"expressions\" will become clearer later.\n",
    "\n",
    "We now make use of the W and V expressions, in order to create the complete expression for the network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "x = vecInput(2) # an input vector of size 2. Also an expression.\n",
    "output = logistic(V*(tanh((W*x)+b)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.706532895565033"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# we can now query our network\n",
    "x.set([0,0])\n",
    "output.value()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# we want to be able to define a loss, so we need an input expression to work against.\n",
    "y = scalarInput(0) # this will hold the correct answer\n",
    "loss = binary_log_loss(output, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.25551486015\n",
      "0.335373580456\n"
     ]
    }
   ],
   "source": [
    "x.set([1,0])\n",
    "y.set(0)\n",
    "print loss.value()\n",
    "\n",
    "y.set(1)\n",
    "print loss.value()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training\n",
    "We now want to set the parameter weights such that the loss is minimized. \n",
    "\n",
    "For this, we will use a trainer object. A trainer is constructed with respect to the parameters of a given model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "trainer = SimpleSGDTrainer(m)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To use the trainer, we need to:\n",
    "* **call the `forward_scalar`** method of `ComputationGraph`. This will run a forward pass through the network, calculating all the intermediate values until the last one (`loss`, in our case), and then convert the value to a scalar. The final output of our network **must** be a single scalar value. However, if we do not care about the value, we can just use `cg.forward()` instead of `cg.forward_sclar()`.\n",
    "* **call the `backward`** method of `ComputationGraph`. This will run a backward pass from the last node, calculating the gradients with respect to minimizing the last expression (in our case we want to minimize the loss). The gradients are stored in the parameter collection, and we can now let the `trainer` take care of the optimization step.\n",
    "* **call `trainer.update()`** to optimize the values with respect to the latest gradients."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "the loss before step is: 0.335373580456\n",
      "the loss after step is: 0.296859383583\n"
     ]
    }
   ],
   "source": [
    "x.set([1,0])\n",
    "y.set(1)\n",
    "loss_value = loss.value() # this performs a forward through the network.\n",
    "print \"the loss before step is:\",loss_value\n",
    "\n",
    "# now do an optimization step\n",
    "loss.backward()  # compute the gradients\n",
    "trainer.update()\n",
    "\n",
    "# see how it affected the loss:\n",
    "loss_value = loss.value(recalculate=True) # recalculate=True means \"don't use precomputed value\"\n",
    "print \"the loss after step is:\",loss_value\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The optimization step indeed made the loss decrease. We now need to run this in a loop.\n",
    "To this end, we will create a `training set`, and iterate over it.\n",
    "\n",
    "For the xor problem, the training instances are easy to create."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def create_xor_instances(num_rounds=2000):\n",
    "    questions = []\n",
    "    answers = []\n",
    "    for round in xrange(num_rounds):\n",
    "        for x1 in 0,1:\n",
    "            for x2 in 0,1:\n",
    "                answer = 0 if x1==x2 else 1\n",
    "                questions.append((x1,x2))\n",
    "                answers.append(answer)\n",
    "    return questions, answers \n",
    "\n",
    "questions, answers = create_xor_instances()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now feed each question / answer pair to the network, and try to minimize the loss.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "average loss is: 0.730996069312\n",
      "average loss is: 0.686455376148\n",
      "average loss is: 0.614968097508\n",
      "average loss is: 0.529396591447\n",
      "average loss is: 0.454356552631\n",
      "average loss is: 0.39492503399\n",
      "average loss is: 0.348310606687\n",
      "average loss is: 0.311234809482\n",
      "average loss is: 0.281200638587\n",
      "average loss is: 0.256437818106\n",
      "average loss is: 0.235696636033\n",
      "average loss is: 0.218082525641\n",
      "average loss is: 0.202943060785\n",
      "average loss is: 0.189793206944\n",
      "average loss is: 0.178265773896\n",
      "average loss is: 0.168078109015\n",
      "average loss is: 0.15900931143\n",
      "average loss is: 0.150884356805\n",
      "average loss is: 0.143562835396\n",
      "average loss is: 0.136930837112\n",
      "average loss is: 0.130894997159\n",
      "average loss is: 0.125378077089\n",
      "average loss is: 0.120315633187\n",
      "average loss is: 0.115653475622\n",
      "average loss is: 0.111345707807\n",
      "average loss is: 0.107353201057\n",
      "average loss is: 0.103642390902\n",
      "average loss is: 0.100184321725\n",
      "average loss is: 0.0969538828368\n",
      "average loss is: 0.0939291894056\n",
      "average loss is: 0.0910910811149\n",
      "average loss is: 0.0884227104994\n",
      "average loss is: 0.0859092032744\n",
      "average loss is: 0.0835373785728\n",
      "average loss is: 0.0812955136038\n",
      "average loss is: 0.0791731475857\n",
      "average loss is: 0.0771609158713\n",
      "average loss is: 0.0752504101568\n",
      "average loss is: 0.0734340592178\n",
      "average loss is: 0.0717050271845\n",
      "average loss is: 0.0700571256665\n",
      "average loss is: 0.0684847396141\n",
      "average loss is: 0.0669827620572\n",
      "average loss is: 0.0655465372522\n",
      "average loss is: 0.0641718128339\n",
      "average loss is: 0.0628546962203\n",
      "average loss is: 0.0615916178524\n",
      "average loss is: 0.0603792975615\n",
      "average loss is: 0.0592147165184\n",
      "average loss is: 0.0580950913344\n",
      "average loss is: 0.0570178513814\n",
      "average loss is: 0.0559806190546\n",
      "average loss is: 0.0549811920022\n",
      "average loss is: 0.0540175269391\n",
      "average loss is: 0.0530877257938\n",
      "average loss is: 0.0521900229302\n",
      "average loss is: 0.0513227736969\n",
      "average loss is: 0.0504844442235\n",
      "average loss is: 0.0496736022536\n",
      "average loss is: 0.0488889090025\n",
      "average loss is: 0.0481291114653\n",
      "average loss is: 0.0473930355647\n",
      "average loss is: 0.0466795804093\n",
      "average loss is: 0.0459877123818\n",
      "average loss is: 0.0453164599289\n",
      "average loss is: 0.0446649091876\n",
      "average loss is: 0.0440321997496\n",
      "average loss is: 0.0434175205679\n",
      "average loss is: 0.0428201068594\n",
      "average loss is: 0.042239236579\n",
      "average loss is: 0.041674227424\n",
      "average loss is: 0.0411244342562\n",
      "average loss is: 0.0405892467939\n",
      "average loss is: 0.0400680867989\n",
      "average loss is: 0.0395604063634\n",
      "average loss is: 0.0390656857708\n",
      "average loss is: 0.0385834318376\n",
      "average loss is: 0.0381131761705\n",
      "average loss is: 0.037654473684\n",
      "average loss is: 0.0372069010154\n"
     ]
    }
   ],
   "source": [
    "total_loss = 0\n",
    "seen_instances = 0\n",
    "for question, answer in zip(questions, answers):\n",
    "    x.set(question)\n",
    "    y.set(answer)\n",
    "    seen_instances += 1\n",
    "    total_loss += loss.value()\n",
    "    loss.backward()\n",
    "    trainer.update()\n",
    "    if (seen_instances > 1 and seen_instances % 100 == 0):\n",
    "        print \"average loss is:\",total_loss / seen_instances\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our network is now trained. Let's verify that it indeed learned the xor function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0,1 0.998090803623\n",
      "1,0 0.998076915741\n",
      "0,0 0.00135990511626\n",
      "1,1 0.00213058013469\n"
     ]
    }
   ],
   "source": [
    "x.set([0,1])\n",
    "print \"0,1\",output.value()\n",
    "\n",
    "x.set([1,0])\n",
    "print \"1,0\",output.value()\n",
    "\n",
    "x.set([0,0])\n",
    "print \"0,0\",output.value()\n",
    "\n",
    "x.set([1,1])\n",
    "print \"1,1\",output.value()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In case we are curious about the parameter values, we can query them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.26847982,  1.25287616],\n",
       "       [ 0.91610891,  0.80253637],\n",
       "       [ 3.18741179, -2.58643913],\n",
       "       [-0.82472938, -0.68830448],\n",
       "       [-2.74162889,  3.30151606],\n",
       "       [ 0.2677069 ,  0.46926948],\n",
       "       [-2.60197234, -2.61786079],\n",
       "       [ 0.89582258, -0.44721049]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "W.value()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-2.33788562, -1.54022419, -4.58266163, -0.91096258, -4.88002253,\n",
       "        -0.70912606, -4.09791088, -0.61150461]])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "V.value()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[-1.9798537492752075,\n",
       " -1.3854612112045288,\n",
       " 1.2350027561187744,\n",
       " -0.8094932436943054,\n",
       " 1.3227168321609497,\n",
       " -0.5688062906265259,\n",
       " 0.9074684381484985,\n",
       " 0.21831640601158142]"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b.value()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### To summarize\n",
    "Here is a complete program:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "average loss is: 0.725458401442\n",
      "average loss is: 0.656036808193\n",
      "average loss is: 0.563800293456\n",
      "average loss is: 0.473188629244\n",
      "average loss is: 0.401578919515\n",
      "average loss is: 0.347210133697\n",
      "average loss is: 0.30537398648\n",
      "average loss is: 0.27243115149\n",
      "average loss is: 0.245902155418\n",
      "average loss is: 0.22411154042\n",
      "average loss is: 0.205906257995\n",
      "average loss is: 0.190473453378\n",
      "average loss is: 0.177226172269\n",
      "average loss is: 0.165731058566\n",
      "average loss is: 0.155661680364\n",
      "average loss is: 0.146767699362\n",
      "average loss is: 0.138854031509\n",
      "average loss is: 0.131766459678\n",
      "average loss is: 0.125381493949\n",
      "average loss is: 0.119599098227\n",
      "average loss is: 0.114337381247\n",
      "average loss is: 0.109528665657\n",
      "average loss is: 0.105116533384\n",
      "average loss is: 0.101053577985\n",
      "average loss is: 0.0972996741069\n",
      "average loss is: 0.093820632044\n",
      "average loss is: 0.0905871372991\n",
      "average loss is: 0.0875739114509\n",
      "average loss is: 0.0847590394488\n",
      "average loss is: 0.0821234288742\n",
      "average loss is: 0.079650368163\n",
      "average loss is: 0.0773251660003\n",
      "average loss is: 0.0751348558335\n",
      "average loss is: 0.0730679483965\n",
      "average loss is: 0.0711142273374\n",
      "average loss is: 0.0692645774255\n",
      "average loss is: 0.0675108397355\n",
      "average loss is: 0.0658456894337\n",
      "average loss is: 0.0642625315812\n",
      "average loss is: 0.0627554119665\n",
      "average loss is: 0.0613189413034\n",
      "average loss is: 0.059948229676\n",
      "average loss is: 0.0586388300699\n",
      "average loss is: 0.05738668844\n",
      "average loss is: 0.0561881021362\n",
      "average loss is: 0.0550396820511\n",
      "average loss is: 0.0539383201534\n",
      "average loss is: 0.0528811609025\n",
      "average loss is: 0.0518655761557\n",
      "average loss is: 0.0508891425877\n",
      "average loss is: 0.0499496224367\n",
      "average loss is: 0.0490449456893\n",
      "average loss is: 0.0481731953563\n",
      "average loss is: 0.0473325925335\n",
      "average loss is: 0.0465214848134\n",
      "average loss is: 0.0457383351514\n",
      "average loss is: 0.0449817118815\n",
      "average loss is: 0.0442502796927\n",
      "average loss is: 0.0435427918518\n",
      "average loss is: 0.0428580828441\n",
      "average loss is: 0.0421950617608\n",
      "average loss is: 0.0415527067172\n",
      "average loss is: 0.0409300591527\n",
      "average loss is: 0.0403262192239\n",
      "average loss is: 0.0397403411381\n",
      "average loss is: 0.0391716292271\n",
      "average loss is: 0.0386193343495\n",
      "average loss is: 0.0380827505725\n",
      "average loss is: 0.0375612118193\n",
      "average loss is: 0.0370540894219\n",
      "average loss is: 0.0365607894682\n",
      "average loss is: 0.0360807502221\n",
      "average loss is: 0.0356134402267\n",
      "average loss is: 0.0351583559568\n",
      "average loss is: 0.0347150203697\n",
      "average loss is: 0.0342829808685\n",
      "average loss is: 0.0338618080745\n",
      "average loss is: 0.0334510939502\n",
      "average loss is: 0.0330504509121\n",
      "average loss is: 0.0326595103741\n"
     ]
    }
   ],
   "source": [
    "# define the parameters\n",
    "m = ParameterCollection()\n",
    "pW = m.add_parameters((8,2))\n",
    "pV = m.add_parameters((1,8))\n",
    "pb = m.add_parameters((8))\n",
    "\n",
    "# renew the computation graph\n",
    "renew_cg()\n",
    "\n",
    "# add the parameters to the graph\n",
    "W = parameter(pW)\n",
    "V = parameter(pV)\n",
    "b = parameter(pb)\n",
    "\n",
    "# create the network\n",
    "x = vecInput(2) # an input vector of size 2.\n",
    "output = logistic(V*(tanh((W*x)+b)))\n",
    "# define the loss with respect to an output y.\n",
    "y = scalarInput(0) # this will hold the correct answer\n",
    "loss = binary_log_loss(output, y)\n",
    "\n",
    "# create training instances\n",
    "def create_xor_instances(num_rounds=2000):\n",
    "    questions = []\n",
    "    answers = []\n",
    "    for round in xrange(num_rounds):\n",
    "        for x1 in 0,1:\n",
    "            for x2 in 0,1:\n",
    "                answer = 0 if x1==x2 else 1\n",
    "                questions.append((x1,x2))\n",
    "                answers.append(answer)\n",
    "    return questions, answers \n",
    "\n",
    "questions, answers = create_xor_instances()\n",
    "\n",
    "# train the network\n",
    "trainer = SimpleSGDTrainer(m)\n",
    "\n",
    "total_loss = 0\n",
    "seen_instances = 0\n",
    "for question, answer in zip(questions, answers):\n",
    "    x.set(question)\n",
    "    y.set(answer)\n",
    "    seen_instances += 1\n",
    "    total_loss += loss.value()\n",
    "    loss.backward()\n",
    "    trainer.update()\n",
    "    if (seen_instances > 1 and seen_instances % 100 == 0):\n",
    "        print \"average loss is:\",total_loss / seen_instances\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dynamic Networks\n",
    "\n",
    "Dynamic networks are very similar to static ones, but instead of creating the network once and then calling \"set\" in each training example to change the inputs, we just create a new network for each training example.\n",
    "\n",
    "We present an example below. While the value of this may not be clear in the `xor` example, the dynamic approach\n",
    "is very convenient for networks for which the structure is not fixed, such as recurrent or recursive networks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "average loss is: 0.736730417013\n",
      "average loss is: 0.725369692743\n",
      "average loss is: 0.715208243926\n",
      "average loss is: 0.698906037733\n",
      "average loss is: 0.667973376453\n",
      "average loss is: 0.620016210104\n",
      "average loss is: 0.564173455558\n",
      "average loss is: 0.511108190748\n",
      "average loss is: 0.464656613212\n",
      "average loss is: 0.424903827408\n",
      "average loss is: 0.390944672838\n",
      "average loss is: 0.361782596097\n",
      "average loss is: 0.336552875967\n",
      "average loss is: 0.314552738269\n",
      "average loss is: 0.295221981726\n",
      "average loss is: 0.27811523865\n",
      "average loss is: 0.262876965393\n",
      "average loss is: 0.249221329002\n",
      "average loss is: 0.236916671552\n",
      "average loss is: 0.225773662324\n",
      "average loss is: 0.215636288271\n",
      "average loss is: 0.206374970573\n",
      "average loss is: 0.197881278039\n",
      "average loss is: 0.190063834667\n",
      "average loss is: 0.182845127269\n",
      "average loss is: 0.176158992879\n",
      "average loss is: 0.16994863152\n",
      "average loss is: 0.164165015582\n",
      "average loss is: 0.158765610311\n",
      "average loss is: 0.153713339384\n",
      "average loss is: 0.148975738776\n",
      "average loss is: 0.14452426397\n",
      "average loss is: 0.140333718062\n",
      "average loss is: 0.13638177571\n",
      "average loss is: 0.132648585576\n",
      "average loss is: 0.129116437846\n",
      "average loss is: 0.125769484215\n",
      "average loss is: 0.122593499324\n",
      "average loss is: 0.119575678358\n",
      "average loss is: 0.116704463887\n",
      "average loss is: 0.113969398874\n",
      "average loss is: 0.111360997359\n",
      "average loss is: 0.108870635643\n",
      "average loss is: 0.106490455879\n",
      "average loss is: 0.104213282756\n",
      "average loss is: 0.102032551605\n",
      "average loss is: 0.0999422444205\n",
      "average loss is: 0.0979368338955\n",
      "average loss is: 0.0960112348951\n",
      "average loss is: 0.094160760665\n",
      "average loss is: 0.0923810851444\n",
      "average loss is: 0.0906682085468\n",
      "average loss is: 0.0890184267577\n",
      "average loss is: 0.0874283051604\n",
      "average loss is: 0.0858946543594\n",
      "average loss is: 0.0844145084265\n",
      "average loss is: 0.0829851059784\n",
      "average loss is: 0.0816038727351\n",
      "average loss is: 0.0802684055211\n",
      "average loss is: 0.0789764590814\n",
      "average loss is: 0.0777259325812\n",
      "average loss is: 0.0765148587798\n",
      "average loss is: 0.0753413928689\n",
      "average loss is: 0.0742038039022\n",
      "average loss is: 0.073100465403\n",
      "average loss is: 0.072029847966\n",
      "average loss is: 0.0709905121502\n",
      "average loss is: 0.0699811016467\n",
      "average loss is: 0.0690003377412\n",
      "average loss is: 0.0680470136383\n",
      "average loss is: 0.0671199895066\n",
      "average loss is: 0.0662181878878\n",
      "average loss is: 0.0653405894968\n",
      "average loss is: 0.0644862291951\n",
      "average loss is: 0.0636541927901\n",
      "average loss is: 0.0628436133573\n",
      "average loss is: 0.062053668331\n",
      "average loss is: 0.0612835769022\n",
      "average loss is: 0.0605325971122\n",
      "average loss is: 0.0598000235481\n"
     ]
    }
   ],
   "source": [
    "import dynet as dy\n",
    "# create training instances, as before\n",
    "def create_xor_instances(num_rounds=2000):\n",
    "    questions = []\n",
    "    answers = []\n",
    "    for round in xrange(num_rounds):\n",
    "        for x1 in 0,1:\n",
    "            for x2 in 0,1:\n",
    "                answer = 0 if x1==x2 else 1\n",
    "                questions.append((x1,x2))\n",
    "                answers.append(answer)\n",
    "    return questions, answers \n",
    "\n",
    "questions, answers = create_xor_instances()\n",
    "\n",
    "# create a network for the xor problem given input and output\n",
    "def create_xor_network(pW, pV, pb, inputs, expected_answer):\n",
    "    dy.renew_cg() # new computation graph\n",
    "    W = dy.parameter(pW) # add parameters to graph as expressions\n",
    "    V = dy.parameter(pV)\n",
    "    b = dy.parameter(pb)\n",
    "    x = dy.vecInput(len(inputs))\n",
    "    x.set(inputs)\n",
    "    y = dy.scalarInput(expected_answer)\n",
    "    output = dy.logistic(V*(dy.tanh((W*x)+b)))\n",
    "    loss =  dy.binary_log_loss(output, y)\n",
    "    return loss\n",
    "\n",
    "m2 = dy.ParameterCollection()\n",
    "pW = m2.add_parameters((8,2))\n",
    "pV = m2.add_parameters((1,8))\n",
    "pb = m2.add_parameters((8))\n",
    "trainer = dy.SimpleSGDTrainer(m2)\n",
    "\n",
    "seen_instances = 0\n",
    "total_loss = 0\n",
    "for question, answer in zip(questions, answers):\n",
    "    loss = create_xor_network(pW, pV, pb, question, answer)\n",
    "    seen_instances += 1\n",
    "    total_loss += loss.value()\n",
    "    loss.backward()\n",
    "    trainer.update()\n",
    "    if (seen_instances > 1 and seen_instances % 100 == 0):\n",
    "        print \"average loss is:\",total_loss / seen_instances\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}

{'fraction_non_alphanumeric': 0.16133723416996013, 'fraction_numerical': 0.1385481359817961, 'mean_word_length': 2.472964943553179, 'pattern_counts': {'":': 398, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2393596', 'n_tokens_mistral': 26974, 'n_tokens_neox': 21455, 'n_words': 5458}