[{"data":1,"prerenderedAt":82},["ShallowReactive",2],{"course-en-neural-networks":3},{"lesson":4,"number":73,"prev":74,"next":78},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":43,"exercises":54},"neural-networks",{"ru":7,"en":8},"","Neural networks and category theory",{"ru":7,"en":10},"A feedforward neural network as JavaScript function composition: neurons, layers, ReLU, why nonlinearity matters, and what category theory describes here.",{"ru":7,"en":12},"Understand how a feedforward neural network is built from functions, with neurons, layers and the network as a composition of layers, and which part of this picture category theory describes.",[14,17,19,21,23,25,27,29,31,33,35,40],{"type":15,"ru":7,"en":16},"text","Let's look at neural networks the way a functional programmer would — as a composition of functions — and connect this to category theory. First, let's recall what a category is: we discussed it in previous chapters.",{"type":15,"ru":7,"en":18},"A category consists of objects, morphisms (arrows between objects) and a composition of morphisms that obeys two laws: identity (every object has an identity morphism, and composing with it changes nothing) and associativity (it doesn't matter where you put the parentheses in a chain of compositions). In programming, types usually play the role of objects, and functions between them play the role of morphisms.",{"type":15,"ru":7,"en":20},"Now let's see how a neural network is built. An artificial neuron multiplies each input by its own weight, adds up the results, adds a bias and passes the resulting number through a nonlinear activation function, for example ReLU: max(0, z).",{"type":15,"ru":7,"en":22},"A layer is several neurons that receive the same inputs. A layer as a whole is a function: a vector of numbers in, a vector of numbers out, one number per neuron. In a feedforward network, the basic architecture, layers form a chain: the output of one layer becomes the input of the next. So the network is a composition of layer functions: f(x) = f3(f2(f1(x))).",{"type":15,"ru":7,"en":24},"Nonlinearity in the hidden layers is essential. Without an activation function each layer is a linear function (more precisely, affine: multiplying by weights plus a bias), and a composition of affine functions is affine again. No matter how many such layers you stack, the network collapses into a single layer and cannot, for example, solve the XOR task from the example below. The output layer, however, may be linear, as in that same example.",{"type":15,"ru":7,"en":26},"The architecture — how many layers, how many neurons in each, which activation functions — is chosen by the designer of the network. Weights and biases, on the other hand, are trainable parameters: they are not passed in when the network is called; a training algorithm finds them, and after that they are fixed. Running a trained network with fixed parameters is a pure function of its input: the same inputs give the same output.",{"type":15,"ru":7,"en":28},"A few words about training. In the most common case (supervised learning) there are examples with correct answers. A loss function returns a number that shows how far the network's answers are from the correct ones. Gradient descent repeatedly nudges every parameter a little in the direction in which the loss decreases. Which way and how much to move each parameter is given by the gradient of the loss, and backpropagation computes it for all parameters at once: the chain rule for differentiating composite functions, applied to the composition of layers from the output back to the input.",{"type":15,"ru":7,"en":30},"Now the same in the language of categories. The objects are spaces of vectors of a given length (in the example below: 2 numbers at the input, 2 in the hidden layer, 1 at the output), and the morphisms are functions between such spaces; each layer is a morphism, and the whole network, being a composition of layers, is a morphism too. By associativity it doesn't matter how you group the layers: pipe(pipe(a, b), c) and pipe(a, pipe(b, c)) are the same function. The identity morphism is a function that returns its input unchanged: add it to the chain and the network stays the same.",{"type":15,"ru":7,"en":32},"It's important not to overstate this connection: here category theory describes how layers fit together, but it does not explain why a network learns. There are attempts to describe training in this language as well, but that is a research topic (for example, the paper \"Backprop as Functor\" by Fong, Spivak and Tuyéras, 2019), and this course does not cover it.",{"type":15,"ru":7,"en":34},"Let's put it all together. Below is a diagram of a small network and the same network in code: a neuron and a layer are functions, and the network is their composition via pipe.",{"type":36,"pseudo":37,"code":38},"code",true,{"ru":7,"en":39},"\u002F\u002F ==== Diagram of the network from the example below ====\n\n           input x: 2 numbers\n                 |\n                 v\n+-------------------------------------+\n| hidden layer: 2 neurons             |\n| neuron = relu(sum(weight * input)   |\n|               + bias)               |\n+-------------------------------------+\n                 |  2 numbers\n                 v\n+-------------------------------------+\n| output layer: 1 neuron              |\n| neuron = sum(weight * input)        |\n|          + bias                     |\n+-------------------------------------+\n                 |\n                 v\n           output y: 1 number\n\nweights and biases are trainable parameters\nthe network is a composition of layers: y = output(hidden(x))",{"type":36,"code":41},{"ru":7,"en":42},"\u002F\u002F ==== The same network in code ====\n\u002F\u002F the parameters are already chosen: this is the XOR solution from the textbook\n\u002F\u002F Goodfellow, Bengio, Courville \"Deep Learning\", section 6.1\n\u002F\u002F there they are set by hand; in a real network training finds them\n\n\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x)\n\n\u002F\u002F activation functions\n\u002F\u002F relu :: Number -> Number\nconst relu = (z) => Math.max(0, z)\n\u002F\u002F identity :: a -> a\nconst identity = (z) => z\n\n\u002F\u002F weighted sum: multiply each input by its weight and add them up\n\u002F\u002F weightedSum :: ([Number], [Number]) -> Number\nconst weightedSum = (weights, inputs) =>\n  inputs.reduce((sum, x, i) => sum + x * weights[i], 0)\n\n\u002F\u002F neuron: the weighted sum of the inputs plus a bias,\n\u002F\u002F passed through the activation function\n\u002F\u002F weights, bias and activation are set when the neuron is created;\n\u002F\u002F when called, it receives only the inputs\n\u002F\u002F neuron :: ([Number], Number, (Number -> Number)) -> [Number] -> Number\nconst neuron = (weights, bias, activation) => (inputs) =>\n  activation(weightedSum(weights, inputs) + bias)\n\n\u002F\u002F layer: several neurons receive the same inputs,\n\u002F\u002F and the output has one number per neuron\n\u002F\u002F layer :: [[Number] -> Number] -> [Number] -> [Number]\nconst layer = (neurons) => (inputs) => neurons.map((n) => n(inputs))\n\n\u002F\u002F hidden layer: 2 numbers -> 2 numbers, relu activation\n\u002F\u002F hidden :: [Number] -> [Number]\nconst hidden = layer([\n  neuron([1, 1], 0, relu),\n  neuron([1, 1], -1, relu),\n])\n\n\u002F\u002F output layer: 2 numbers -> 1 number, no nonlinearity, as in the textbook\n\u002F\u002F output :: [Number] -> [Number]\nconst output = layer([\n  neuron([1, -2], 0, identity),\n])\n\n\u002F\u002F the network is a composition of layers\n\u002F\u002F network :: [Number] -> [Number]\nconst network = pipe(hidden, output)\n\n\u002F\u002F the network's answer as a single number\n\u002F\u002F getAnswer :: [Number] -> Number\nconst getAnswer = pipe(network, ([y]) => y)\n\nfor (const x of [[0, 0], [0, 1], [1, 0], [1, 1]]) {\n  console.log(`${x[0]} XOR ${x[1]} = ${getAnswer(x)}`)\n}\n\u002F\u002F 0 XOR 0 = 0\n\u002F\u002F 0 XOR 1 = 1\n\u002F\u002F 1 XOR 0 = 1\n\u002F\u002F 1 XOR 1 = 0",[44,46,48,50,52],{"ru":7,"en":45},"A neuron multiplies each input by its own weight, adds up the results, adds a bias and passes the number through a nonlinear activation function, for example ReLU: max(0, z).",{"ru":7,"en":47},"A layer is a function from a vector of numbers to a vector of numbers, and a feedforward network is a composition of layer functions: f(x) = f3(f2(f1(x))).",{"ru":7,"en":49},"Without nonlinearity in the hidden layers, a composition of affine layers is affine again: the network collapses into a single layer and cannot, for example, solve the XOR task.",{"ru":7,"en":51},"Weights and biases are found by a training algorithm and then fixed; a trained network with fixed parameters is a pure function of its input.",{"ru":7,"en":53},"Category theory describes how layers fit together, but it does not explain why a network learns.",[55,64],{"task":56,"starter":58,"solution":60,"expected":62},{"ru":7,"en":57},"Take the hidden layer from the lesson and leave it unchanged. Pick the weights and bias of the output neuron (identity activation) so that the network computes OR and then AND, and print the truth tables. Hint: first work out what hidden outputs for the inputs [0, 0], [0, 1], [1, 0] and [1, 1].",{"ru":7,"en":59},"\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x)\n\n\u002F\u002F relu :: Number -> Number, the same as max(0, z)\nconst relu = (z) => (z > 0 ? z : 0)\n\u002F\u002F identity :: a -> a\nconst identity = (z) => z\n\n\u002F\u002F weightedSum :: ([Number], [Number]) -> Number\nconst weightedSum = (weights, inputs) =>\n  inputs.reduce((sum, x, i) => sum + x * weights[i], 0)\n\n\u002F\u002F neuron :: ([Number], Number, (Number -> Number)) -> [Number] -> Number\nconst neuron = (weights, bias, activation) => (inputs) =>\n  activation(weightedSum(weights, inputs) + bias)\n\n\u002F\u002F layer :: [[Number] -> Number] -> [Number] -> [Number]\nconst layer = (neurons) => (inputs) => neurons.map((n) => n(inputs))\n\n\u002F\u002F the hidden layer from the lesson\n\u002F\u002F hidden :: [Number] -> [Number]\nconst hidden = layer([\n  neuron([1, 1], 0, relu),\n  neuron([1, 1], -1, relu),\n])\n\n\u002F\u002F the network: the hidden layer, then one output neuron\n\u002F\u002F gate :: ([Number], Number) -> [Number] -> Number\nconst gate = (weights, bias) =>\n  pipe(hidden, layer([neuron(weights, bias, identity)]), ([y]) => y)\n\n\u002F\u002F your code: pick the weights and the bias\nconst or = gate([0, 0], 0)\nconst and = gate([0, 0], 0)\n\nconst inputs = [[0, 0], [0, 1], [1, 0], [1, 1]]\nfor (const [name, net] of [['OR', or], ['AND', and]]) {\n  for (const x of inputs) {\n    console.log(`${x[0]} ${name} ${x[1]} = ${net(x)}`)\n  }\n}",{"ru":7,"en":61},"\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x)\n\n\u002F\u002F relu :: Number -> Number, the same as max(0, z)\nconst relu = (z) => (z > 0 ? z : 0)\n\u002F\u002F identity :: a -> a\nconst identity = (z) => z\n\n\u002F\u002F weightedSum :: ([Number], [Number]) -> Number\nconst weightedSum = (weights, inputs) =>\n  inputs.reduce((sum, x, i) => sum + x * weights[i], 0)\n\n\u002F\u002F neuron :: ([Number], Number, (Number -> Number)) -> [Number] -> Number\nconst neuron = (weights, bias, activation) => (inputs) =>\n  activation(weightedSum(weights, inputs) + bias)\n\n\u002F\u002F layer :: [[Number] -> Number] -> [Number] -> [Number]\nconst layer = (neurons) => (inputs) => neurons.map((n) => n(inputs))\n\n\u002F\u002F the hidden layer from the lesson\n\u002F\u002F hidden :: [Number] -> [Number]\nconst hidden = layer([\n  neuron([1, 1], 0, relu),\n  neuron([1, 1], -1, relu),\n])\n\n\u002F\u002F the network: the hidden layer, then one output neuron\n\u002F\u002F gate :: ([Number], Number) -> [Number] -> Number\nconst gate = (weights, bias) =>\n  pipe(hidden, layer([neuron(weights, bias, identity)]), ([y]) => y)\n\n\u002F\u002F for the inputs [0, 0], [0, 1], [1, 0], [1, 1]\n\u002F\u002F hidden outputs [0, 0], [1, 0], [1, 0], [2, 1]\n\n\u002F\u002F OR: the first output minus the second gives 0, 1, 1, 1\nconst or = gate([1, -1], 0)\n\u002F\u002F AND: the second output as is gives 0, 0, 0, 1\nconst and = gate([0, 1], 0)\n\nconst inputs = [[0, 0], [0, 1], [1, 0], [1, 1]]\nfor (const [name, net] of [['OR', or], ['AND', and]]) {\n  for (const x of inputs) {\n    console.log(`${x[0]} ${name} ${x[1]} = ${net(x)}`)\n  }\n}",{"ru":7,"en":63},"0 OR 0 = 0\n0 OR 1 = 1\n1 OR 0 = 1\n1 OR 1 = 1\n0 AND 0 = 0\n0 AND 1 = 0\n1 AND 0 = 0\n1 AND 1 = 1",{"task":65,"starter":67,"solution":69,"expected":71},{"ru":7,"en":66},"Check in code that without nonlinearity two layers collapse into one. The deep network consists of two layers with identity activation. The hidden layer has two neurons: one with weights [1, 2] and bias 1, and one with weights [3, -1] and bias 0. The output layer has one neuron with weights [2, 1] and bias -4. Build these layers with a deepWith function that takes the hidden layer's activation as an argument, and find the weights and bias of a single neuron that gives the same answer. The starter compares both networks on the inputs [0, 0], [1, 0], [0, 1] and [2, 3], then puts relu instead of identity into the hidden layer and compares the networks again on the input [0, 1].",{"ru":7,"en":68},"\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x)\n\n\u002F\u002F relu :: Number -> Number, the same as max(0, z)\nconst relu = (z) => (z > 0 ? z : 0)\n\u002F\u002F identity :: a -> a\nconst identity = (z) => z\n\n\u002F\u002F weightedSum :: ([Number], [Number]) -> Number\nconst weightedSum = (weights, inputs) =>\n  inputs.reduce((sum, x, i) => sum + x * weights[i], 0)\n\n\u002F\u002F neuron :: ([Number], Number, (Number -> Number)) -> [Number] -> Number\nconst neuron = (weights, bias, activation) => (inputs) =>\n  activation(weightedSum(weights, inputs) + bias)\n\n\u002F\u002F layer :: [[Number] -> Number] -> [Number] -> [Number]\nconst layer = (neurons) => (inputs) => neurons.map((n) => n(inputs))\n\n\u002F\u002F two layers; the hidden layer's activation is a parameter\n\u002F\u002F deepWith :: (Number -> Number) -> [Number] -> Number\n\u002F\u002F your code\n\n\u002F\u002F deep :: [Number] -> Number\nconst deep = deepWith(identity)\n\n\u002F\u002F one neuron with the same answer as deep\n\u002F\u002F single :: [Number] -> Number\n\u002F\u002F your code\n\nfor (const x of [[0, 0], [1, 0], [0, 1], [2, 3]]) {\n  console.log(`[${x}]: deep = ${deep(x)}, single = ${single(x)}`)\n}\n\n\u002F\u002F relu instead of identity in the hidden layer\nconsole.log(`with relu, [0,1]: deep = ${deepWith(relu)([0, 1])}, single = ${single([0, 1])}`)",{"ru":7,"en":70},"\u002F\u002F pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z\nconst pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x)\n\n\u002F\u002F relu :: Number -> Number, the same as max(0, z)\nconst relu = (z) => (z > 0 ? z : 0)\n\u002F\u002F identity :: a -> a\nconst identity = (z) => z\n\n\u002F\u002F weightedSum :: ([Number], [Number]) -> Number\nconst weightedSum = (weights, inputs) =>\n  inputs.reduce((sum, x, i) => sum + x * weights[i], 0)\n\n\u002F\u002F neuron :: ([Number], Number, (Number -> Number)) -> [Number] -> Number\nconst neuron = (weights, bias, activation) => (inputs) =>\n  activation(weightedSum(weights, inputs) + bias)\n\n\u002F\u002F layer :: [[Number] -> Number] -> [Number] -> [Number]\nconst layer = (neurons) => (inputs) => neurons.map((n) => n(inputs))\n\n\u002F\u002F two layers; the hidden layer's activation is a parameter\n\u002F\u002F deepWith :: (Number -> Number) -> [Number] -> Number\nconst deepWith = (activation) => pipe(\n  layer([\n    neuron([1, 2], 1, activation),\n    neuron([3, -1], 0, activation),\n  ]),\n  layer([neuron([2, 1], -4, identity)]),\n  ([y]) => y,\n)\n\n\u002F\u002F deep :: [Number] -> Number\nconst deep = deepWith(identity)\n\n\u002F\u002F substitute the hidden layer into the output neuron:\n\u002F\u002F 2 * (x1 + 2 * x2 + 1) + (3 * x1 - x2) - 4 = 5 * x1 + 3 * x2 - 2\n\u002F\u002F single :: [Number] -> Number\nconst single = pipe(layer([neuron([5, 3], -2, identity)]), ([y]) => y)\n\nfor (const x of [[0, 0], [1, 0], [0, 1], [2, 3]]) {\n  console.log(`[${x}]: deep = ${deep(x)}, single = ${single(x)}`)\n}\n\n\u002F\u002F with relu the second hidden neuron outputs 0 instead of -1 for the input [0, 1],\n\u002F\u002F and the answers diverge: the single-neuron formula no longer fits\nconsole.log(`with relu, [0,1]: deep = ${deepWith(relu)([0, 1])}, single = ${single([0, 1])}`)",{"ru":7,"en":72},"[0,0]: deep = -2, single = -2\n[1,0]: deep = 3, single = 3\n[0,1]: deep = 1, single = 1\n[2,3]: deep = 17, single = 17\nwith relu, [0,1]: deep = 2, single = 1",24,{"slug":75,"title":76},"maybe-either",{"ru":7,"en":77},"Maybe and Either",{"slug":79,"title":80},"fp-in-typescript-and-effect",{"ru":7,"en":81},"FP in TypeScript and Effect",1792684725081]