\n", "#### Broadcasting\n", "You should be aware of one particular feature of the above code: broadcasting. When we end up training our neural network, we don't want to run the for every sample; rather, we want to run the machine on all the samples at once. This has no effect on semantics, but is important for performance.\n", "\n", "When we do this, we represent each sample as a separate row (the first dimension of the tensor). Since constants are the same for all samples, they need to be _broadcast_ along the first dimension; Theano needs to know to automatically scale the constant vector along the first dimension, copying it as many times as necessary.\n", "\n", "`to_one_hot` automatically creates a variable of the `row` type, which is broadcastable in its first dimension. Observe this in the following code, in which `y` automatically gets broadcast along the first dimension to match the dimension of `x`:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "X = [[ 1. 1. 1.]\n", " [ 1. 1. 1.]]\n", "Y = [[ 0. 1. 0.]]\n", "X + Y = [[ 1. 2. 1.]\n", " [ 1. 2. 1.]]\n" ] } ], "source": [ "x = np.ones((2, 3))\n", "y = gate_one.module(3)\n", "\n", "print(\"X =\", x)\n", "print(\"Y =\", y.eval())\n", "print(\"X + Y =\", (x + y).eval())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For more info on broadcasting, take a look at the [Theano documentation on broadcasting](http://deeplearning.net/software/theano/library/tensor/basic.html#broadcasting-in-theano-vs-numpy).\n", "

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Unary Gates\n", "\n", "Next up, we define two one-argument gates. The `eq_zero` gate returns whether its input is equal to zero; the `negate` gate returns its input times negative one (modulo $M$).\n", "\n", "`eq_zero` returns a boolean (a zero or a one); that is, the result only has non-zero values in the first to components. To implement it, we must create the vector component-by-component, for which we need Theano's `set_subtensor`, which allows direct manipulation of vector components:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# In Theano, writing\n", "# >>> A = set_subtensor(A[0], x)\n", "# corresponds to standard Python's\n", "# >>> A = A.copy(); A[0] = x\n", "from theano.tensor import set_subtensor\n", "\n", "def eq_zero(A, max_int):\n", " \"\"\"Given a Theano vector A, return a vector\n", " of the same shape where the first component is\n", " 1 - A[0], the second component is A[0], and the\n", " other components are all zero.\n", " \n", " This corresponds to a neural gate that checks for zero.\"\"\"\n", " \n", " # Initialize result to be zeros in the same shape as A.\n", " # This should be a list of row vectors of length max_int.\n", " # By operating on all rows at once we allow multiple samples\n", " # to be processed in one call to this function.\n", " result = tensor.zeros_like(A)\n", " result = set_subtensor(result[:, 1], A[:, 0])\n", " result = set_subtensor(result[:, 0], 1 - A[:, 0])\n", " return result\n", "\n", "gate_eqz = Gate(1, eq_zero)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In order to implement `negate`, we must recognize that arithmetic in our formulation operates modulo $M$. Negative values simply correspond to other positive integers. Specifically, the mapping from values to their negatives is:\n", "\n", "$$\\begin{align*}\n", "0 \\to&\\; 0 \\\\\n", "1 \\to&\\; M - 1 \\\\\n", "2 \\to&\\; M - 2 \\\\\n", "\\vdots \\to&\\; \\vdots \\\\\n", "M - 1 \\to&\\; 1\\end{align*}$$\n", "\n", "You can confirm this mapping by observing that $x + (-x) \\equiv 0 \\text{ mod } M$ for each one, as in $2 + (M - 2) = M \\equiv 0 \\text{ mod } M$. As you can see from observing the right column, this is just the values 0 through $M - 1$ in descending order, but rotated one space to have zero at the top. We can implement this with Theano's `roll` and Python's `a[::-1]` for reversing an array:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# `roll` circularly rotates elements of a vector.\n", "# For example, \n", "# >>> roll([1, 2, 3], -2)\n", "# rotates the elements two spaces to the left, resulting in\n", "# >>> [3, 1, 2]\n", "from theano.tensor import roll\n", "\n", "def negate(A, max_int):\n", " \"\"\"Negate a distribution over integers.\"\"\"\n", " return roll(A[:, ::-1], 1, axis=1)\n", "\n", "gate_negate = Gate(1, negate)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Binary Gates\n", "Finally, let's implement at least one binary gate: addition. We discussed the addition gate in the [previous post](), yielding the following module for computing the distribution of a sum:\n", "\n", "$$m_{\\text{ADD}}(\\vec A, \\vec B)_\\ell = \\sum_{j=0}^{M-1} A_j B_{\\ell - k \\text{ mod } M}.$$\n", "\n", "We can implement this efficiently by creating a matrix, $B'$, which, when premultiplied by $\\vec A$, yields $m_{\\text{ADD}}(\\vec A, \\vec B)$. The columns of $B'$ must be the coefficients $B_{\\ell - k \\text{ mod } M}$; these columns are just reversed and circularly shifted version of $\\vec B$ itself:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# `stack` stacks a list of vectors\n", "# into a matrix. It increases the number \n", "# of dimensions in the tensor by one.\n", "# The dimension it adds is configurable.\n", "from theano.tensor import stack\n", "\n", "# `batched_dot` performs matrix multiplication\n", "# across a set of samples, where each sample is\n", "# a row (uses the dimension).\n", "from theano.tensor import batched_dot\n", "\n", "def add(A, B, max_int):\n", " \"\"\"Returns the distribution for a sum of integers.\"\"\"\n", " rows = [roll(B[:, ::-1], shift + 1, axis=1)\n", " for shift in range(max_int)]\n", " B_prime = stack(rows, axis=1).transpose(0, 2, 1)\n", " return batched_dot(A, B_prime)\n", "\n", "gate_add = Gate(2, add)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We use the `transpose` method to transpose the last two dimension but leave the first one alone (since it contains the parallel samples). This gate can be tricky, so I recommend using it as a self-test in the exercise below!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To gain a bit of intuition, let's test our modules:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 = 0? [[ 0. 1. 0. 0. 0.]]\n", "0 = 1? [[ 1. 0. 0. 0. 0.]]\n", "2 [[ 0. 0. 1. 0. 0.]]\n", "-2 = 3 [[ 0. 0. 0. 1. 0.]]\n", "1 + 2 = 3 [[ 0. 0. 0. 1. 0.]]\n", "3 + 3 = 1 [[ 0. 1. 0. 0. 0.]]\n" ] } ], "source": [ "# Distributions over the set {0, 1, 2, 3, 4}\n", "max_int = 5\n", "\n", "zero = gate_zero.module(max_int)\n", "one = gate_one.module(max_int)\n", "two = gate_two.module(max_int)\n", "three = add(one, two, max_int)\n", "\n", "print(\"0 = 0? \", eq_zero(zero, max_int).eval())\n", "print(\"0 = 1? \", eq_zero(one, max_int).eval())\n", "print(\"2 \", two.eval())\n", "print(\"-2 = 3 \", negate(two, max_int).eval())\n", "print(\"1 + 2 = 3\", three.eval())\n", "print(\"3 + 3 = 1\", add(three, three, max_int).eval())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Confirm that these definitions work when the input is a list of samples (each sample as one row), rather than just one sample at a time. For each gate, look at all the intermediate products and explain what shape each of the tensors have. Pay particular attention to the `add` gate." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Implementing Fuzzy Circuits" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have a set of gates to play with, let's figure out how to connect them into end-to-end fuzzy circuits.\n", "\n", "Recall from the previous post that, for a given gate $i$, the controller generates coefficients $\\vec a_i$ and $\\vec b_i$ as necessary, where the vector indicates coefficients for a linear combination of registers and previous outputs. Given these coefficients, we'd like to write the gates together into one end-to-end system. To do so, we need to be able to take a coefficient-weighted sum of registers and previous outputs:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def avg(distributions, coefficients):\n", " \"\"\"\n", " Return the weighted average of a set of vectors.\n", " \n", " Shapes:\n", " distributions: (S, N, M)\n", " coefficients: (S, N)\n", " return value: (S, M)\n", "\n", " where\n", " S: number of samples to perform this operation on\n", " N: number of vectors in the set\n", " M: number of elements in each vector\n", " \"\"\"\n", " # Shuffle coefficients to shape (S, N, 1)\n", " coeffs = coefficients.dimshuffle(0, 1, 'x')\n", " \n", " # Transpose distributions to (S, M, N)\n", " dists = distributions.transpose(0, 2, 1)\n", " \n", " # Batched multiply to get shape (S, M, 1),\n", " # then drop the last dimension.\n", " return batched_dot(dists, coeffs).flatten(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This operation is a straight-forward matrix multiplication, made much less straight-forward by the need to massage the dimensions into a form where applying the operation to many samples at once works. We can confirm that it works with one sample:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([[ 63.1, 126.2, 189.3]])" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "vectors = [[\n", " [1, 2, 3], # X\n", " [10, 20, 30], # Y\n", " [100, 200, 300], # Z\n", "]]\n", "coefficients = [[0.1, 0.3, 0.6]]\n", "\n", "from theano.tensor import as_tensor\n", "\n", "# 0.1 X + 0.3 Y + 0.6 Z\n", "avg(as_tensor(vectors), as_tensor(coefficients)).eval()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Reimplement this yourself with Theano, making sure that the operation works when applied to many samples at once. Look at the docstring of `avg` to determine the input shapes." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The next building block is one that runs just _one_ gate, given the registers and previous gate outputs, and the list of controller-generated coefficients:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def run_gate(gate_inputs, gate, controller_coefficients, max_int):\n", " \"\"\"Return the output of a gate in the circuit.\n", " \n", " gate_inputs:\n", " The values of the registers and previous gate outputs.\n", " gate:\n", " The gate to compute output for. Arity must\n", " match len(controller_coefficients).\n", " controller_coeffficients:\n", " A list of coefficient arrays from the controller,\n", " one coefficient for every gate input (0 for constants).\n", " \"\"\"\n", " args = [avg(gate_inputs, coefficients)\n", " for coefficients in controller_coefficients]\n", " output = gate.module(*args, max_int)\n", " \n", " # Special-case constant gates.\n", " # Since they have no outputs, they always output\n", " # one sample. Repeat their outputs as many times\n", " # as necessary, effectively doing manual broadcasting\n", " # to generate an output of the right size.\n", " if gate.arity == 0:\n", " output = output.repeat(gate_inputs.shape[0], axis=0)\n", " \n", " return output" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, since we can now run _one_ gate, we can combine all our gates into a full circuit. The full circuit runs through all the gates, generating outputs, and then generates new values for the registers, similarly using the controller coefficients." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from theano.tensor import concatenate\n", "\n", "def run_circuit(registers, gates, controller_coefficients, max_int):\n", " # Initially, only the registers may be used as inputs.\n", " gate_inputs = registers\n", " \n", " # Run through all the gates.\n", " for i in range(len(gates)):\n", " output = run_gate(gate_inputs, gates[i],\n", " controller_coefficients[i], max_int)\n", " # Append the output of the gate as an input for future gates.\n", " gate_inputs = concatenate([gate_inputs,\n", " output.dimshuffle(0, 'x', 1)],\n", " axis=1)\n", " \n", " # All leftover coefficients are for registers.\n", " new_registers = []\n", " for i in range(len(gates), len(controller_coefficients)):\n", " new_registers.append(avg(gate_inputs, controller_coefficients[i]))\n", " return tensor.stack(new_registers, axis=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Testing this requires a bit more setup than before, as it encompasses almost the entire complexity of our system. We will create a simple system, with three registers, four gates, and $M = 5$. We must define the initial register values, the order of the gates, and the connections between the registers, the gates, and the new register values. The connections are set by choosing appropriate controller coefficients." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Registers: R1 = 0, R2 = 1, R3 = 3\n", "# These use the previously defined max_int = 5.\n", "v0 = zero.eval()\n", "v1 = one.eval()\n", "v3 = three.eval()\n", "registers = tensor.stack([v0, v1, v3], axis=1)\n", "\n", "# Gates: 1, NEG(x), ADD(x, y), EQZ(x)\n", "gates = [gate_one, gate_negate, gate_add, gate_eqz]\n", "\n", "# Circuit:\n", "#\n", "# R1 ----------------------- - R1'\n", "# 1 -- NEG -- \\ /\n", "# \\ \\ /\n", "# ADD -- EQZ --X \n", "# / \\\n", "# R2 ----------- - R2'\n", "# R3 ---------------------------- R3'\n", "#\n", "# Equivalently:\n", "# R3' = R3\n", "# R2' = R1\n", "# R1' = [R2 - 1 == 0]\n", "\n", "from theano.tensor import as_tensor\n", "def c(*cs):\n", " \"\"\"Convert a list into a coefficient tensor, shape 1 x N.\"\"\"\n", " return as_tensor(cs).reshape((1, len(cs)))\n", " \n", "controller_coefficients = [\n", " # 1 coefficients\n", " [],\n", " \n", " # NEG coefficients\n", " [c(0, 0, 0, 1)],\n", " \n", " # ADD coefficients\n", " [c(0, 0, 0, 0, 1),\n", " c(0, 1, 0, 0, 0)],\n", " \n", " # EQZ coefficients\n", " [c(0, 0, 0, 0, 0, 1)],\n", " \n", " # R1' (not a gate, thus not a list of coefficients)\n", " c(0, 0, 0, 0, 0, 0, 1),\n", " \n", " # R2'\n", " c(1, 0, 0, 0, 0, 0, 0),\n", " \n", " # R3'\n", " c(0, 0, 1, 0, 0, 0, 0),\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With the inputs set up, we can run our circuit and observe the outputs of each of the gates and the new values of each register. We have four gates and three new register values:\n", "\n", "- The first gate is a constant gate, and should return 1.\n", "- The second gate is a negation of the 1, so should return -1.\n", "- The third gate adds R2 to -1, and, since R2 = 0, should return 0.\n", "- The fourth gate checks R2 - 1 for equality with 0, so should return 1.\n", "- R3', the new value of R3, should equal R3 and be 3.\n", "- R2', the new value of R2, should equal R1 and be 0.\n", "- R1' should equal the output of the last gate, so should be 1.\n", "\n", "We can confirm these expected values:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 0 3]]\n" ] } ], "source": [ "new_registers = run_circuit(registers, gates,\n", " controller_coefficients, max_int)\n", "print(new_registers.eval().argmax(axis=2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Implementing the Controller" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have now implemented the probabilistic circuit gates and combined them together into a single circuit, directed by coefficients generated by a hypothetical neural network controller. In this section, we'll implement the neural network controller itself. For this post, we'll use a simple feed-forward multilayer perceptron, although we could also use an LSTM recurrent neural network.\n", "\n", "Recall that the inputs to the neural network are the 0th components of the registers; that way, the neural network can use binary information (\"is this register zero?\") but cannot learn to solve the problem entirely on its own.\n", "\n", "We'll start by generating the *weights* of the neural network. The weights will be [Theano shared variables](http://deeplearning.net/software/theano/library/compile/shared.html#theano.compile.sharedvalue.shared), which will allow us to update them as we train. Shared variables are mutable values (`numpy` arrays) that can be used in a Theano computation graph and which Theano knows how to update.\n", "\n", "The weights will be initially randomly sampled from a uniform distribution around zero:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# `shared` converts a numpy array to a shared variable.\n", "from theano import shared\n", "from numpy.random import uniform\n", "\n", "def init_weight(*dims, low=-0.3, high=0.3):\n", " \"\"\"Create a randomly-initialized shared variable weight matrix.\"\"\"\n", " weights = uniform(low=low, high=high, size=dims)\n", " var = shared(weights.astype(np.float32), name=\"W{0}x{1}\".format(*dims))\n", " \n", " return var" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The neural network will start with an input layer, drawing from the registers; it will then have one or more hidden layers; finally, from the hidden layer the neural network will generate all of its outputs (controller coefficients and willingness to complete the computation).\n", "\n", "" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def mlp_weights(num_registers, layer_sizes, gates):\n", " \"\"\"\n", " Generate weights and biases for all the connections\n", " in the neural network controller.\n", " \n", " layer_sizes: Number of units in each hidden layer.\n", " \"\"\"\n", " \n", " # The first layer has one input per register.\n", " prev_layer = num_registers\n", "\n", " # Weights for making the hidden layers.\n", " for layer_size in layer_sizes:\n", " # Weights.\n", " yield init_weight(prev_layer, layer_size) \n", " # Biases.\n", " yield init_weight(1, layer_size)\n", " \n", " # Keep track of last layer size.\n", " prev_layer = layer_size\n", " \n", " # Weights for gate coefficients (output layers).\n", " for prev_gates, gate in enumerate(gates):\n", " num_outputs = num_registers + prev_gates\n", " for _ in range(gate.arity):\n", " # Weights.\n", " yield init_weight(prev_layer, num_outputs)\n", " # Biases.\n", " yield init_weight(1, num_outputs)\n", " \n", " # Weights for new register value coefficients (output layers).\n", " num_outputs = num_registers + len(gates)\n", " for _ in range(num_registers):\n", " # Weights.\n", " yield init_weight(prev_layer, num_outputs)\n", " # Biases.\n", " yield init_weight(1, num_outputs)\n", " \n", " # Weights for willingness to complete computation output.\n", " yield init_weight(prev_layer, 1)\n", " # Biases.\n", " yield init_weight(1, 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using these weights, we can define the outputs of the network by implementing forward propogation. All intermediate layers use [rectified linear units (ReLu)](https://en.wikipedia.org/wiki/Rectifier_(neural_networks)), and the output layers must sum to one, so use a [softmax](https://en.wikipedia.org/wiki/Softmax_function). The willingness to complete computation is a single number between zero and one, so uses a sigmoid unit." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from theano.tensor.nnet import softmax, relu, sigmoid\n", "\n", "# Define a helper function for deconstructing\n", "# the parameter list.\n", "def take(values, i):\n", " \"\"\"Return the next pair of weights and biases after the\n", " starting index and the new starting index.\"\"\"\n", " return values[i], values[i + 1], i + 2\n", "\n", "def mlp_forward_prop(num_registers, num_layers, gates,\n", " registers, params):\n", " \"\"\"Run forward propogation on the register machine (one step).\"\"\"\n", " # Extract 0th component from all registers.\n", " last_layer = registers[:, :, 0]\n", " \n", " # Propogate forward to hidden layers.\n", " idx = 0\n", " for _ in range(num_layers):\n", " W, b, idx = take(params, idx)\n", " last_layer = relu(last_layer.dot(W) + b)\n", " \n", " # Propogate forward to gate coefficient outputs.\n", " # In the result list, each result is a list of\n", " # coefficients, as gates may have 0, 1, or 2 inputs.\n", " controller_coefficients = []\n", " for gate in gates:\n", " coeffs = []\n", " for _ in range(gate.arity):\n", " W, b, idx = take(params, idx)\n", " coeffs.append(softmax(last_layer.dot(W) + b))\n", " controller_coefficients.append(coeffs)\n", " \n", " # Forward propogate to new register value coefficients.\n", " for _ in range(num_registers):\n", " W, b, idx = take(params, idx)\n", " coeffs = softmax(last_layer.dot(W) + b)\n", " controller_coefficients.append(coeffs)\n", " \n", " # Forward propogate to generate willingness to complete.\n", " W, b, idx = take(params, idx)\n", " complete = sigmoid(last_layer.dot(W) + b)\n", " \n", " return controller_coefficients, complete" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now run a single timestep of our register machine from end to end. However, without training it, it does not output anything interesting.\n", "\n", "**Exercise:** Verify that this code works, and that it works for many samples at once. Constructing the inputs for this code is educational on its own!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now run forward propagation on our neural network to generate the controller coefficients, and we can use the controller coefficients as weights to run our fuzzy circuit.\n", "\n", "Putting those together to run a full timestep of our machine now becomes fairly straightforward:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def step_machine(gates, max_int, num_registers, num_layers,\n", " registers, params):\n", " \"\"\"Run a single timestep of the machine.\"\"\"\n", " # Run single-step forward propagation.\n", " controller_out = mlp_forward_prop(num_registers, num_layers, gates,\n", " registers, params)\n", " coefficients, complete = controller_out\n", "\n", " # Using the generated coefficients, advance the registers.\n", " new_registers = run_circuit(registers, gates,\n", " coefficients, max_int)\n", "\n", " return new_registers, complete" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Implementing the Cost Function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$\\renewcommand{\\R}[0]{\\mathbb{R}}\n", "\\renewcommand{\\Z}[0]{\\mathbb{Z}}\n", "\\newcommand{\\bmatr}[1] {\\begin{bmatrix} #1 \\end{bmatrix}}$In order to have forward propogation do something useful with our model, we must train the weights, and for that we need to compute our objective function and then differentiate it with respect to the weights. Recall from the previous post that our objective is\n", "\n", "$$J(\\theta) = -\\sum_{t = 1}^T p_t \\sum_{i=1}^R \\log(r^{(t)}_{i,y_i}),$$\n", "where $r^{(t)}_{i,y_i}$ is the probability of register $i$ having value $y_i$ at timestep $t$ (the $y_i$th component at time $t$), $y \\in {\\Z_M}^R$ is the vector of desired integer outputs at the end of the algorithm, and $p_t$ is the probability that the computation completed after timestep $t$.\n", "\n", "To compute this cost, we must be able to compute $r^{(t)}_{i,y_i}$:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def log_prob_correct(registers, desired_output, num_registers, max_int):\n", " \"\"\"Compute log-probability of correctness over all registers.\"\"\"\n", " cost = 0\n", " \n", " # Add epsilon to every log to avoid having inf in costs.\n", " epsilon = 1e-100\n", " \n", " for i in range(num_registers):\n", " # Create a mask to extract just the values we want.\n", " # This has the same shape as the registers, and a one\n", " # on components we want to include in the sum, a zero\n", " # on components we don't wish to include in the sum.\n", " mask = to_one_hot(desired_output[:, i], max_int)\n", " \n", " # Compute the loss for this register using the mask.\n", " loss = (mask * tensor.log(registers[:, i, :] + epsilon)).sum(axis=1)\n", " \n", " # Accumulate costs over all registers, keeping the dimensions S x 1.\n", " cost += tensor.shape_padright(loss, 1)\n", " \n", " return cost" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Although we could run forward propogation, collect all the results, and use them to compute the cost, this would require storing in memory all the results. Instead, we can compute the cost *during* the forward propogation, thus reducing the amount of data we need to actively store. Observe that in the following code we accumulate the cost over each timestep.\n", "\n", "We must also compute $p_t$ in order to compute the cost for a timestep, which is a bit messy:\n", "\n", "$$p_t = \\begin{cases}\n", " 1 - \\displaystyle\\sum_{i=1}^{t-1} p_i & \\text{ if } t = T \\\\\n", " f_t \\displaystyle\\prod_{i=1}^{t-1} (1 - f_i)& \\text{ otherwise}\n", "\\end{cases}$$\n", "where $T$ is the number of timesteps and $f_i$ is the willingness to complete at timestep $i$.\n", "\n", "At the end, we must know the cumulative probability so far, and at every other timestep, we must know the probability that the computation isn't already concluded. To be able to compute all these, we pass `timestep` $(t)$, `max_timesteps` $(T)$, `cum_prob_complete` $(\\sum_{i=1}^{t-1} p_i)$, and `prob_incomplete` $(\\prod_{i=1}^{t-1} (1 - f_i))$ to each step:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def step_cost(gates, max_int, desired_output, max_timesteps,\n", " num_registers, num_layers, timestep, registers,\n", " cost, cum_prob_complete, prob_incomplete, params):\n", " # Run the machine forward one step.\n", " machine_result = step_machine(gates, max_int, num_registers,\n", " num_layers, registers, params)\n", " registers, complete = machine_result\n", " \n", " # Complete the probability that the algorithm is done\n", " # after this step. Force the algorithm to complete after \n", " # T timesteps.\n", " if timestep == max_timesteps:\n", " prob_complete = 1 - cum_prob_complete\n", " else:\n", " prob_complete = complete * prob_incomplete\n", " \n", " # Update the probability that the computation isn't complete\n", " prob_incomplete *= 1 - complete\n", " \n", " # Accumulate the probability that a result has been produced.\n", " cum_prob_complete += prob_complete\n", " \n", " # Cost for this timestep.\n", " unscaled_cost = log_prob_correct(registers, desired_output,\n", " num_registers, max_int)\n", " scaled_cost = prob_complete * unscaled_cost\n", " cost -= scaled_cost\n", " \n", " return registers, cost, cum_prob_complete, prob_incomplete " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Putting this all together, we run the machine for $T$ timesteps, passing the outputs at each step as the next inputs:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from theano.tensor import dtensor3, imatrix\n", "\n", "# This function is a boring utility function.\n", "# Main code of interest is below in `run`.\n", "def make_broadcastable(weights):\n", " \"\"\"Shared variables (the weights of the controller) are\n", " not broadcastable by default. We need to make them broadcastable\n", " to use them. This function does so manually.\"\"\"\n", " broadcastable = []\n", " for var in weights:\n", " # Only make biases broadcastable.\n", " if var.get_value().shape[0] == 1:\n", " # Keep the name the same.\n", " name = var.name\n", " var = tensor.addbroadcast(var, 0)\n", " var.name = name\n", " broadcastable.append(var)\n", " return broadcastable\n", "\n", "def run(gates, num_registers, max_int,\n", " num_timesteps, num_layers, reg_lambda, params):\n", " params = make_broadcastable(params)\n", "\n", " # Create symbolic variables for the input to the machine\n", " # and for the desired output of the machine.\n", " initial_registers = dtensor3(\"R\")\n", " desired_registers = imatrix(\"Y\")\n", " \n", " # Run the model for all timesteps. The arguments are \n", " # registers, cost, cumulative probability complete, \n", " # and probability incomplete. The latter are initialized\n", " # to zero and to one, respectively.\n", " v0 = as_tensor(0)\n", " v1 = as_tensor(1)\n", " output = [initial_registers, v0, v0, v1]\n", " registers = []\n", " for timestep in range(num_timesteps):\n", " output = step_cost(gates, max_int, desired_registers,\n", " num_timesteps, num_registers,\n", " num_layers, timestep + 1,\n", " *output, params)\n", " registers.append(output[0])\n", "\n", " # Add in regularization, to avoid overfitting simple examples.\n", " reg_cost = reg_lambda * sum((p * p).sum() for p in params)\n", " \n", " # Get the final cost: regularization plus loss.\n", " final_cost = reg_cost + output[1].sum()\n", " \n", " # Return the symbolic variables, the final cost, and the\n", " # intermediate register values for analysis and prediction.\n", " return initial_registers, desired_registers, final_cost, registers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Preparing Training Data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once we have computed the cost, the magic of Theano really shines: we can get backpropogation practically for free by using the `grad` method. `grad` automatically computes the derivatives of a value with respect to any variables, in this case the shared weights of the neural network.\n", "\n", "With that in mind, let's come up with a simple training example and enough data to train with: we'll teach our machine to do a single-step computation corresponding to the circuit we defined above:\n", "\n", "$$\\begin{align*}\n", "R_1' &= [R_2 - 1 == 0] \\\\\n", "R_3' &= R_3 \\\\\n", "R_2' &= R_1\n", "\\end{align*}$$" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def example_circuit(r1, r2, r3):\n", " \"\"\"Python implementation of our example circuit.\"\"\"\n", " return int(r2 - 1 == 0), r3, r1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Given the limited number of registers and integer values, we can generate all possible inputs and all corresponding outputs as training data. `itertools.product` makes this very easy to do by generating the Cartesian product of our integer set:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import itertools\n", "\n", "# Generate all sample inputs.\n", "max_int = 50\n", "num_registers = 3\n", "inputs = list(itertools.product(range(max_int),\n", " repeat=num_registers))\n", "\n", "# Generate all sample outputs.\n", "outputs = [example_circuit(*values) for values in inputs]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Right now the inputs and outputs are stored as lists of tuples, whereas Theano and Numpy work with arrays, and expect the input to be one-hot encoded. Let's address that by encoding the inputs and storing the data as Numpy arrays:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def encode(samples):\n", " \"\"\"Convert inputs to one-hot matrix form.\n", " The result is shape (S, R, M), where, as usual:\n", " S - num samples, R - num registers, M - max int\n", " \"\"\"\n", " samples = np.asarray(samples)\n", " \n", " # Encode each register separately.\n", " # to_one_hot requires a 1-d vector.\n", " encoded = []\n", " for i in range(num_registers):\n", " encoded.append(to_one_hot(samples[:, i], max_int).eval())\n", " return np.asarray(encoded).swapaxes(0, 1)\n", "\n", "inputs = encode(inputs)\n", "outputs = np.asarray(outputs, dtype=np.int32)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These input and output arrays are suitable to train on, but have a subtle, lurking issue. Namely: what percentage of the outputs have R1 equal to zero, and what percentage have R1 equal to one?\n", "\n", "If you consider our example with $M = 50$, output R1 is equal to one _only_ when input R2 is equal to one. Only one out of fifty inputs will have R2 equal to one, so just about 2% of our data will have output R2 equal to one. Although this is not a classification problem, we nonetheless have an issue of imbalanced classes!\n", "\n", "When you have heavily imbalanced classes, neural networks will tend to just learn to predict the majority class; although this is a local minimum, it's one that is very easy to find, and so the networks will almost always do so. The easiest ways to fix this are to either assign the examples weights (and weigh the minority class much more heavily), to undersample the majority class (only take a subset of that data), or to oversample the minority class (repeat that data). For us, the simplest approach will be to repeat the minority class enough times to make it equivalent to the majority class:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Find the underrepresented class indices: R2 = 1\n", "idxs = inputs[:, 1, 1] == 1\n", "\n", "# Oversample the class 48X to make it equal to R2 != 1 class.\n", "inputs_plus = np.repeat(inputs[idxs, :, :], 48, axis=0)\n", "outputs_plus = np.repeat(outputs[idxs, :], 48, axis=0)\n", "\n", "# Create new data set with approximately equal class sizes.\n", "inputs = np.concatenate((inputs, inputs_plus))\n", "outputs = np.concatenate((outputs, outputs_plus))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Why are we repeating the minority class 48 times? After we oversample, what percentage of the data will be in the minority class (R2 = 1) and what percentage will be in the majority class (R2 != 1)?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In order to diagnose over and underfitting, and get an accurate estimate of the performance, we split our data into a training and test set:" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Randomly shuffle the indices 0..S - 1.\n", "# Use these indices to shuffle inputs and outputs in unison.\n", "num_samples = inputs.shape[0]\n", "shuffle_order = np.random.permutation(num_samples)\n", "\n", "# Use 30% of our data for testing, 70% for training.\n", "test_ratio = 0.3\n", "test_indices = shuffle_order[:int(test_ratio * num_samples)]\n", "train_indices = shuffle_order[int(test_ratio * num_samples):]\n", "\n", "test_inputs = inputs[test_indices, :, :]\n", "test_outputs = outputs[test_indices, :]\n", "train_inputs = inputs[train_indices, :, :]\n", "train_outputs = outputs[train_indices, :]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adam Optimization Method" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As in the Kurach et al. paper, we'll use the [Adam optimization algorithm](https://arxiv.org/pdf/1412.6980.pdf). This algorithm resembles Adagrad and RMSProp; a good overview of the different optimization algorithms is [here](http://colinraffel.com/wiki/stochastic_optimization_techniques). The paper that introduces Adam give some nice theoretical bounds, but more importantly, it seems like it has empirically good performance. \n", "\n", "I tested this code using Adam and standard SGD, and found that standard SGD would often converge to high-cost local minima and could not progress further." ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def adam_optimize(params, train, train_inputs, train_outputs,\n", " alpha=0.001, b1=0.9, b2=0.999,\n", " epsilon=1e-8, batch_size=1000):\n", " \"\"\"Implementation of Adam optimization method, with hyperparameters\n", " taken as recommended by the original publication.\"\"\"\n", " # Initialize first and second moment estimates to zero.\n", " # This causes some bias, which is addressed later.\n", " moment1 = [0 for _ in params]\n", " moment2 = [0 for _ in params]\n", " \n", " timestep = 0 # Current optimization step\n", " batch = 0 # Where does this batch start\n", " \n", " converged = False\n", " while not converged:\n", " timestep += 1\n", " \n", " # Train on a small batch.\n", " inputs = train_inputs[batch:batch+batch_size, :, :]\n", " outputs = train_outputs[batch:batch+batch_size, :] \n", " cost, *gradients = train(inputs, outputs)\n", " \n", " # Advance to next batch.\n", " batch = (batch + batch_size) % train_inputs.shape[0]\n", "\n", " # Compute first and second moment estimates.\n", " # These are decaying moving averages; first moment\n", " # uses the gradient, second uses squared gradient.\n", " moment1 = [b1 * m + (1 - b1) * gradient\n", " for (m, gradient)\n", " in zip(moment1, gradients)]\n", " moment2 = [b2 * v + (1 - b2) * gradient ** 2\n", " for (v, gradient)\n", " in zip(moment2, gradients)]\n", " \n", " # Correct for initialization bias and compute new values.\n", " correction1 = 1. / (1 - b1 ** timestep)\n", " correction2 = 1. / (1 - b2 ** timestep)\n", " corrected1 = [correction1 * m for m in moment1]\n", " corrected2 = [correction2 * v for v in moment2]\n", " \n", " # Compute new parameter values.\n", " params_new = [p.get_value() - alpha * m1 / (np.sqrt(m2) + epsilon)\n", " for (p, m1, m2) in zip(params, corrected1, corrected2)]\n", "\n", " # Check for convergence by looking at magnitude of delta.\n", " delta = [abs(p.get_value() - p_new)\n", " for (p, p_new) in zip(params, params_new)]\n", " converged = all((d < 0.5 * alpha).all() for d in delta) \n", " \n", " # Update parameters to new values.\n", " for p, p_new in zip(params, params_new):\n", " p.set_value(p_new.astype('float32'))\n", " \n", " # Provide some output for tracking during runtime.\n", " if timestep % 100 == 1 or converged:\n", " print(\"Cost (t = %4d): \\t%.2f\" % (timestep - 1, cost))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Training with Backpropagation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "After all of that work and preparation, we can finally construct our model and train it:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false, "scrolled": false }, "outputs": [], "source": [ "# Initialize neural network parameters.\n", "layer_sizes = [5, 5]\n", "params = list(mlp_weights(num_registers, layer_sizes, gates))\n", "\n", "# Initialize cost and gradients.\n", "num_timesteps = 2\n", "reg_lambda = 0.1\n", "result = run(gates, num_registers, max_int,\n", " num_timesteps, len(layer_sizes),\n", " reg_lambda, params)\n", "init_registers, desired_registers, cost, registers = result\n", "gradients = theano.grad(cost, params)\n", "\n", "# Compile training function to compute gradients.\n", "train = theano.function([init_registers, desired_registers],\n", " [cost] + gradients)\n", "\n", "\n", "# Compile prediction function (registers after one timestep)\n", "predict = theano.function([init_registers], registers[0])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Adam takes about a thousand iterations to fully train the model, printing the cost every 100 iterations:" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Cost (t = 0): \t6014.46\n", "Cost (t = 100): \t5442.26\n", "Cost (t = 200): \t4038.44\n", "Cost (t = 300): \t2068.13\n", "Cost (t = 400): \t1187.40\n", "Cost (t = 500): \t577.50\n", "Cost (t = 600): \t171.71\n", "Cost (t = 666): \t107.83\n" ] } ], "source": [ "adam_optimize(params, train, train_inputs, train_outputs)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have a trained model, we can evaluate its performance on our test set:" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Correct: 100.0%\n" ] } ], "source": [ "def percent_correct(inputs, outputs):\n", " \"\"\"Compute the percent of examples that were computed correctly.\"\"\"\n", " # Convert the one-hot encoding to integers.\n", " result = predict(inputs).argmax(axis=2)\n", " \n", " # Check how many of the registers for each sample\n", " # had the expected result.\n", " num_eq = (result == outputs).sum(axis=1)\n", " \n", " # A sample was correct if *all* of the registers\n", " # were correct. Count correct samples.\n", " all_eq = (num_eq == inputs.shape[1]).sum()\n", " \n", " # Return ratio of correct samples times 100.\n", " return 100 * float(all_eq) / inputs.shape[0]\n", "\n", "print(\"Correct: %.1f%%\" % percent_correct(test_inputs, test_outputs))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our model managed to learn to solve this problem with 100% correctness – unsurprising, given that it was actually just learning to produce a constant circuit, completely independent of the registers!\n", "\n", "This concludes the runnable portion of this blog post." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Random Access Memory Gates\n", "\n", "Extending our model from a register machine to a full random-access machine turns out to be quite straightforward. Recall from the previous post that our machine accesses memory through fuzzy READ and WRITE gates, so all we need to do is\n", "\n", "1. Implement the READ gate.\n", "2. Implement the WRITE gate.\n", "3. Modify the cost function to use memory, rather than the registers.\n", "\n", "Both of these gates are *surprisingly* simple, although the implementation can be somewhat mysterious. The best way to understand the implementation is to use the matrix dimension, figure out what dimensions you expect, and what dimensions every intermediate product should be.\n", "\n", "When reading, we want to average the contribution of every memory cell to the result, weighted by the input probabilities. For example, if $M = 3$, and our pointer is $(0.2, 0.8, 0.0)$, we would take 0.2 of the first cell plus 0.8 of the second cell:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def read(ptr, max_int, mem):\n", " \"\"\"Gate to read from the memory tape.\n", " Return a tuple of the result and the new (unmodified) memory bank.\n", " \n", " ptr: Distribution over locations to read from.\n", " mem: Memory bank.\n", " \n", " ptr – S x M'\n", " mem – S x M' x M\n", " \n", " where\n", " S – number of samples being operated on\n", " M' – number of memory locations\n", " M – number of representable integers\n", " \n", " M = M' always, but distinguishing between them helps keep track of semantics.\n", " \"\"\"\n", " # Reading from memory ends up being a matrix multiplication (per sample),\n", " # but getting it right just involves shuffling the dimensions to be right:\n", " #\n", " # m = mem.transpose(0, 2, 1): S x M x M'\n", " # p = shape_padright(ptr, 1): S x M' x 1\n", " # batched_dot(m, p): S x M x 1\n", " # batched_dot(m, p).flatten(2): S x M\n", " return batched_dot(mem.transpose(0, 2, 1),\n", " shape_padright(ptr, 1)).flatten(2), mem" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Create some input data for this gate and verify that it works as expected.\n", "\n", "The WRITE gate operates on a similar principle. Instead of writing to one location, it writes to *all* locations, with the strength of the writing modulated by the input pointer probabilities. Each memory cell also retains its old values, similarly weighted by the input pointer probabilities. For example, if $M = 3$, and our pointer is $(0.2, 0.8, 0.0)$, the first cell would be 0.8 times its old value plus 0.2 times the new values, the second cell would be 0.2 times the old value plus 0.8 times the new value, and the third cell would keep its old value:" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def write(ptr, val, max_int, mem):\n", " \"\"\"Gate to write to the memory tape.\n", " Return a tuple of the written value and the modified memory bank.\n", " \n", " ptr: Distribution over locations to write to.\n", " val: Distribution over values to write.\n", " mem: Memory bank.\n", " \n", " ptr – S x M'\n", " ptr – S x M\n", " mem – S x M' x M\n", " \n", " where\n", " S – number of samples being operated on\n", " M' – number of memory locations\n", " M – number of representable integers\n", " \n", " M = M' always, but distinguishing between them helps keep track of semantics.\n", " \"\"\"\n", " # As with reading, tracking the dimensions makes this operation simple.\n", " # We want to compute an \"old\" contribution and a \"new\" contribution.\n", " # p = shape_padright(ptr, 1): S x M' x 1\n", " # v = val.dimshuffle(0, 'x', 1): S x 1 x M\n", " # 1 - ptr: S x M'\n", " # J = shape_padright(1 - ptr, 1): S x M' x 1\n", " # old = J * mem: S x M' x M (broadcasting)\n", " # new = p * v: S x M' x M\n", " p = shape_padright(ptr, 1)\n", " v = val.dimshuffle(0, 'x', 1)\n", " j = shape_padright(1 - ptr, 1)\n", " new_mem = j * mem + batched_dot(p, v)\n", " return val, new_mem" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we modify our cost function to look at memory, rather than registers, our model will be the complete NRAM model." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Training Tips and Tricks\n", "\n", "Training this machine can get a bit tricky. Depending on the complexity of the task, it has a tendency to quickly converge to a local minimum and get stuck there. The following are a few tricks to get past these local minima.\n", "\n", "### Gradient Noise\n", "\n", "Add Gaussian noise to the gradients after backpropagation, and let the magnitude of the Gaussian noise decay with the iteration timestep. This forces the model to explore a bit more during the early iterations, and can help it avoid those local minima. (See [this paper](https://arxiv.org/abs/1511.06807).)\n", "\n", "### Gradient Clipping\n", "\n", "During backpropagation, the gradients have a tendency to get quite large for deeper networks. Clipping the gradients to some minimum and maximum values can help remediate this. Theano offers the [`grad_clip` operator](http://deeplearning.net/software/theano/library/gradient.html#theano.gradient.grad_clip) specifically for this purpose.\n", "\n", "### Gradient Normalization\n", "\n", "Normalizing the gradient to some fixed constant magnitude after backpropagation can be helpful, although in my experience this is less important with Adam or similar optimization methods as opposed to straightforward SGD.\n", "\n", "### Curriculum Learning\n", "\n", "Rather than immediately training on your target problem, attempt to break the problem down into incremental steps, and train first on the easiest problem, then a mix of the easiest and harder problems, and so on, gradually increasing the difficulty (by mixing in harder and harder examples in the batches). In my experience, this was necessary for almost all tasks.\n", "\n", "### Entropy Bonus\n", "\n", "In order to encourage the model to explore before settling on a local minimum, add a \"bonus\" (as opposed to penalty) to the cost function for high-entropy distributions. This prevents the model from just outputting a single value early on; decrease the entropy bonus (exponentially) throughout training. Shannon entropy of the probability distributions works nicely:\n", "\n", "$$E(\\vec A) = \\sum_{i=0}^{M-1} A_i \\log A_i.$$\n", "\n", "$E(\\vec A)$ is high when the distribution is spread out, and low when it is concentrated at a single point." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conclusion\n", "\n", "Ultimately, building and training these models takes some practice and time; debugging them when they don't work can be tricky. A combination of the tips and tricks from above, as well as others, can often help coax these models into learning.\n", "\n", "If you would like to play with this model yourself, check out the [Github repository](https://github.com/gibiansky/experiments/tree/master/nram) – it contains all the code necessary to build the full NRAM network, and depends only on Numpy and Theano. You can teach the machine surprisingly complex operations with very few neural network parameters! You can choose one of the tasks from the publication, or invent your own." ] } ], "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.5.0" } }, "nbformat": 4, "nbformat_minor": 0 }