4 lines
128 KiB
JavaScript
4 lines
128 KiB
JavaScript
var documenterSearchIndex = {"docs":
|
||
[{"location":"training/optimisers/#Optimisers-1","page":"Optimisers","title":"Optimisers","text":"","category":"section"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"Consider a simple linear regression. We create some dummy data, calculate a loss, and backpropagate to calculate gradients for the parameters W and b.","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"using Flux\n\nW = rand(2, 5)\nb = rand(2)\n\npredict(x) = (W * x) .+ b\nloss(x, y) = sum((predict(x) .- y).^2)\n\nx, y = rand(5), rand(2) # Dummy data\nl = loss(x, y) # ~ 3\n\nθ = Params([W, b])\ngrads = gradient(() -> loss(x, y), θ)","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"We want to update each parameter, using the gradient, in order to improve (reduce) the loss. Here's one way to do that:","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"using Flux.Optimise: update!\n\nη = 0.1 # Learning Rate\nfor p in (W, b)\n update!(p, -η * grads[p])\nend","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"Running this will alter the parameters W and b and our loss should go down. Flux provides a more general way to do optimiser updates like this.","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"opt = Descent(0.1) # Gradient descent with learning rate 0.1\n\nfor p in (W, b)\n update!(opt, p, grads[p])\nend","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"An optimiser update! accepts a parameter and a gradient, and updates the parameter according to the chosen rule. We can also pass opt to our training loop, which will update all parameters of the model in a loop. However, we can now easily replace Descent with a more advanced optimiser such as ADAM.","category":"page"},{"location":"training/optimisers/#Optimiser-Reference-1","page":"Optimisers","title":"Optimiser Reference","text":"","category":"section"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"All optimisers return an object that, when passed to train!, will update the parameters passed to it.","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"Flux.Optimise.update!\nDescent\nMomentum\nNesterov\nRMSProp\nADAM\nRADAM\nAdaMax\nADAGrad\nADADelta\nAMSGrad\nNADAM\nADAMW","category":"page"},{"location":"training/optimisers/#Flux.Optimise.update!","page":"Optimisers","title":"Flux.Optimise.update!","text":"update!(x, x̄)\n\nUpdate the array x according to x .-= x̄.\n\n\n\n\n\nupdate!(opt, p, g)\nupdate!(opt, ps::Params, gs)\n\nPerform an update step of the parameters ps (or the single parameter p) according to optimizer opt and the gradients gs (the gradient g).\n\nAs a result, the parameters are mutated and the optimizer's internal state may change.\n\n\n\n\n\n","category":"function"},{"location":"training/optimisers/#Flux.Optimise.Descent","page":"Optimisers","title":"Flux.Optimise.Descent","text":"Descent(η = 0.1)\n\nClassic gradient descent optimiser with learning rate η. For each parameter p and its gradient δp, this runs p -= η*δp\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\n\nExamples\n\nopt = Descent()\n\nopt = Descent(0.3)\n\nps = params(model)\n\ngs = gradient(ps) do\n loss(x, y)\nend\n\nFlux.Optimise.update!(opt, ps, gs)\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.Momentum","page":"Optimisers","title":"Flux.Optimise.Momentum","text":"Momentum(η = 0.01, ρ = 0.9)\n\nGradient descent optimizer with learning rate η and momentum ρ.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\nMomentum (ρ): Controls the acceleration of gradient descent in the prominent direction, in effect dampening oscillations.\n\nExamples\n\nopt = Momentum()\n\nopt = Momentum(0.01, 0.99)\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.Nesterov","page":"Optimisers","title":"Flux.Optimise.Nesterov","text":"Nesterov(η = 0.001, ρ = 0.9)\n\nGradient descent optimizer with learning rate η and Nesterov momentum ρ.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\nNesterov momentum (ρ): Controls the acceleration of gradient descent in the prominent direction, in effect dampening oscillations.\n\nExamples\n\nopt = Nesterov()\n\nopt = Nesterov(0.003, 0.95)\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.RMSProp","page":"Optimisers","title":"Flux.Optimise.RMSProp","text":"RMSProp(η = 0.001, ρ = 0.9)\n\nOptimizer using the RMSProp algorithm. Often a good choice for recurrent networks. Parameters other than learning rate generally don't need tuning.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\nMomentum (ρ): Controls the acceleration of gradient descent in the prominent direction, in effect dampening oscillations.\n\nExamples\n\nopt = RMSProp()\n\nopt = RMSProp(0.002, 0.95)\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.ADAM","page":"Optimisers","title":"Flux.Optimise.ADAM","text":"ADAM(η = 0.001, β::Tuple = (0.9, 0.999))\n\nADAM optimiser.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\nDecay of momentums (β::Tuple): Exponential decay for the first (β1) and the second (β2) momentum estimate.\n\nExamples\n\nopt = ADAM()\n\nopt = ADAM(0.001, (0.9, 0.8))\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.RADAM","page":"Optimisers","title":"Flux.Optimise.RADAM","text":"RADAM(η = 0.001, β::Tuple = (0.9, 0.999))\n\nRectified ADAM optimizer.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\nDecay of momentums (β::Tuple): Exponential decay for the first (β1) and the second (β2) momentum estimate.\n\nExamples\n\nopt = RADAM()\n\nopt = RADAM(0.001, (0.9, 0.8))\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.AdaMax","page":"Optimisers","title":"Flux.Optimise.AdaMax","text":"AdaMax(η = 0.001, β::Tuple = (0.9, 0.999))\n\nAdaMax is a variant of ADAM based on the ∞-norm.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\nDecay of momentums (β::Tuple): Exponential decay for the first (β1) and the second (β2) momentum estimate.\n\nExamples\n\nopt = AdaMax()\n\nopt = AdaMax(0.001, (0.9, 0.995))\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.ADAGrad","page":"Optimisers","title":"Flux.Optimise.ADAGrad","text":"ADAGrad(η = 0.1)\n\nADAGrad optimizer. It has parameter specific learning rates based on how frequently it is updated. Parameters don't need tuning.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\n\nExamples\n\nopt = ADAGrad()\n\nopt = ADAGrad(0.001)\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.ADADelta","page":"Optimisers","title":"Flux.Optimise.ADADelta","text":"ADADelta(ρ = 0.9)\n\nADADelta is a version of ADAGrad adapting its learning rate based on a window of past gradient updates. Parameters don't need tuning.\n\nParameters\n\nRho (ρ): Factor by which the gradient is decayed at each time step.\n\nExamples\n\nopt = ADADelta()\n\nopt = ADADelta(0.89)\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.AMSGrad","page":"Optimisers","title":"Flux.Optimise.AMSGrad","text":"AMSGrad(η = 0.001, β::Tuple = (0.9, 0.999))\n\nThe AMSGrad version of the ADAM optimiser. Parameters don't need tuning.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\nDecay of momentums (β::Tuple): Exponential decay for the first (β1) and the second (β2) momentum estimate.\n\nExamples\n\nopt = AMSGrad()\n\nopt = AMSGrad(0.001, (0.89, 0.995))\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.NADAM","page":"Optimisers","title":"Flux.Optimise.NADAM","text":"NADAM(η = 0.001, β::Tuple = (0.9, 0.999))\n\nNADAM is a Nesterov variant of ADAM. Parameters don't need tuning.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\nDecay of momentums (β::Tuple): Exponential decay for the first (β1) and the second (β2) momentum estimate.\n\nExamples\n\nopt = NADAM()\n\nopt = NADAM(0.002, (0.89, 0.995))\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.ADAMW","page":"Optimisers","title":"Flux.Optimise.ADAMW","text":"ADAMW(η = 0.001, β::Tuple = (0.9, 0.999), decay = 0)\n\nADAMW is a variant of ADAM fixing (as in repairing) its weight decay regularization.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\nDecay of momentums (β::Tuple): Exponential decay for the first (β1) and the second (β2) momentum estimate.\ndecay: Decay applied to weights during optimisation.\n\nExamples\n\nopt = ADAMW()\n\nopt = ADAMW(0.001, (0.89, 0.995), 0.1)\n\n\n\n\n\n","category":"function"},{"location":"training/optimisers/#Optimiser-Interface-1","page":"Optimisers","title":"Optimiser Interface","text":"","category":"section"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"Flux's optimisers are built around a struct that holds all the optimiser parameters along with a definition of how to apply the update rule associated with it. We do this via the apply! function which takes the optimiser as the first argument followed by the parameter and its corresponding gradient.","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"In this manner Flux also allows one to create custom optimisers to be used seamlessly. Let's work this with a simple example.","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"mutable struct Momentum\n eta\n rho\n velocity\nend\n\nMomentum(eta::Real, rho::Real) = Momentum(eta, rho, IdDict())","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"The Momentum type will act as our optimiser in this case. Notice that we have added all the parameters as fields, along with the velocity which we will use as our state dictionary. Each parameter in our models will get an entry in there. We can now define the rule applied when this optimiser is invoked.","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"function Flux.Optimise.apply!(o::Momentum, x, Δ)\n η, ρ = o.eta, o.rho\n v = get!(o.velocity, x, zero(x))::typeof(x)\n @. v = ρ * v - η * Δ\n @. Δ = -v\nend","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"This is the basic definition of a Momentum update rule given by:","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"v = ρ * v - η * Δ\nw = w - v","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"The apply! defines the update rules for an optimiser opt, given the parameters and gradients. It returns the updated gradients. Here, every parameter x is retrieved from the running state v and subsequently updates the state of the optimiser.","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"Flux internally calls on this function via the update! function. It shares the API with apply! but ensures that multiple parameters are handled gracefully.","category":"page"},{"location":"training/optimisers/#Composing-Optimisers-1","page":"Optimisers","title":"Composing Optimisers","text":"","category":"section"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"Flux defines a special kind of optimiser simply called Optimiser which takes in arbitrary optimisers as input. Its behaviour is similar to the usual optimisers, but differs in that it acts by calling the optimisers listed in it sequentially. Each optimiser produces a modified gradient that will be fed into the next, and the resultant update will be applied to the parameter as usual. A classic use case is where adding decays is desirable. Flux defines some basic decays including ExpDecay, InvDecay etc.","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"opt = Optimiser(ExpDecay(0.001, 0.1, 1000, 1e-4), Descent())","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"Here we apply exponential decay to the Descent optimiser. The defaults of ExpDecay say that its learning rate will be decayed every 1000 steps. It is then applied like any optimiser.","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"w = randn(10, 10)\nw1 = randn(10,10)\nps = Params([w, w1])\n\nloss(x) = Flux.mse(w * x, w1 * x)\n\nloss(rand(10)) # around 9\n\nfor t = 1:10^5\n θ = Params([w, w1])\n θ̄ = gradient(() -> loss(rand(10)), θ)\n Flux.Optimise.update!(opt, θ, θ̄)\nend\n\nloss(rand(10)) # around 0.9","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"In this manner it is possible to compose optimisers for some added flexibility.","category":"page"},{"location":"training/optimisers/#Decays-1","page":"Optimisers","title":"Decays","text":"","category":"section"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"Similar to optimisers, Flux also defines some simple decays that can be used in conjunction with other optimisers, or standalone.","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"ExpDecay\nInvDecay\nWeightDecay","category":"page"},{"location":"training/optimisers/#Flux.Optimise.ExpDecay","page":"Optimisers","title":"Flux.Optimise.ExpDecay","text":"ExpDecay(η = 0.001, decay = 0.1, decay_step = 1000, clip = 1e-4)\n\nDiscount the learning rate η by the factor decay every decay_step steps till a minimum of clip.\n\nParameters\n\nLearning rate (η): Amount by which gradients are discounted before updating the weights.\ndecay: Factor by which the learning rate is discounted.\ndecay_step: Schedule decay operations by setting the number of steps between two decay operations.\nclip: Minimum value of learning rate.\n\nExamples\n\nTo apply exponential decay to an optimiser:\n\nOptimiser(ExpDecay(..), Opt(..))\n\nopt = Optimiser(ExpDecay(), ADAM())\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.InvDecay","page":"Optimisers","title":"Flux.Optimise.InvDecay","text":"InvDecay(γ = 0.001)\n\nApply inverse time decay to an optimiser, so that the effective step size at iteration n is eta / (1 + γ * n) where eta is the initial step size. The wrapped optimiser's step size is not modified.\n\nExamples\n\nOptimiser(InvDecay(..), Opt(..))\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.WeightDecay","page":"Optimisers","title":"Flux.Optimise.WeightDecay","text":"WeightDecay(wd = 0)\n\nDecay weights by wd.\n\nParameters\n\nWeight decay (wd)\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Gradient-Clipping-1","page":"Optimisers","title":"Gradient Clipping","text":"","category":"section"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"Gradient clipping is useful for training recurrent neural networks, which have a tendency to suffer from the exploding gradient problem. An example usage is","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"opt = Optimiser(ClipValue(1e-3), ADAM(1e-3))","category":"page"},{"location":"training/optimisers/#","page":"Optimisers","title":"Optimisers","text":"ClipValue\nClipNorm","category":"page"},{"location":"training/optimisers/#Flux.Optimise.ClipValue","page":"Optimisers","title":"Flux.Optimise.ClipValue","text":"ClipValue(thresh)\n\nClip gradients when their absolute value exceeds thresh.\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.ClipNorm","page":"Optimisers","title":"Flux.Optimise.ClipNorm","text":"ClipNorm(thresh)\n\nClip gradients when their L2 norm exceeds thresh.\n\n\n\n\n\n","category":"type"},{"location":"models/regularisation/#Regularisation-1","page":"Regularisation","title":"Regularisation","text":"","category":"section"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"Applying regularisation to model parameters is straightforward. We just need to apply an appropriate regulariser, such as norm, to each model parameter and add the result to the overall loss.","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"For example, say we have a simple regression.","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"using Flux: crossentropy\nm = Dense(10, 5)\nloss(x, y) = crossentropy(softmax(m(x)), y)","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"We can regularise this by taking the (L2) norm of the parameters, m.W and m.b.","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"using LinearAlgebra\n\npenalty() = norm(m.W) + norm(m.b)\nloss(x, y) = crossentropy(softmax(m(x)), y) + penalty()","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"When working with layers, Flux provides the params function to grab all parameters at once. We can easily penalise everything with sum(norm, params).","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"julia> params(m)\n2-element Array{Any,1}:\n param([0.355408 0.533092; … 0.430459 0.171498])\n param([0.0, 0.0, 0.0, 0.0, 0.0])\n\njulia> sum(norm, params(m))\n26.01749952921026","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"Here's a larger example with a multi-layer perceptron.","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"m = Chain(\n Dense(28^2, 128, relu),\n Dense(128, 32, relu),\n Dense(32, 10), softmax)\n\nloss(x, y) = crossentropy(m(x), y) + sum(norm, params(m))\n\nloss(rand(28^2), rand(10))","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"One can also easily add per-layer regularisation via the activations function:","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"julia> using Flux: activations\n\njulia> c = Chain(Dense(10, 5, σ), Dense(5, 2), softmax)\nChain(Dense(10, 5, σ), Dense(5, 2), softmax)\n\njulia> activations(c, rand(10))\n3-element Array{Any,1}:\n Float32[0.84682214, 0.6704139, 0.42177814, 0.257832, 0.36255655]\n Float32[0.1501253, 0.073269576] \n Float32[0.5192045, 0.48079553] \n\njulia> sum(norm, ans)\n2.1166067f0","category":"page"},{"location":"models/regularisation/#","page":"Regularisation","title":"Regularisation","text":"Flux.activations","category":"page"},{"location":"models/regularisation/#Flux.activations","page":"Regularisation","title":"Flux.activations","text":"activations(c::Chain, input)\n\nCalculate the forward results of each layers in Chain c with input as model input.\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Utility-Functions-1","page":"Utility Functions","title":"Utility Functions","text":"","category":"section"},{"location":"utilities/#","page":"Utility Functions","title":"Utility Functions","text":"Flux contains some utility functions for working with data; these functions help create inputs for your models or batch your dataset. Other functions can be used to initialize your layers or to regularly execute callback functions.","category":"page"},{"location":"utilities/#Working-with-Data-1","page":"Utility Functions","title":"Working with Data","text":"","category":"section"},{"location":"utilities/#","page":"Utility Functions","title":"Utility Functions","text":"Flux.unsqueeze\nFlux.stack\nFlux.unstack\nFlux.chunk\nFlux.frequencies\nFlux.batch\nFlux.batchseq\nBase.rpad(v::AbstractVector, n::Integer, p)","category":"page"},{"location":"utilities/#Flux.unsqueeze","page":"Utility Functions","title":"Flux.unsqueeze","text":"unsqueeze(xs, dim)\n\nReturn xs reshaped into an Array one dimensionality higher than xs, where dim indicates in which dimension xs is extended.\n\nExamples\n\njulia> xs = [[1, 2], [3, 4], [5, 6]]\n3-element Array{Array{Int64,1},1}:\n [1, 2]\n [3, 4]\n [5, 6]\n\njulia> Flux.unsqueeze(xs, 1)\n1×3 Array{Array{Int64,1},2}:\n [1, 2] [3, 4] [5, 6]\n\njulia> Flux.unsqueeze([1 2; 3 4], 2)\n2×1×2 Array{Int64,3}:\n[:, :, 1] =\n 1\n 3\n\n[:, :, 2] =\n 2\n 4\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Flux.stack","page":"Utility Functions","title":"Flux.stack","text":"stack(xs, dim)\n\nConcatenate the given Array of Arrays xs into a single Array along the given dimension dim.\n\nExamples\n\njulia> xs = [[1, 2], [3, 4], [5, 6]]\n3-element Array{Array{Int64,1},1}:\n [1, 2]\n [3, 4]\n [5, 6]\n\njulia> Flux.stack(xs, 1)\n3×2 Array{Int64,2}:\n 1 2\n 3 4\n 5 6\n\njulia> cat(xs, dims=1)\n3-element Array{Array{Int64,1},1}:\n [1, 2]\n [3, 4]\n [5, 6]\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Flux.unstack","page":"Utility Functions","title":"Flux.unstack","text":"unstack(xs, dim)\n\nUnroll the given xs into an Array of Arrays along the given dimension dim.\n\nExamples\n\njulia> Flux.unstack([1 3 5 7; 2 4 6 8], 2)\n4-element Array{Array{Int64,1},1}:\n [1, 2]\n [3, 4]\n [5, 6]\n [7, 8]\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Flux.chunk","page":"Utility Functions","title":"Flux.chunk","text":"chunk(xs, n)\n\nSplit xs into n parts.\n\nExamples\n\njulia> Flux.chunk(1:10, 3)\n3-element Array{UnitRange{Int64},1}:\n 1:4\n 5:8\n 9:10\n\njulia> Flux.chunk(collect(1:10), 3)\n3-element Array{SubArray{Int64,1,Array{Int64,1},Tuple{UnitRange{Int64}},true},1}:\n [1, 2, 3, 4]\n [5, 6, 7, 8]\n [9, 10]\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Flux.frequencies","page":"Utility Functions","title":"Flux.frequencies","text":"frequencies(xs)\n\nCount the number of times that each element of xs appears.\n\nExamples\n\njulia> Flux.frequencies(['a','b','b'])\nDict{Char,Int64} with 2 entries:\n 'a' => 1\n 'b' => 2\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Flux.batch","page":"Utility Functions","title":"Flux.batch","text":"batch(xs)\n\nBatch the arrays in xs into a single array.\n\nExamples\n\njulia> Flux.batch([[1,2,3],[4,5,6]])\n3×2 Array{Int64,2}:\n 1 4\n 2 5\n 3 6\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Flux.batchseq","page":"Utility Functions","title":"Flux.batchseq","text":"batchseq(seqs, pad)\n\nTake a list of N sequences, and turn them into a single sequence where each item is a batch of N. Short sequences will be padded by pad.\n\nExamples\n\njulia> Flux.batchseq([[1, 2, 3], [4, 5]], 0)\n3-element Array{Array{Int64,1},1}:\n [1, 4]\n [2, 5]\n [3, 0]\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Base.rpad-Tuple{AbstractArray{T,1} where T,Integer,Any}","page":"Utility Functions","title":"Base.rpad","text":"Return the given sequence padded with p up to a maximum length of n.\n\nExamples\n\njulia> rpad([1, 2], 4, 0)\n4-element Array{Int64,1}:\n 1\n 2\n 0\n 0\n\njulia> rpad([1, 2, 3], 2, 0)\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\n\n\n\n\n","category":"method"},{"location":"utilities/#Layer-Initialization-1","page":"Utility Functions","title":"Layer Initialization","text":"","category":"section"},{"location":"utilities/#","page":"Utility Functions","title":"Utility Functions","text":"These are primarily useful if you are planning to write your own layers. Flux initializes convolutional layers and recurrent cells with glorot_uniform by default. To change the default on an applicable layer, pass the desired function with the init keyword. For example:","category":"page"},{"location":"utilities/#","page":"Utility Functions","title":"Utility Functions","text":"julia> conv = Conv((3, 3), 1 => 8, relu; init=Flux.glorot_normal)\nConv((3, 3), 1=>8, relu)","category":"page"},{"location":"utilities/#","page":"Utility Functions","title":"Utility Functions","text":"Flux.glorot_uniform\nFlux.glorot_normal","category":"page"},{"location":"utilities/#Flux.glorot_uniform","page":"Utility Functions","title":"Flux.glorot_uniform","text":"glorot_uniform(dims...)\n\nReturn an Array of size dims containing random variables taken from a uniform distribution in the interval -x x, where x = sqrt(24 / sum(dims)) / 2.\n\nExamples\n\njulia> Flux.glorot_uniform(2, 3)\n2×3 Array{Float32,2}:\n 0.601094 -0.57414 -0.814925\n 0.900868 0.805994 0.057514\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Flux.glorot_normal","page":"Utility Functions","title":"Flux.glorot_normal","text":"glorot_normal(dims...)\n\nReturn an Array of size dims containing random variables taken from a normal distribution with mean 0 and standard deviation sqrt(2 / sum(dims)).\n\nExamples\n\njulia> Flux.glorot_normal(3, 2)\n3×2 Array{Float32,2}:\n 0.429505 -0.0852891\n 0.523935 0.371009\n -0.223261 0.188052\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Model-Abstraction-1","page":"Utility Functions","title":"Model Abstraction","text":"","category":"section"},{"location":"utilities/#","page":"Utility Functions","title":"Utility Functions","text":"Flux.destructure","category":"page"},{"location":"utilities/#Flux.destructure","page":"Utility Functions","title":"Flux.destructure","text":"destructure(m)\n\nFlatten a model's parameters into a single weight vector.\n\njulia> m = Chain(Dense(10, 5, σ), Dense(5, 2), softmax)\nChain(Dense(10, 5, σ), Dense(5, 2), softmax)\n\njulia> θ, re = destructure(m);\n\njulia> θ\n67-element Array{Float32,1}:\n-0.1407104\n...\n\nThe second return value re allows you to reconstruct the original network after making modifications to the weight vector (for example, with a hypernetwork).\n\njulia> re(θ .* 2)\nChain(Dense(10, 5, σ), Dense(5, 2), softmax)\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Callback-Helpers-1","page":"Utility Functions","title":"Callback Helpers","text":"","category":"section"},{"location":"utilities/#","page":"Utility Functions","title":"Utility Functions","text":"Flux.throttle\nFlux.stop","category":"page"},{"location":"utilities/#Flux.throttle","page":"Utility Functions","title":"Flux.throttle","text":"throttle(f, timeout; leading=true, trailing=false)\n\nReturn a function that when invoked, will only be triggered at most once during timeout seconds.\n\nNormally, the throttled function will run as much as it can, without ever going more than once per wait duration; but if you'd like to disable the execution on the leading edge, pass leading=false. To enable execution on the trailing edge, pass trailing=true.\n\n\n\n\n\n","category":"function"},{"location":"utilities/#Flux.Optimise.stop","page":"Utility Functions","title":"Flux.Optimise.stop","text":"stop()\n\nCall Flux.stop() in a callback to indicate when a callback condition is met. This will trigger the train loop to stop and exit.\n\nExamples\n\ncb = function ()\n accuracy() > 0.9 && Flux.stop()\nend\n\n\n\n\n\n","category":"function"},{"location":"datasets/#Datasets-1","page":"Datasets","title":"Datasets","text":"","category":"section"},{"location":"datasets/#","page":"Datasets","title":"Datasets","text":"Flux includes several standard machine learning datasets.","category":"page"},{"location":"datasets/#","page":"Datasets","title":"Datasets","text":"Flux.Data.Iris.features()\nFlux.Data.Iris.labels()\nFlux.Data.MNIST.images()\nFlux.Data.MNIST.labels()\nFlux.Data.FashionMNIST.images()\nFlux.Data.FashionMNIST.labels()\nFlux.Data.CMUDict.phones()\nFlux.Data.CMUDict.symbols()\nFlux.Data.CMUDict.rawdict()\nFlux.Data.CMUDict.cmudict()\nFlux.Data.Sentiment.train()\nFlux.Data.Sentiment.test()\nFlux.Data.Sentiment.dev()","category":"page"},{"location":"datasets/#Flux.Data.Iris.features-Tuple{}","page":"Datasets","title":"Flux.Data.Iris.features","text":"features()\n\nGet the features of the iris dataset. This is a 4x150 matrix of Float64 elements. It has a row for each feature (sepal length, sepal width, petal length, petal width) and a column for each example.\n\njulia> features = Flux.Data.Iris.features();\n\njulia> summary(features)\n\"4×150 Array{Float64,2}\"\n\njulia> features[:, 1]\n4-element Array{Float64,1}:\n 5.1\n 3.5\n 1.4\n 0.2\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.Iris.labels-Tuple{}","page":"Datasets","title":"Flux.Data.Iris.labels","text":"labels()\n\nGet the labels of the iris dataset, a 150 element array of strings listing the species of each example.\n\njulia> labels = Flux.Data.Iris.labels();\n\njulia> summary(labels)\n\"150-element Array{String,1}\"\n\njulia> labels[1]\n\"Iris-setosa\"\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.MNIST.images-Tuple{}","page":"Datasets","title":"Flux.Data.MNIST.images","text":"images()\nimages(:test)\n\nLoad the MNIST images.\n\nEach image is a 28×28 array of Gray colour values (see Colors.jl).\n\nReturn the 60,000 training images by default; pass :test to retrieve the 10,000 test images.\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.MNIST.labels-Tuple{}","page":"Datasets","title":"Flux.Data.MNIST.labels","text":"labels()\nlabels(:test)\n\nLoad the labels corresponding to each of the images returned from images(). Each label is a number from 0-9.\n\nReturn the 60,000 training labels by default; pass :test to retrieve the 10,000 test labels.\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.FashionMNIST.images-Tuple{}","page":"Datasets","title":"Flux.Data.FashionMNIST.images","text":"images()\nimages(:test)\n\nLoad the Fashion-MNIST images.\n\nEach image is a 28×28 array of Gray colour values (see Colors.jl).\n\nReturn the 60,000 training images by default; pass :test to retrieve the 10,000 test images.\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.FashionMNIST.labels-Tuple{}","page":"Datasets","title":"Flux.Data.FashionMNIST.labels","text":"labels()\nlabels(:test)\n\nLoad the labels corresponding to each of the images returned from images(). Each label is a number from 0-9.\n\nReturn the 60,000 training labels by default; pass :test to retrieve the 10,000 test labels.\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.CMUDict.phones-Tuple{}","page":"Datasets","title":"Flux.Data.CMUDict.phones","text":"phones()\n\nReturn a Vector containing the phones used in the CMU Pronouncing Dictionary.\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.CMUDict.symbols-Tuple{}","page":"Datasets","title":"Flux.Data.CMUDict.symbols","text":"symbols()\n\nReturn a Vector containing the symbols used in the CMU Pronouncing Dictionary. A symbol is a phone with optional auxiliary symbols, indicating for example the amount of stress on the phone.\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.CMUDict.rawdict-Tuple{}","page":"Datasets","title":"Flux.Data.CMUDict.rawdict","text":"rawdict()\n\nReturn the unfiltered CMU Pronouncing Dictionary.\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.CMUDict.cmudict-Tuple{}","page":"Datasets","title":"Flux.Data.CMUDict.cmudict","text":"cmudict()\n\nReturn a filtered CMU Pronouncing Dictionary.\n\nIt is filtered so each word contains only ASCII characters and a combination of word characters (as determined by the regex engine using \\w), '-' and '.'.\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.Sentiment.train-Tuple{}","page":"Datasets","title":"Flux.Data.Sentiment.train","text":"train()\n\nReturn the train split of the Stanford Sentiment Treebank. The data is in treebank format.\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.Sentiment.test-Tuple{}","page":"Datasets","title":"Flux.Data.Sentiment.test","text":"test()\n\nReturn the test split of the Stanford Sentiment Treebank. The data is in treebank format.\n\n\n\n\n\n","category":"method"},{"location":"datasets/#Flux.Data.Sentiment.dev-Tuple{}","page":"Datasets","title":"Flux.Data.Sentiment.dev","text":"dev()\n\nReturn the dev split of the Stanford Sentiment Treebank. The data is in treebank format.\n\n\n\n\n\n","category":"method"},{"location":"data/dataloader/#DataLoader-1","page":"DataLoader","title":"DataLoader","text":"","category":"section"},{"location":"data/dataloader/#","page":"DataLoader","title":"DataLoader","text":"Flux provides the DataLoader type in the Flux.Data module to handle iteration over mini-batches of data. ","category":"page"},{"location":"data/dataloader/#","page":"DataLoader","title":"DataLoader","text":"Flux.Data.DataLoader","category":"page"},{"location":"data/dataloader/#Flux.Data.DataLoader","page":"DataLoader","title":"Flux.Data.DataLoader","text":"DataLoader(data...; batchsize=1, shuffle=false, partial=true)\n\nAn object that iterates over mini-batches of data, each mini-batch containing batchsize observations (except possibly the last one). \n\nTakes as input one or more data tensors, e.g. X in unsupervised learning, X and Y in supervised learning. The last dimension in each tensor is considered to be the observation dimension. \n\nIf shuffle=true, shuffles the observations each time iterations are re-started. If partial=false, drops the last mini-batch if it is smaller than the batchsize.\n\nThe original data is preserved as a tuple in the data field of the DataLoader. \n\nExample usage:\n\nXtrain = rand(10, 100)\ntrain_loader = DataLoader(Xtrain, batchsize=2) \n# iterate over 50 mini-batches of size 2\nfor x in train_loader\n @assert size(x) == (10, 2)\n ...\nend\n\ntrain_loader.data # original dataset\n\nXtrain = rand(10, 100)\nYtrain = rand(100)\ntrain_loader = DataLoader(Xtrain, Ytrain, batchsize=2, shuffle=true) \nfor epoch in 1:100\n for (x, y) in train_loader\n @assert size(x) == (10, 2)\n @assert size(y) == (2,)\n ...\n end\nend\n\n# train for 10 epochs\nusing IterTools: ncycle \nFlux.train!(loss, ps, ncycle(train_loader, 10), opt)\n\n\n\n\n\n","category":"type"},{"location":"performance/#Performance-Tips-1","page":"Performance Tips","title":"Performance Tips","text":"","category":"section"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"All the usual Julia performance tips apply. As always profiling your code is generally a useful way of finding bottlenecks. Below follow some Flux specific tips/reminders.","category":"page"},{"location":"performance/#Don't-use-more-precision-than-you-need-1","page":"Performance Tips","title":"Don't use more precision than you need","text":"","category":"section"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"Flux works great with all kinds of number types. But often you do not need to be working with say Float64 (let alone BigFloat). Switching to Float32 can give you a significant speed up, not because the operations are faster, but because the memory usage is halved. Which means allocations occur much faster. And you use less memory.","category":"page"},{"location":"performance/#Preserve-inputs'-types-1","page":"Performance Tips","title":"Preserve inputs' types","text":"","category":"section"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"Not only should your activation and loss functions be type-stable, they should also preserve the type of their inputs.","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"A very artificial example using an activation function like","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":" my_tanh(x) = Float64(tanh(x))","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"will result in performance on Float32 input orders of magnitude slower than the normal tanh would, because it results in having to use slow mixed type multiplication in the dense layers. Similar situations can occur in the loss function during backpropagation.","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"Which means if you change your data say from Float64 to Float32 (which should give a speedup: see above), you will see a large slow-down.","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"This can occur sneakily, because you can cause type-promotion by interacting with a numeric literals. E.g. the following will have run into the same problem as above:","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":" leaky_tanh(x) = 0.01*x + tanh(x)","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"While one could change the activation function (e.g. to use 0.01f0x), the idiomatic (and safe way) to avoid type casts whenever inputs changes is to use oftype:","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":" leaky_tanh(x) = oftype(x/1, 0.01)*x + tanh(x)","category":"page"},{"location":"performance/#Evaluate-batches-as-Matrices-of-features-1","page":"Performance Tips","title":"Evaluate batches as Matrices of features","text":"","category":"section"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"While it can sometimes be tempting to process your observations (feature vectors) one at a time e.g.","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"function loss_total(xs::AbstractVector{<:Vector}, ys::AbstractVector{<:Vector})\n sum(zip(xs, ys)) do (x, y_target)\n y_pred = model(x) # evaluate the model\n return loss(y_pred, y_target)\n end\nend","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"It is much faster to concatenate them into a matrix, as this will hit BLAS matrix-matrix multiplication, which is much faster than the equivalent sequence of matrix-vector multiplications. The improvement is enough that it is worthwhile allocating new memory to store them contiguously.","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"x_batch = reduce(hcat, xs)\ny_batch = reduce(hcat, ys)\n...\nfunction loss_total(x_batch::Matrix, y_batch::Matrix)\n y_preds = model(x_batch)\n sum(loss.(y_preds, y_batch))\nend","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"When doing this kind of concatenation use reduce(hcat, xs) rather than hcat(xs...). This will avoid the splatting penalty, and will hit the optimised reduce method.","category":"page"},{"location":"models/advanced/#Advanced-Model-Building-and-Customisation-1","page":"Advanced Model Building","title":"Advanced Model Building and Customisation","text":"","category":"section"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"Here we will try and describe usage of some more advanced features that Flux provides to give more control over model building.","category":"page"},{"location":"models/advanced/#Customising-Parameter-Collection-for-a-Model-1","page":"Advanced Model Building","title":"Customising Parameter Collection for a Model","text":"","category":"section"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"Taking reference from our example Affine layer from the basics.","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"By default all the fields in the Affine type are collected as its parameters, however, in some cases it may be desired to hold other metadata in our \"layers\" that may not be needed for training, and are hence supposed to be ignored while the parameters are collected. With Flux, it is possible to mark the fields of our layers that are trainable in two ways.","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"The first way of achieving this is through overloading the trainable function.","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"julia> @functor Affine\n\njulia> a = Affine(rand(3,3), rand(3))\nAffine{Array{Float64,2},Array{Float64,1}}([0.66722 0.774872 0.249809; 0.843321 0.403843 0.429232; 0.683525 0.662455 0.065297], [0.42394, 0.0170927, 0.544955])\n\njulia> Flux.params(a) # default behavior\nParams([[0.66722 0.774872 0.249809; 0.843321 0.403843 0.429232; 0.683525 0.662455 0.065297], [0.42394, 0.0170927, 0.544955]])\n\njulia> Flux.trainable(a::Affine) = (a.W, a.b,)\n\njulia> Flux.params(a)\nParams([[0.66722 0.774872 0.249809; 0.843321 0.403843 0.429232; 0.683525 0.662455 0.065297]])","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"Only the fields returned by trainable will be collected as trainable parameters of the layer when calling Flux.params.","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"Another way of achieving this is through the @functor macro directly. Here, we can mark the fields we are interested in by grouping them in the second argument:","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"Flux.@functor Affine (W,)","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"However, doing this requires the struct to have a corresponding constructor that accepts those parameters.","category":"page"},{"location":"models/advanced/#Freezing-Layer-Parameters-1","page":"Advanced Model Building","title":"Freezing Layer Parameters","text":"","category":"section"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"When it is desired to not include all the model parameters (for e.g. transfer learning), we can simply not pass in those layers into our call to params.","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"Consider a simple multi-layer perceptron model where we want to avoid optimising the first two Dense layers. We can obtain this using the slicing features Chain provides:","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"m = Chain(\n Dense(784, 64, relu),\n Dense(64, 64, relu),\n Dense(32, 10)\n )\n\nps = Flux.params(m[3:end])","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"The Zygote.Params object ps now holds a reference to only the parameters of the layers passed to it.","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"During training, the gradients will only be computed for (and applied to) the last Dense layer, therefore only that would have its parameters changed.","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"Flux.params also takes multiple inputs to make it easy to collect parameters from heterogenous models with a single call. A simple demonstration would be if we wanted to omit optimising the second Dense layer in the previous example. It would look something like this:","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"Flux.params(m[1], m[3:end])","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"Sometimes, a more fine-tuned control is needed. We can freeze a specific parameter of a specific layer which already entered a Params object ps, by simply deleting it from ps:","category":"page"},{"location":"models/advanced/#","page":"Advanced Model Building","title":"Advanced Model Building","text":"ps = params(m)\ndelete!(ps, m[2].b) ","category":"page"},{"location":"ecosystem/#The-Julia-Ecosystem-1","page":"The Julia Ecosystem","title":"The Julia Ecosystem","text":"","category":"section"},{"location":"ecosystem/#","page":"The Julia Ecosystem","title":"The Julia Ecosystem","text":"One of the main strengths of Julia lies in an ecosystem of packages globally providing a rich and consistent user experience.","category":"page"},{"location":"ecosystem/#","page":"The Julia Ecosystem","title":"The Julia Ecosystem","text":"This is a non-exhaustive list of Julia packages, nicely complementing Flux in typical machine learning and deep learning workflows:","category":"page"},{"location":"ecosystem/#","page":"The Julia Ecosystem","title":"The Julia Ecosystem","text":"ArgParse.jl: package for parsing command-line arguments to Julia programs.\nAugmentor.jl: a fast image augmentation library in Julia for machine learning.\nBSON.jl: package for working with the Binary JSON serialisation format\nDataFrames.jl: in-memory tabular data in Julia\nDrWatson.jl: a scientific project assistant software\nMLDatasets.jl: utility package for accessing common machine learning datasets\nOnlineStats.jl: single-pass algorithms for statistics\nParameters.jl: types with default field values, keyword constructors and (un-)pack macros\nProgressMeters.jl: progress meters for long-running computations\nTensorBoardLogger.jl: easy peasy logging to tensorboard in Julia","category":"page"},{"location":"ecosystem/#","page":"The Julia Ecosystem","title":"The Julia Ecosystem","text":"This tight integration among Julia pakages is shown in some of the examples in the model-zoo repository.","category":"page"},{"location":"models/nnlib/#NNlib-1","page":"NNlib","title":"NNlib","text":"","category":"section"},{"location":"models/nnlib/#","page":"NNlib","title":"NNlib","text":"Flux re-exports all of the functions exported by the NNlib package.","category":"page"},{"location":"models/nnlib/#Activation-Functions-1","page":"NNlib","title":"Activation Functions","text":"","category":"section"},{"location":"models/nnlib/#","page":"NNlib","title":"NNlib","text":"Non-linearities that go between layers of your model. Note that, unless otherwise stated, activation functions operate on scalars. To apply them to an array you can call σ.(xs), relu.(xs) and so on.","category":"page"},{"location":"models/nnlib/#","page":"NNlib","title":"NNlib","text":"NNlib.celu\nNNlib.elu\nNNlib.gelu\nNNlib.hardsigmoid\nNNlib.hardtanh\nNNlib.leakyrelu\nNNlib.lisht\nNNlib.logcosh\nNNlib.logsigmoid\nNNlib.mish\nNNlib.relu\nNNlib.relu6\nNNlib.rrelu\nNNlib.selu\nNNlib.sigmoid\nNNlib.softplus\nNNlib.softshrink\nNNlib.softsign\nNNlib.swish\nNNlib.tanhshrink\nNNlib.trelu","category":"page"},{"location":"models/nnlib/#NNlib.celu","page":"NNlib","title":"NNlib.celu","text":"celu(x, α=1) = \n (x ≥ 0 ? x : α * (exp(x/α) - 1))\n\nContinuously Differentiable Exponential Linear Units See Continuously Differentiable Exponential Linear Units.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.elu","page":"NNlib","title":"NNlib.elu","text":"elu(x, α=1) =\n x > 0 ? x : α * (exp(x) - 1)\n\nExponential Linear Unit activation function. See Fast and Accurate Deep Network Learning by Exponential Linear Units. You can also specify the coefficient explicitly, e.g. elu(x, 1).\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.gelu","page":"NNlib","title":"NNlib.gelu","text":"gelu(x) = 0.5x * (1 + tanh(√(2/π) * (x + 0.044715x^3)))\n\nGaussian Error Linear Unit activation function.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.hardsigmoid","page":"NNlib","title":"NNlib.hardsigmoid","text":"hardσ(x, a=0.2) = max(0, min(1.0, a * x + 0.5))\n\nSegment-wise linear approximation of sigmoid See: BinaryConnect: Training Deep Neural Networks withbinary weights during propagations\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.hardtanh","page":"NNlib","title":"NNlib.hardtanh","text":"hardtanh(x) = max(-1, min(1, x))\n\nSegment-wise linear approximation of tanh. Cheaper and more computational efficient version of tanh. See: (http://ronan.collobert.org/pub/matos/2004phdthesislip6.pdf)\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.leakyrelu","page":"NNlib","title":"NNlib.leakyrelu","text":"leakyrelu(x, a=0.01) = max(a*x, x)\n\nLeaky Rectified Linear Unit activation function. You can also specify the coefficient explicitly, e.g. leakyrelu(x, 0.01).\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.lisht","page":"NNlib","title":"NNlib.lisht","text":"lisht(x) = x * tanh(x)\n\nNon-Parametric Linearly Scaled Hyperbolic Tangent Activation Function See LiSHT\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.logcosh","page":"NNlib","title":"NNlib.logcosh","text":"logcosh(x)\n\nReturn log(cosh(x)) which is computed in a numerically stable way.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.logsigmoid","page":"NNlib","title":"NNlib.logsigmoid","text":"logσ(x)\n\nReturn log(σ(x)) which is computed in a numerically stable way.\n\njulia> logσ(0)\n-0.6931471805599453\njulia> logσ.([-100, -10, 100])\n3-element Array{Float64,1}:\n -100.0\n -10.000045398899218\n -3.720075976020836e-44\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.mish","page":"NNlib","title":"NNlib.mish","text":"mish(x) = x * tanh(softplus(x))\n\nSelf Regularized Non-Monotonic Neural Activation Function See Mish: A Self Regularized Non-Monotonic Neural Activation Function.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.relu","page":"NNlib","title":"NNlib.relu","text":"relu(x) = max(0, x)\n\nRectified Linear Unit activation function.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.relu6","page":"NNlib","title":"NNlib.relu6","text":"relu6(x) = min(max(0, x), 6)\n\nRectified Linear Unit activation function capped at 6. See Convolutional Deep Belief Networks on CIFAR-10\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.rrelu","page":"NNlib","title":"NNlib.rrelu","text":"rrelu(x, l=1/8, u=1/3) = max(a*x, x)\n\na = randomly sampled from uniform distribution U(l, u)\n\nRandomized Leaky Rectified Linear Unit activation function. You can also specify the bound explicitly, e.g. rrelu(x, 0.0, 1.0).\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.selu","page":"NNlib","title":"NNlib.selu","text":"selu(x) = λ * (x ≥ 0 ? x : α * (exp(x) - 1))\n\nλ ≈ 1.0507\nα ≈ 1.6733\n\nScaled exponential linear units. See Self-Normalizing Neural Networks.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.sigmoid","page":"NNlib","title":"NNlib.sigmoid","text":"σ(x) = 1 / (1 + exp(-x))\n\nClassic sigmoid activation function.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.softplus","page":"NNlib","title":"NNlib.softplus","text":"softplus(x) = log(exp(x) + 1)\n\nSee Deep Sparse Rectifier Neural Networks.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.softshrink","page":"NNlib","title":"NNlib.softshrink","text":"softshrink(x, λ=0.5) = \n (x ≥ λ ? x - λ : (-λ ≥ x ? x + λ : 0))\n\nSee Softshrink Activation Function\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.softsign","page":"NNlib","title":"NNlib.softsign","text":"softsign(x) = x / (1 + |x|)\n\nSee Quadratic Polynomials Learn Better Image Features.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.swish","page":"NNlib","title":"NNlib.swish","text":"swish(x) = x * σ(x)\n\nSelf-gated activation function. See Swish: a Self-Gated Activation Function.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.tanhshrink","page":"NNlib","title":"NNlib.tanhshrink","text":"tanhshrink(x) = x - tanh(x)\n\nSee Tanhshrink Activation Function\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.trelu","page":"NNlib","title":"NNlib.trelu","text":"trelu(x, theta = 1.0) = x > theta ? x : 0\n\nThreshold Gated Rectified Linear See ThresholdRelu\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#Softmax-1","page":"NNlib","title":"Softmax","text":"","category":"section"},{"location":"models/nnlib/#","page":"NNlib","title":"NNlib","text":"NNlib.softmax\nNNlib.logsoftmax","category":"page"},{"location":"models/nnlib/#NNlib.softmax","page":"NNlib","title":"NNlib.softmax","text":"softmax(x; dims=1)\n\nSoftmax turns input array x into probability distributions that sum to 1 along the dimensions specified by dims. It is semantically equivalent to the following:\n\nsoftmax(x; dims=1) = exp.(x) ./ sum(exp.(x), dims=dims)\n\nwith additional manipulations enhancing numerical stability.\n\nFor a matrix input x it will by default (dims=1) treat it as a batch of vectors, with each column independent. Keyword dims=2 will instead treat rows independently, etc...\n\njulia> softmax([1, 2, 3])\n3-element Array{Float64,1}:\n 0.0900306\n 0.244728\n 0.665241\n\nSee also logsoftmax.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.logsoftmax","page":"NNlib","title":"NNlib.logsoftmax","text":"logsoftmax(x; dims=1)\n\nComputes the log of softmax in a more numerically stable way than directly taking log.(softmax(xs)). Commonly used in computing cross entropy loss.\n\nIt is semantically equivalent to the following:\n\nlogsoftmax(x; dims=1) = x .- log.(sum(exp.(x), dims=dims))\n\nSee also softmax.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#Pooling-1","page":"NNlib","title":"Pooling","text":"","category":"section"},{"location":"models/nnlib/#","page":"NNlib","title":"NNlib","text":"NNlib.maxpool\nNNlib.meanpool","category":"page"},{"location":"models/nnlib/#NNlib.maxpool","page":"NNlib","title":"NNlib.maxpool","text":"maxpool(x, k::NTuple; pad=0, stride=k)\n\nPerform max pool operation with window size k on input tensor x.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.meanpool","page":"NNlib","title":"NNlib.meanpool","text":"meanpool(x, k::NTuple; pad=0, stride=k)\n\nPerform mean pool operation with window size k on input tensor x.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#Convolution-1","page":"NNlib","title":"Convolution","text":"","category":"section"},{"location":"models/nnlib/#","page":"NNlib","title":"NNlib","text":"NNlib.conv\nNNlib.depthwiseconv","category":"page"},{"location":"models/nnlib/#NNlib.conv","page":"NNlib","title":"NNlib.conv","text":"conv(x, w; stride=1, pad=0, dilation=1, flipped=false)\n\nApply convolution filter w to input x. x and w are 3d/4d/5d tensors in 1d/2d/3d convolutions respectively. \n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.depthwiseconv","page":"NNlib","title":"NNlib.depthwiseconv","text":"depthwiseconv(x, w; stride=1, pad=0, dilation=1, flipped=false)\n\nDepthwise convolution operation with filter w on input x. x and w are 3d/4d/5d tensors in 1d/2d/3d convolutions respectively. \n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#Batched-Operations-1","page":"NNlib","title":"Batched Operations","text":"","category":"section"},{"location":"models/nnlib/#","page":"NNlib","title":"NNlib","text":"NNlib.batched_mul\nNNlib.batched_mul!\nNNlib.batched_adjoint\nNNlib.batched_transpose","category":"page"},{"location":"models/nnlib/#NNlib.batched_mul","page":"NNlib","title":"NNlib.batched_mul","text":"batched_mul(A, B) -> C\n\nBatched matrix multiplication. Result has C[:,:,k] == A[:,:,k] * B[:,:,k] for all k.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.batched_mul!","page":"NNlib","title":"NNlib.batched_mul!","text":"batched_mul!(C, A, B) -> C\n\nIn-place batched matrix multiplication, equivalent to mul!(C[:,:,k], A[:,:,k], B[:,:,k]) for all k.\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.batched_adjoint","page":"NNlib","title":"NNlib.batched_adjoint","text":"batched_transpose(A::AbstractArray{T,3})\nbatched_adjoint(A)\n\nEquivalent to applying transpose or adjoint to each matrix A[:,:,k].\n\nThese exist to control how batched_mul behaves, as it operated on such matrix slices of an array with ndims(A)==3.\n\nBatchedTranspose{T, N, S} <: AbstractBatchedMatrix{T, N}\nBatchedAdjoint{T, N, S}\n\nLazy wrappers analogous to Transpose and Adjoint, returned by batched_transpose\n\n\n\n\n\n","category":"function"},{"location":"models/nnlib/#NNlib.batched_transpose","page":"NNlib","title":"NNlib.batched_transpose","text":"batched_transpose(A::AbstractArray{T,3})\nbatched_adjoint(A)\n\nEquivalent to applying transpose or adjoint to each matrix A[:,:,k].\n\nThese exist to control how batched_mul behaves, as it operated on such matrix slices of an array with ndims(A)==3.\n\nBatchedTranspose{T, N, S} <: AbstractBatchedMatrix{T, N}\nBatchedAdjoint{T, N, S}\n\nLazy wrappers analogous to Transpose and Adjoint, returned by batched_transpose\n\n\n\n\n\n","category":"function"},{"location":"saving/#Saving-and-Loading-Models-1","page":"Saving & Loading","title":"Saving and Loading Models","text":"","category":"section"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"You may wish to save models so that they can be loaded and run in a later session. The easiest way to do this is via BSON.jl.","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"Save a model:","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"julia> using Flux\n\njulia> model = Chain(Dense(10,5,relu),Dense(5,2),softmax)\nChain(Dense(10, 5, NNlib.relu), Dense(5, 2), NNlib.softmax)\n\njulia> using BSON: @save\n\njulia> @save \"mymodel.bson\" model","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"Load it again:","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"julia> using Flux\n\njulia> using BSON: @load\n\njulia> @load \"mymodel.bson\" model\n\njulia> model\nChain(Dense(10, 5, NNlib.relu), Dense(5, 2), NNlib.softmax)","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"Models are just normal Julia structs, so it's fine to use any Julia storage format for this purpose. BSON.jl is particularly well supported and most likely to be forwards compatible (that is, models saved now will load in future versions of Flux).","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"note: Note\nIf a saved model's weights are stored on the GPU, the model will not load later on if there is no GPU support available. It's best to move your model to the CPU with cpu(model) before saving it.","category":"page"},{"location":"saving/#Saving-Model-Weights-1","page":"Saving & Loading","title":"Saving Model Weights","text":"","category":"section"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"In some cases it may be useful to save only the model parameters themselves, and rebuild the model architecture in your code. You can use params(model) to get model parameters. You can also use data.(params) to remove tracking.","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"julia> using Flux\n\njulia> model = Chain(Dense(10,5,relu),Dense(5,2),softmax)\nChain(Dense(10, 5, NNlib.relu), Dense(5, 2), NNlib.softmax)\n\njulia> weights = params(model);\n\njulia> using BSON: @save\n\njulia> @save \"mymodel.bson\" weights","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"You can easily load parameters back into a model with Flux.loadparams!.","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"julia> using Flux\n\njulia> model = Chain(Dense(10,5,relu),Dense(5,2),softmax)\nChain(Dense(10, 5, NNlib.relu), Dense(5, 2), NNlib.softmax)\n\njulia> using BSON: @load\n\njulia> @load \"mymodel.bson\" weights\n\njulia> Flux.loadparams!(model, weights)","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"The new model we created will now be identical to the one we saved parameters for.","category":"page"},{"location":"saving/#Checkpointing-1","page":"Saving & Loading","title":"Checkpointing","text":"","category":"section"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"In longer training runs it's a good idea to periodically save your model, so that you can resume if training is interrupted (for example, if there's a power cut). You can do this by saving the model in the callback provided to train!.","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"using Flux: throttle\nusing BSON: @save\n\nm = Chain(Dense(10,5,relu),Dense(5,2),softmax)\n\nevalcb = throttle(30) do\n # Show loss\n @save \"model-checkpoint.bson\" model\nend","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"This will update the \"model-checkpoint.bson\" file every thirty seconds.","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"You can get more advanced by saving a series of models throughout training, for example","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"@save \"model-$(now()).bson\" model","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"will produce a series of models like \"model-2018-03-06T02:57:10.41.bson\". You could also store the current test set loss, so that it's easy to (for example) revert to an older copy of the model if it starts to overfit.","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"@save \"model-$(now()).bson\" model loss = testloss()","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"You can even store optimiser state alongside the model, to resume training exactly where you left off.","category":"page"},{"location":"saving/#","page":"Saving & Loading","title":"Saving & Loading","text":"opt = ADAM()\n@save \"model-$(now()).bson\" model opt","category":"page"},{"location":"models/layers/#Basic-Layers-1","page":"Model Reference","title":"Basic Layers","text":"","category":"section"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"These core layers form the foundation of almost all neural networks.","category":"page"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"Chain\nDense","category":"page"},{"location":"models/layers/#Flux.Chain","page":"Model Reference","title":"Flux.Chain","text":"Chain(layers...)\n\nChain multiple layers / functions together, so that they are called in sequence on a given input.\n\nChain also supports indexing and slicing, e.g. m[2] or m[1:end-1]. m[1:3](x) will calculate the output of the first three layers.\n\nExamples\n\njulia> m = Chain(x -> x^2, x -> x+1);\n\njulia> m(5) == 26\ntrue\n\njulia> m = Chain(Dense(10, 5), Dense(5, 2));\n\njulia> x = rand(10);\n\njulia> m(x) == m[2](m[1](x))\ntrue\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.Dense","page":"Model Reference","title":"Flux.Dense","text":"Dense(in::Integer, out::Integer, σ = identity)\n\nCreate a traditional Dense layer with parameters W and b.\n\ny = σ.(W * x .+ b)\n\nThe input x must be a vector of length in, or a batch of vectors represented as an in × N matrix. The out y will be a vector or batch of length out.\n\nExamples\n\n```jldoctest; setup = :(using Random; Random.seed!(0)) julia> d = Dense(5, 2) Dense(5, 2)\n\njulia> d(rand(5)) 2-element Array{Float32,1}: -0.16210233 0.12311903```\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Convolution-and-Pooling-Layers-1","page":"Model Reference","title":"Convolution and Pooling Layers","text":"","category":"section"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"These layers are used to build convolutional neural networks (CNNs).","category":"page"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"Conv\nMaxPool\nGlobalMaxPool\nMeanPool\nGlobalMeanPool\nDepthwiseConv\nConvTranspose\nCrossCor\nSamePad\nflatten\nFlux.Zeros\nFlux.convfilter\nFlux.depthwiseconvfilter","category":"page"},{"location":"models/layers/#Flux.Conv","page":"Model Reference","title":"Flux.Conv","text":"Conv(filter, in => out, σ = identity; init = glorot_uniform,\n stride = 1, pad = 0, dilation = 1)\n\nfilter = (2,2)\nin = 1\nout = 16\nConv((2, 2), 1=>16, relu)\n\nStandard convolutional layer. filter should be a tuple like (2, 2). in and out specify the number of input and output channels respectively.\n\nData should be stored in WHCN order (width, height, # channels, batch size). In other words, a 100×100 RGB image would be a 100×100×3×1 array, and a batch of 50 would be a 100×100×3×50 array.\n\nAccepts keyword arguments weight and bias to set the corresponding fields. Setting bias to Flux.Zeros() will switch bias off for the layer.\n\nTakes the keyword arguments pad, stride and dilation. Use pad=SamePad() to apply padding so that outputsize == inputsize / stride.\n\nExamples\n\nApply a Conv layer to a 1-channel input using a 2×2 window filter size, giving us a 16-channel output. Output is activated with ReLU.\n\nfilter = (2,2)\nin = 1\nout = 16\nConv(filter, in => out, relu)\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.MaxPool","page":"Model Reference","title":"Flux.MaxPool","text":"MaxPool(k; pad = 0, stride = k)\n\nMax pooling layer. k is the size of the window for each dimension of the input.\n\nUse pad=SamePad() to apply padding so that outputsize == inputsize / stride.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.GlobalMaxPool","page":"Model Reference","title":"Flux.GlobalMaxPool","text":"GlobalMaxPool()\n\nGlobal max pooling layer.\n\nTransforms (w,h,c,b)-shaped input into (1,1,c,b)-shaped output, by performing max pooling on the complete (w,h)-shaped feature maps.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.MeanPool","page":"Model Reference","title":"Flux.MeanPool","text":"MeanPool(k; pad = 0, stride = k)\n\nMean pooling layer. k is the size of the window for each dimension of the input.\n\nUse pad=SamePad() to apply padding so that outputsize == inputsize / stride.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.GlobalMeanPool","page":"Model Reference","title":"Flux.GlobalMeanPool","text":"GlobalMeanPool()\n\nGlobal mean pooling layer.\n\nTransforms (w,h,c,b)-shaped input into (1,1,c,b)-shaped output, by performing mean pooling on the complete (w,h)-shaped feature maps.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.DepthwiseConv","page":"Model Reference","title":"Flux.DepthwiseConv","text":"DepthwiseConv(filter::Tuple, in=>out)\nDepthwiseConv(filter::Tuple, in=>out, activation)\nDepthwiseConv(filter, in => out, σ = identity; init = glorot_uniform,\n stride = 1, pad = 0, dilation = 1)\n\nDepthwise convolutional layer. filter should be a tuple like (2, 2). in and out specify the number of input and output channels respectively. Note that out must be an integer multiple of in.\n\nData should be stored in WHCN order (width, height, # channels, batch size). In other words, a 100×100 RGB image would be a 100×100×3×1 array, and a batch of 50 would be a 100×100×3×50 array.\n\nAccepts keyword arguments weight and bias to set the corresponding fields. Setting bias to Flux.Zeros() will switch bias off for the layer.\n\nTakes the keyword arguments pad, stride and dilation. Use pad=SamePad() to apply padding so that outputsize == inputsize / stride.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.ConvTranspose","page":"Model Reference","title":"Flux.ConvTranspose","text":"ConvTranspose(filter, in=>out)\nConvTranspose(filter, in=>out, activation)\nConvTranspose(filter, in => out, σ = identity; init = glorot_uniform,\n stride = 1, pad = 0, dilation = 1)\n\nStandard convolutional transpose layer. filter should be a tuple like (2, 2). in and out specify the number of input and output channels respectively.\n\nData should be stored in WHCN order (width, height, # channels, batch size). In other words, a 100×100 RGB image would be a 100×100×3×1 array, and a batch of 50 would be a 100×100×3×50 array.\n\nAccepts keyword arguments weight and bias to set the corresponding fields. Setting bias to Flux.Zeros() will switch bias off for the layer.\n\nTakes the keyword arguments pad, stride and dilation. Use pad=SamePad() to apply padding so that outputsize == stride * inputsize - stride + 1.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.CrossCor","page":"Model Reference","title":"Flux.CrossCor","text":"CrossCor(filter, in=>out)\nCrossCor(filter, in=>out, activation)\nCrossCor(filter, in => out, σ = identity; init = glorot_uniform,\n stride = 1, pad = 0, dilation = 1)\n\nStandard cross convolutional layer. filter should be a tuple like (2, 2). in and out specify the number of input and output channels respectively.\n\nData should be stored in WHCN order (width, height, # channels, batch size). In other words, a 100×100 RGB image would be a 100×100×3×1 array, and a batch of 50 would be a 100×100×3×50 array.\n\nAccepts keyword arguments weight and bias to set the corresponding fields. Setting bias to Flux.Zeros() will switch bias off for the layer.\n\nTakes the keyword arguments pad, stride and dilation. Use pad=SamePad() to apply padding so that outputsize == inputsize / stride.\n\nExamples\n\nApply a CrossCor layer to a 1-channel input using a 2×2 window filter size, giving us a 16-channel output. Output is activated with ReLU.\n\nfilter = (2,2)\nin = 1\nout = 16\nCrossCor((2, 2), 1=>16, relu)\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.SamePad","page":"Model Reference","title":"Flux.SamePad","text":"SamePad\n\nPadding for convolutional layers will be calculated so that outputshape == inputshape when stride = 1.\n\nFor stride > 1 the output shape depends on the type of convolution layer.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.flatten","page":"Model Reference","title":"Flux.flatten","text":"flatten(x::AbstractArray)\n\nTransform (w, h, c, b)-shaped input into (w × h × c, b)-shaped output by linearizing all values for each element in the batch.\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.Zeros","page":"Model Reference","title":"Flux.Zeros","text":"Zeros()\nZeros(size...)\nZeros(Type, size...)\n\nActs as a stand-in for an array of zeros that can be used during training which is ignored by the optimisers.\n\nUseful to turn bias off for a forward pass of a layer.\n\nExamples\n\njulia> Flux.Zeros(3,3)\n3×3 Flux.Zeros{Bool,2}:\n false false false\n false false false\n false false false\n\njulia> Flux.Zeros(Float32, 3,3)\n3×3 Flux.Zeros{Float32,2}:\n 0.0 0.0 0.0\n 0.0 0.0 0.0\n 0.0 0.0 0.0\n\njulia> rand(3,3) .+ Flux.Zeros()\n3×3 Array{Float64,2}:\n 0.198739 0.490459 0.785386\n 0.779074 0.39986 0.66383\n 0.854981 0.447292 0.314497\n\njulia> bias_less_conv = Conv((2,2), 1=>3, bias = Flux.Zeros())\nConv((2, 2), 1=>3)\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.convfilter","page":"Model Reference","title":"Flux.convfilter","text":"convfilter(filter::Tuple, in=>out)\n\nConstructs a standard convolutional weight matrix with given filter and channels from in to out.\n\nAccepts the keyword init (default: glorot_uniform) to control the sampling distribution.\n\nSee also: depthwiseconvfilter\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.depthwiseconvfilter","page":"Model Reference","title":"Flux.depthwiseconvfilter","text":"depthwiseconvfilter(filter::Tuple, in=>out)\n\nConstructs a depthwise convolutional weight array defined by filter and channels from in to out.\n\nAccepts the keyword init (default: glorot_uniform) to control the sampling distribution.\n\nSee also: convfilter\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Recurrent-Layers-1","page":"Model Reference","title":"Recurrent Layers","text":"","category":"section"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"Much like the core layers above, but can be used to process sequence data (as well as other kinds of structured data).","category":"page"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"RNN\nLSTM\nGRU\nFlux.Recur\nFlux.reset!","category":"page"},{"location":"models/layers/#Flux.RNN","page":"Model Reference","title":"Flux.RNN","text":"RNN(in::Integer, out::Integer, σ = tanh)\n\nThe most basic recurrent layer; essentially acts as a Dense layer, but with the output fed back into the input each time step.\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.LSTM","page":"Model Reference","title":"Flux.LSTM","text":"LSTM(in::Integer, out::Integer)\n\nLong Short Term Memory recurrent layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.\n\nSee this article for a good overview of the internals.\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.GRU","page":"Model Reference","title":"Flux.GRU","text":"GRU(in::Integer, out::Integer)\n\nGated Recurrent Unit layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.\n\nSee this article for a good overview of the internals.\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.Recur","page":"Model Reference","title":"Flux.Recur","text":"Recur(cell)\n\nRecur takes a recurrent cell and makes it stateful, managing the hidden state in the background. cell should be a model of the form:\n\nh, y = cell(h, x...)\n\nFor example, here's a recurrent network that keeps a running total of its inputs:\n\naccum(h, x) = (h + x, x)\nrnn = Flux.Recur(accum, 0)\nrnn(2) # 2\nrnn(3) # 3\nrnn.state # 5\nrnn.(1:10) # apply to a sequence\nrnn.state # 60\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.reset!","page":"Model Reference","title":"Flux.reset!","text":"reset!(rnn)\n\nReset the hidden state of a recurrent layer back to its original value.\n\nAssuming you have a Recur layer rnn, this is roughly equivalent to:\n\nrnn.state = hidden(rnn.cell)\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Other-General-Purpose-Layers-1","page":"Model Reference","title":"Other General Purpose Layers","text":"","category":"section"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"These are marginally more obscure than the Basic Layers. But in contrast to the layers described in the other sections are not readily grouped around a particular purpose (e.g. CNNs or RNNs).","category":"page"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"Maxout\nSkipConnection","category":"page"},{"location":"models/layers/#Flux.Maxout","page":"Model Reference","title":"Flux.Maxout","text":"Maxout(over)\n\nThe Maxout layer has a number of internal layers which all receive the same input. It returns the elementwise maximum of the internal layers' outputs.\n\nMaxout over linear dense layers satisfies the univeral approximation theorem.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.SkipConnection","page":"Model Reference","title":"Flux.SkipConnection","text":"SkipConnection(layer, connection)\n\nCreate a skip connection which consists of a layer or Chain of consecutive layers and a shortcut connection linking the block's input to the output through a user-supplied 2-argument callable. The first argument to the callable will be propagated through the given layer while the second is the unchanged, \"skipped\" input.\n\nThe simplest \"ResNet\"-type connection is just SkipConnection(layer, +), and requires the output of the layers to be the same shape as the input. Here is a more complicated example:\n\nm = Conv((3,3), 4=>7, pad=(1,1))\nx = ones(5,5,4,10);\nsize(m(x)) == (5, 5, 7, 10)\n\nsm = SkipConnection(m, (mx, x) -> cat(mx, x, dims=3))\nsize(sm(x)) == (5, 5, 11, 10)\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Normalisation-and-Regularisation-1","page":"Model Reference","title":"Normalisation & Regularisation","text":"","category":"section"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"These layers don't affect the structure of the network but may improve training times or reduce overfitting.","category":"page"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"Flux.normalise\nBatchNorm\nFlux.dropout\nDropout\nAlphaDropout\nLayerNorm\nInstanceNorm\nGroupNorm","category":"page"},{"location":"models/layers/#Flux.normalise","page":"Model Reference","title":"Flux.normalise","text":"normalise(x; dims=1)\n\nNormalise x to mean 0 and standard deviation 1 across the dimensions given by dims. Defaults to normalising over columns.\n\njulia> a = reshape(collect(1:9), 3, 3)\n3×3 Array{Int64,2}:\n 1 4 7\n 2 5 8\n 3 6 9\n\njulia> Flux.normalise(a)\n3×3 Array{Float64,2}:\n -1.22474 -1.22474 -1.22474\n 0.0 0.0 0.0\n 1.22474 1.22474 1.22474\n\njulia> Flux.normalise(a, dims=2)\n3×3 Array{Float64,2}:\n -1.22474 0.0 1.22474\n -1.22474 0.0 1.22474\n -1.22474 0.0 1.22474\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.BatchNorm","page":"Model Reference","title":"Flux.BatchNorm","text":"BatchNorm(channels::Integer, σ = identity;\n initβ = zeros, initγ = ones,\n ϵ = 1e-8, momentum = .1)\n\nBatch Normalization layer. channels should be the size of the channel dimension in your data (see below).\n\nGiven an array with N dimensions, call the N-1th the channel dimension. (For a batch of feature vectors this is just the data dimension, for WHCN images it's the usual channel dimension.)\n\nBatchNorm computes the mean and variance for each each W×H×1×N slice and shifts them to have a new mean and variance (corresponding to the learnable, per-channel bias and scale parameters).\n\nUse testmode! during inference.\n\nExamples\n\nm = Chain(\n Dense(28^2, 64),\n BatchNorm(64, relu),\n Dense(64, 10),\n BatchNorm(10),\n softmax)\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.dropout","page":"Model Reference","title":"Flux.dropout","text":"dropout(x, p; dims = :)\n\nThe dropout function. For each input, either sets that input to 0 (with probability p) or scales it by 1 / (1 - p). dims specifies the unbroadcasted dimensions, e.g. dims=1 applies dropout along columns and dims=2 along rows. This is used as a regularisation, i.e. it reduces overfitting during training.\n\nSee also the Dropout layer.\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.Dropout","page":"Model Reference","title":"Flux.Dropout","text":"Dropout(p, dims = :)\n\nDropout layer. In the forward pass, apply the Flux.dropout function on the input.\n\nDoes nothing to the input once Flux.testmode! is true.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.AlphaDropout","page":"Model Reference","title":"Flux.AlphaDropout","text":"AlphaDropout(p)\n\nA dropout layer. Used in Self-Normalizing Neural Networks. The AlphaDropout layer ensures that mean and variance of activations remain the same as before.\n\nDoes nothing to the input once testmode! is true.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.LayerNorm","page":"Model Reference","title":"Flux.LayerNorm","text":"LayerNorm(h::Integer)\n\nA normalisation layer designed to be used with recurrent hidden states of size h. Normalises the mean and standard deviation of each input before applying a per-neuron gain/bias.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.InstanceNorm","page":"Model Reference","title":"Flux.InstanceNorm","text":"InstanceNorm(channels::Integer, σ = identity;\n initβ = zeros, initγ = ones,\n ϵ = 1e-8, momentum = .1)\n\nInstance Normalization layer. channels should be the size of the channel dimension in your data (see below).\n\nGiven an array with N dimensions, call the N-1th the channel dimension. (For a batch of feature vectors this is just the data dimension, for WHCN images it's the usual channel dimension.)\n\nInstanceNorm computes the mean and variance for each each W×H×1×1 slice and shifts them to have a new mean and variance (corresponding to the learnable, per-channel bias and scale parameters).\n\nUse testmode! during inference.\n\nExamples\n\nm = Chain(\n Dense(28^2, 64),\n InstanceNorm(64, relu),\n Dense(64, 10),\n InstanceNorm(10),\n softmax)\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.GroupNorm","page":"Model Reference","title":"Flux.GroupNorm","text":"GroupNorm(chs::Integer, G::Integer, λ = identity;\n initβ = (i) -> zeros(Float32, i), initγ = (i) -> ones(Float32, i),\n ϵ = 1f-5, momentum = 0.1f0)\n\nGroup Normalization layer. This layer can outperform Batch Normalization and Instance Normalization.\n\nchs is the number of channels, the channel dimension of your input. For an array of N dimensions, the N-1th index is the channel dimension.\n\nG is the number of groups along which the statistics are computed. The number of channels must be an integer multiple of the number of groups.\n\nUse testmode! during inference.\n\nExamples\n\nm = Chain(Conv((3,3), 1=>32, leakyrelu;pad = 1),\n GroupNorm(32,16))\n # 32 channels, 16 groups (G = 16), thus 2 channels per group used\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Testmode-1","page":"Model Reference","title":"Testmode","text":"","category":"section"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"Many normalisation layers behave differently under training and inference (testing). By default, Flux will automatically determine when a layer evaluation is part of training or inference. Still, depending on your use case, it may be helpful to manually specify when these layers should be treated as being trained or not. For this, Flux provides Flux.testmode!. When called on a model (e.g. a layer or chain of layers), this function will place the model into the mode specified.","category":"page"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"Flux.testmode!\ntrainmode!","category":"page"},{"location":"models/layers/#Flux.testmode!","page":"Model Reference","title":"Flux.testmode!","text":"testmode!(m, mode = true)\n\nSet a layer or model's test mode (see below). Using :auto mode will treat any gradient computation as training.\n\nNote: if you manually set a model into test mode, you need to manually place it back into train mode during training phase.\n\nPossible values include:\n\nfalse for training\ntrue for testing\n:auto or nothing for Flux to detect the mode automatically\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.trainmode!","page":"Model Reference","title":"Flux.trainmode!","text":"trainmode!(m, mode = true)\n\nSet a layer of model's train mode (see below). Symmetric to testmode! (i.e. `trainmode!(m, mode) == testmode!(m, !mode)).\n\nNote: if you manually set a model into train mode, you need to manually place it into test mode during testing phase.\n\nPossible values include:\n\ntrue for training\nfalse for testing\n:auto or nothing for Flux to detect the mode automatically\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Cost-Functions-1","page":"Model Reference","title":"Cost Functions","text":"","category":"section"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"Flux.mae\nFlux.mse\nFlux.msle\nFlux.huber_loss\nFlux.crossentropy\nFlux.logitcrossentropy\nFlux.binarycrossentropy\nFlux.logitbinarycrossentropy\nFlux.kldivergence\nFlux.poisson\nFlux.hinge\nFlux.squared_hinge\nFlux.dice_coeff_loss\nFlux.tversky_loss","category":"page"},{"location":"models/layers/#Flux.mae","page":"Model Reference","title":"Flux.mae","text":"mae(ŷ, y)\n\nReturn the mean of absolute error; calculated as sum(abs.(ŷ .- y)) / length(y).\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.mse","page":"Model Reference","title":"Flux.mse","text":"mse(ŷ, y)\n\nReturn the mean squared error between ŷ and y; calculated as sum((ŷ .- y).^2) / length(y).\n\nExamples\n\njulia> Flux.mse([0, 2], [1, 1])\n1//1\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.msle","page":"Model Reference","title":"Flux.msle","text":"msle(ŷ, y; ϵ=eps(eltype(ŷ)))\n\nReturn the mean of the squared logarithmic errors; calculated as sum((log.(ŷ .+ ϵ) .- log.(y .+ ϵ)).^2) / length(y). The ϵ term provides numerical stability.\n\nPenalizes an under-predicted estimate greater than an over-predicted estimate.\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.huber_loss","page":"Model Reference","title":"Flux.huber_loss","text":"huber_loss(ŷ, y; δ=1.0)\n\nReturn the mean of the Huber loss given the prediction ŷ and true values y.\n\n | 0.5 * |ŷ - y|, for |ŷ - y| <= δ\nHuber loss = |\n | δ * (|ŷ - y| - 0.5 * δ), otherwise\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.crossentropy","page":"Model Reference","title":"Flux.crossentropy","text":"crossentropy(ŷ, y; weight = nothing)\n\nReturn the cross entropy between the given probability distributions; calculated as -sum(y .* log.(ŷ) .* weight) / size(y, 2).\n\nweight can be Nothing, a Number or an AbstractVector. weight=nothing acts like weight=1 but is faster.\n\nSee also: Flux.logitcrossentropy, Flux.binarycrossentropy, Flux.logitbinarycrossentropy\n\nExamples\n\njulia> Flux.crossentropy(softmax([-1.1491, 0.8619, 0.3127]), [1, 1, 0])\n3.085467254747739\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.logitcrossentropy","page":"Model Reference","title":"Flux.logitcrossentropy","text":"logitcrossentropy(ŷ, y; weight = 1)\n\nReturn the crossentropy computed after a Flux.logsoftmax operation; calculated as -sum(y .* logsoftmax(ŷ) .* weight) / size(y, 2).\n\nlogitcrossentropy(ŷ, y) is mathematically equivalent to Flux.crossentropy(softmax(ŷ), y) but it is more numerically stable.\n\nSee also: Flux.crossentropy, Flux.binarycrossentropy, Flux.logitbinarycrossentropy\n\nExamples\n\njulia> Flux.logitcrossentropy([-1.1491, 0.8619, 0.3127], [1, 1, 0])\n3.085467254747738\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.binarycrossentropy","page":"Model Reference","title":"Flux.binarycrossentropy","text":"binarycrossentropy(ŷ, y; ϵ=eps(ŷ))\n\nReturn -y*log(y + ϵ) - (1-y)*log(1-y + ϵ). The ϵ term provides numerical stability.\n\nTypically, the prediction ŷ is given by the output of a sigmoid activation.\n\nSee also: Flux.crossentropy, Flux.logitcrossentropy, Flux.logitbinarycrossentropy\n\nExamples\n\njulia> Flux.binarycrossentropy.(σ.([-1.1491, 0.8619, 0.3127]), [1, 1, 0])\n3-element Array{Float64,1}:\n 1.424397097347566\n 0.35231664672364077\n 0.8616703662235441\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.logitbinarycrossentropy","page":"Model Reference","title":"Flux.logitbinarycrossentropy","text":"logitbinarycrossentropy(ŷ, y)\n\nlogitbinarycrossentropy(ŷ, y) is mathematically equivalent to Flux.binarycrossentropy(σ(ŷ), y) but it is more numerically stable.\n\nSee also: Flux.crossentropy, Flux.logitcrossentropy, Flux.binarycrossentropy\n\nExamples\n\njulia> Flux.logitbinarycrossentropy.([-1.1491, 0.8619, 0.3127], [1, 1, 0])\n3-element Array{Float64,1}:\n 1.4243970973475661\n 0.35231664672364094\n 0.8616703662235443\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.kldivergence","page":"Model Reference","title":"Flux.kldivergence","text":"kldivergence(ŷ, y)\n\nReturn the Kullback-Leibler divergence between the given probability distributions.\n\nKL divergence is a measure of how much one probability distribution is different from the other. It is always non-negative and zero only when both the distributions are equal everywhere.\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.poisson","page":"Model Reference","title":"Flux.poisson","text":"poisson(ŷ, y)\n\nReturn how much the predicted distribution ŷ diverges from the expected Poisson distribution y; calculated as sum(ŷ .- y .* log.(ŷ)) / size(y, 2).\n\nMore information..\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.hinge","page":"Model Reference","title":"Flux.hinge","text":"hinge(ŷ, y)\n\nReturn the hinge loss given the prediction ŷ and true labels y (containing 1 or -1); calculated as sum(max.(0, 1 .- ŷ .* y)) / size(y, 2).\n\nSee also: squared_hinge\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.squared_hinge","page":"Model Reference","title":"Flux.squared_hinge","text":"squared_hinge(ŷ, y)\n\nReturn the squared hinge loss given the prediction ŷ and true labels y (containing 1 or -1); calculated as sum((max.(0, 1 .- ŷ .* y)).^2) / size(y, 2).\n\nSee also: hinge\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.dice_coeff_loss","page":"Model Reference","title":"Flux.dice_coeff_loss","text":"dice_coeff_loss(ŷ, y; smooth=1)\n\nReturn a loss based on the dice coefficient. Used in the V-Net image segmentation architecture. Similar to the F1_score. Calculated as: 1 - 2sum(|ŷ . y| + smooth) / (sum(ŷ.^2) + sum(y.^2) + smooth)`\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#Flux.tversky_loss","page":"Model Reference","title":"Flux.tversky_loss","text":"tversky_loss(ŷ, y; β=0.7)\n\nReturn the Tversky loss. Used with imbalanced data to give more weight to false negatives. Larger β weigh recall higher than precision (by placing more emphasis on false negatives) Calculated as: 1 - sum(|y .* ŷ| + 1) / (sum(y .* ŷ + β(1 .- y) . ŷ + (1 - β)y . (1 .- ŷ)) + 1)\n\n\n\n\n\n","category":"function"},{"location":"community/#Community-1","page":"Community","title":"Community","text":"","category":"section"},{"location":"community/#","page":"Community","title":"Community","text":"All Flux users are welcome to join our community on the Julia forum, or the slack (channel #machine-learning). If you have questions or issues we'll try to help you out.","category":"page"},{"location":"community/#","page":"Community","title":"Community","text":"If you're interested in hacking on Flux, the source code is open and easy to understand – it's all just the same Julia code you work with normally. You might be interested in our intro issues to get started.","category":"page"},{"location":"models/recurrence/#Recurrent-Models-1","page":"Recurrence","title":"Recurrent Models","text":"","category":"section"},{"location":"models/recurrence/#Recurrent-Cells-1","page":"Recurrence","title":"Recurrent Cells","text":"","category":"section"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"In the simple feedforward case, our model m is a simple function from various inputs xᵢ to predictions yᵢ. (For example, each x might be an MNIST digit and each y a digit label.) Each prediction is completely independent of any others, and using the same x will always produce the same y.","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"y₁ = f(x₁)\ny₂ = f(x₂)\ny₃ = f(x₃)\n# ...","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"Recurrent networks introduce a hidden state that gets carried over each time we run the model. The model now takes the old h as an input, and produces a new h as output, each time we run it.","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"h = # ... initial state ...\nh, y₁ = f(h, x₁)\nh, y₂ = f(h, x₂)\nh, y₃ = f(h, x₃)\n# ...","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"Information stored in h is preserved for the next prediction, allowing it to function as a kind of memory. This also means that the prediction made for a given x depends on all the inputs previously fed into the model.","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"(This might be important if, for example, each x represents one word of a sentence; the model's interpretation of the word \"bank\" should change if the previous input was \"river\" rather than \"investment\".)","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"Flux's RNN support closely follows this mathematical perspective. The most basic RNN is as close as possible to a standard Dense layer, and the output is also the hidden state.","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"Wxh = randn(5, 10)\nWhh = randn(5, 5)\nb = randn(5)\n\nfunction rnn(h, x)\n h = tanh.(Wxh * x .+ Whh * h .+ b)\n return h, h\nend\n\nx = rand(10) # dummy data\nh = rand(5) # initial hidden state\n\nh, y = rnn(h, x)","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"If you run the last line a few times, you'll notice the output y changing slightly even though the input x is the same.","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"We sometimes refer to functions like rnn above, which explicitly manage state, as recurrent cells. There are various recurrent cells available, which are documented in the layer reference. The hand-written example above can be replaced with:","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"using Flux\n\nrnn2 = Flux.RNNCell(10, 5)\n\nx = rand(10) # dummy data\nh = rand(5) # initial hidden state\n\nh, y = rnn2(h, x)","category":"page"},{"location":"models/recurrence/#Stateful-Models-1","page":"Recurrence","title":"Stateful Models","text":"","category":"section"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"For the most part, we don't want to manage hidden states ourselves, but to treat our models as being stateful. Flux provides the Recur wrapper to do this.","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"x = rand(10)\nh = rand(5)\n\nm = Flux.Recur(rnn, h)\n\ny = m(x)","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"The Recur wrapper stores the state between runs in the m.state field.","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"If you use the RNN(10, 5) constructor – as opposed to RNNCell – you'll see that it's simply a wrapped cell.","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"julia> RNN(10, 5)\nRecur(RNNCell(10, 5, tanh))","category":"page"},{"location":"models/recurrence/#Sequences-1","page":"Recurrence","title":"Sequences","text":"","category":"section"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"Often we want to work with sequences of inputs, rather than individual xs.","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"seq = [rand(10) for i = 1:10]","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"With Recur, applying our model to each element of a sequence is trivial:","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"m.(seq) # returns a list of 5-element vectors","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"This works even when we've chain recurrent layers into a larger model.","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"m = Chain(LSTM(10, 15), Dense(15, 5))\nm.(seq)","category":"page"},{"location":"models/recurrence/#","page":"Recurrence","title":"Recurrence","text":"Finally, we can reset the hidden state of the cell back to its initial value using reset!(m).","category":"page"},{"location":"training/training/#Training-1","page":"Training","title":"Training","text":"","category":"section"},{"location":"training/training/#","page":"Training","title":"Training","text":"To actually train a model we need four things:","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"A objective function, that evaluates how well a model is doing given some input data.\nThe trainable parameters of the model.\nA collection of data points that will be provided to the objective function.\nAn optimiser that will update the model parameters appropriately.","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"With these we can call train!:","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"Flux.Optimise.train!","category":"page"},{"location":"training/training/#Flux.Optimise.train!","page":"Training","title":"Flux.Optimise.train!","text":"train!(loss, params, data, opt; cb)\n\nFor each datapoint d in data compute the gradient of loss(d...) through backpropagation and call the optimizer opt.\n\nIn case datapoints d are of numeric array type, assume no splatting is needed and compute the gradient of loss(d).\n\nA callback is given with the keyword argument cb. For example, this will print \"training\" every 10 seconds (using Flux.throttle):\n\ntrain!(loss, params, data, opt, cb = throttle(() -> println(\"training\"), 10))\n\nThe callback can call Flux.stop to interrupt the training loop.\n\nMultiple optimisers and callbacks can be passed to opt and cb as arrays.\n\n\n\n\n\n","category":"function"},{"location":"training/training/#","page":"Training","title":"Training","text":"There are plenty of examples in the model zoo.","category":"page"},{"location":"training/training/#Loss-Functions-1","page":"Training","title":"Loss Functions","text":"","category":"section"},{"location":"training/training/#","page":"Training","title":"Training","text":"The objective function must return a number representing how far the model is from its target – the loss of the model. The loss function that we defined in basics will work as an objective. We can also define an objective in terms of some model:","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"m = Chain(\n Dense(784, 32, σ),\n Dense(32, 10), softmax)\n\nloss(x, y) = Flux.mse(m(x), y)\nps = Flux.params(m)\n\n# later\nFlux.train!(loss, ps, data, opt)","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"The objective will almost always be defined in terms of some cost function that measures the distance of the prediction m(x) from the target y. Flux has several of these built in, like mse for mean squared error or crossentropy for cross entropy loss, but you can calculate it however you want. For a list of all built-in loss functions, check out the layer reference.","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"At first glance it may seem strange that the model that we want to train is not part of the input arguments of Flux.train! too. However the target of the optimizer is not the model itself, but the objective function that represents the departure between modelled and observed data. In other words, the model is implicitly defined in the objective function, and there is no need to give it explicitly. Passing the objective function instead of the model and a cost function separately provides more flexibility, and the possibility of optimizing the calculations.","category":"page"},{"location":"training/training/#Model-parameters-1","page":"Training","title":"Model parameters","text":"","category":"section"},{"location":"training/training/#","page":"Training","title":"Training","text":"The model to be trained must have a set of tracked parameters that are used to calculate the gradients of the objective function. In the basics section it is explained how to create models with such parameters. The second argument of the function Flux.train! must be an object containing those parameters, which can be obtained from a model m as params(m).","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"Such an object contains a reference to the model's parameters, not a copy, such that after their training, the model behaves according to their updated values.","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"Handling all the parameters on a layer by layer basis is explained in the Layer Helpers section. Also, for freezing model parameters, see the Advanced Usage Guide.","category":"page"},{"location":"training/training/#Datasets-1","page":"Training","title":"Datasets","text":"","category":"section"},{"location":"training/training/#","page":"Training","title":"Training","text":"The data argument provides a collection of data to train with (usually a set of inputs x and target outputs y). For example, here's a dummy data set with only one data point:","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"x = rand(784)\ny = rand(10)\ndata = [(x, y)]","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"Flux.train! will call loss(x, y), calculate gradients, update the weights and then move on to the next data point if there is one. We can train the model on the same data three times:","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"data = [(x, y), (x, y), (x, y)]\n# Or equivalently\nusing IterTools: ncycle\ndata = ncycle([(x, y)], 3)","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"It's common to load the xs and ys separately. In this case you can use zip:","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"xs = [rand(784), rand(784), rand(784)]\nys = [rand( 10), rand( 10), rand( 10)]\ndata = zip(xs, ys)","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"Training data can be conveniently partitioned for mini-batch training using the Flux.Data.DataLoader type:","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"X = rand(28, 28, 60000)\nY = rand(0:9, 60000)\ndata = DataLoader(X, Y, batchsize=128) ","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"Note that, by default, train! only loops over the data once (a single \"epoch\"). A convenient way to run multiple epochs from the REPL is provided by @epochs.","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"julia> using Flux: @epochs\n\njulia> @epochs 2 println(\"hello\")\nINFO: Epoch 1\nhello\nINFO: Epoch 2\nhello\n\njulia> @epochs 2 Flux.train!(...)\n# Train for two epochs","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"Flux.@epochs","category":"page"},{"location":"training/training/#Flux.Optimise.@epochs","page":"Training","title":"Flux.Optimise.@epochs","text":"@epochs N body\n\nRun body N times. Mainly useful for quickly doing multiple epochs of training in a REPL.\n\nExamples\n\njulia> Flux.@epochs 2 println(\"hello\")\n[ Info: Epoch 1\nhello\n[ Info: Epoch 2\nhello\n\n\n\n\n\n","category":"macro"},{"location":"training/training/#Callbacks-1","page":"Training","title":"Callbacks","text":"","category":"section"},{"location":"training/training/#","page":"Training","title":"Training","text":"train! takes an additional argument, cb, that's used for callbacks so that you can observe the training process. For example:","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"train!(objective, ps, data, opt, cb = () -> println(\"training\"))","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"Callbacks are called for every batch of training data. You can slow this down using Flux.throttle(f, timeout) which prevents f from being called more than once every timeout seconds.","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"A more typical callback might look like this:","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"test_x, test_y = # ... create single batch of test data ...\nevalcb() = @show(loss(test_x, test_y))\n\nFlux.train!(objective, ps, data, opt,\n cb = throttle(evalcb, 5))","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"Calling Flux.stop() in a callback will exit the training loop early.","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"cb = function ()\n accuracy() > 0.9 && Flux.stop()\nend","category":"page"},{"location":"training/training/#Custom-Training-loops-1","page":"Training","title":"Custom Training loops","text":"","category":"section"},{"location":"training/training/#","page":"Training","title":"Training","text":"The Flux.train! function can be very convenient, especially for simple problems. Its also very flexible with the use of callbacks. But for some problems its much cleaner to write your own custom training loop. An example follows that works similar to the default Flux.train but with no callbacks. You don't need callbacks if you just code the calls to your functions directly into the loop. E.g. in the places marked with comments.","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"function my_custom_train!(loss, ps, data, opt)\n ps = Params(ps)\n for d in data\n gs = gradient(ps) do\n training_loss = loss(d...)\n # Insert what ever code you want here that needs Training loss, e.g. logging\n return training_loss\n end\n # insert what ever code you want here that needs gradient\n # E.g. logging with TensorBoardLogger.jl as histogram so you can see if it is becoming huge\n update!(opt, ps, gs)\n # Here you might like to check validation set accuracy, and break out to do early stopping\n end\nend","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"You could simplify this further, for example by hard-coding in the loss function.","category":"page"},{"location":"gpu/#GPU-Support-1","page":"GPU Support","title":"GPU Support","text":"","category":"section"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"NVIDIA GPU support should work out of the box on systems with CUDA and CUDNN installed. For more details see the CuArrays readme.","category":"page"},{"location":"gpu/#GPU-Usage-1","page":"GPU Support","title":"GPU Usage","text":"","category":"section"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"Support for array operations on other hardware backends, like GPUs, is provided by external packages like CuArrays. Flux is agnostic to array types, so we simply need to move model weights and data to the GPU and Flux will handle it.","category":"page"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"For example, we can use CuArrays (with the cu converter) to run our basic example on an NVIDIA GPU.","category":"page"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"(Note that you need to have CUDA available to use CuArrays – please see the CuArrays.jl instructions for more details.)","category":"page"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"using CuArrays\n\nW = cu(rand(2, 5)) # a 2×5 CuArray\nb = cu(rand(2))\n\npredict(x) = W*x .+ b\nloss(x, y) = sum((predict(x) .- y).^2)\n\nx, y = cu(rand(5)), cu(rand(2)) # Dummy data\nloss(x, y) # ~ 3","category":"page"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"Note that we convert both the parameters (W, b) and the data set (x, y) to cuda arrays. Taking derivatives and training works exactly as before.","category":"page"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"If you define a structured model, like a Dense layer or Chain, you just need to convert the internal parameters. Flux provides fmap, which allows you to alter all parameters of a model at once.","category":"page"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"d = Dense(10, 5, σ)\nd = fmap(cu, d)\nd.W # CuArray\nd(cu(rand(10))) # CuArray output\n\nm = Chain(Dense(10, 5, σ), Dense(5, 2), softmax)\nm = fmap(cu, m)\nd(cu(rand(10)))","category":"page"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"As a convenience, Flux provides the gpu function to convert models and data to the GPU if one is available. By default, it'll do nothing, but loading CuArrays will cause it to move data to the GPU instead.","category":"page"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"julia> using Flux, CuArrays\n\njulia> m = Dense(10,5) |> gpu\nDense(10, 5)\n\njulia> x = rand(10) |> gpu\n10-element CuArray{Float32,1}:\n 0.800225\n ⋮\n 0.511655\n\njulia> m(x)\n5-element CuArray{Float32,1}:\n -0.30535\n ⋮\n -0.618002","category":"page"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"The analogue cpu is also available for moving models and data back off of the GPU.","category":"page"},{"location":"gpu/#","page":"GPU Support","title":"GPU Support","text":"julia> x = rand(10) |> gpu\n10-element CuArray{Float32,1}:\n 0.235164\n ⋮\n 0.192538\n\njulia> x |> cpu\n10-element Array{Float32,1}:\n 0.235164\n ⋮\n 0.192538","category":"page"},{"location":"#Flux:-The-Julia-Machine-Learning-Library-1","page":"Home","title":"Flux: The Julia Machine Learning Library","text":"","category":"section"},{"location":"#","page":"Home","title":"Home","text":"Flux is a library for machine learning. It comes \"batteries-included\" with many useful tools built in, but also lets you use the full power of the Julia language where you need it. We follow a few key principles:","category":"page"},{"location":"#","page":"Home","title":"Home","text":"Doing the obvious thing. Flux has relatively few explicit APIs for features like regularisation or embeddings. Instead, writing down the mathematical form will work – and be fast.\nYou could have written Flux. All of it, from LSTMs to GPU kernels, is straightforward Julia code. When in doubt, it’s well worth looking at the source. If you need something different, you can easily roll your own.\nPlay nicely with others. Flux works well with Julia libraries from data frames and images to differential equation solvers, so you can easily build complex data processing pipelines that integrate Flux models.","category":"page"},{"location":"#Installation-1","page":"Home","title":"Installation","text":"","category":"section"},{"location":"#","page":"Home","title":"Home","text":"Download Julia 1.0 or later, if you haven't already. You can add Flux from using Julia's package manager, by typing ] add Flux in the Julia prompt.","category":"page"},{"location":"#","page":"Home","title":"Home","text":"If you have CUDA you can also run ] add CuArrays to get GPU support; see here for more details.","category":"page"},{"location":"#Learning-Flux-1","page":"Home","title":"Learning Flux","text":"","category":"section"},{"location":"#","page":"Home","title":"Home","text":"There are several different ways to learn Flux. If you just want to get started writing models, the model zoo gives good starting points for many common ones. This documentation provides a reference to all of Flux's APIs, as well as a from-scratch introduction to Flux's take on models and how they work. Once you understand these docs, congratulations, you also understand Flux's source code, which is intended to be concise, legible and a good reference for more advanced concepts.","category":"page"},{"location":"models/basics/#Model-Building-Basics-1","page":"Basics","title":"Model-Building Basics","text":"","category":"section"},{"location":"models/basics/#Taking-Gradients-1","page":"Basics","title":"Taking Gradients","text":"","category":"section"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Flux's core feature is taking gradients of Julia code. The gradient function takes another Julia function f and a set of arguments, and returns the gradient with respect to each argument. (It's a good idea to try pasting these examples in the Julia terminal.)","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"julia> using Flux\n\njulia> f(x) = 3x^2 + 2x + 1;\n\njulia> df(x) = gradient(f, x)[1]; # df/dx = 6x + 2\n\njulia> df(2)\n14\n\njulia> d2f(x) = gradient(df, x)[1]; # d²f/dx² = 6\n\njulia> d2f(2)\n6","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"When a function has many parameters, we can get gradients of each one at the same time:","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"julia> f(x, y) = sum((x .- y).^2);\n\njulia> gradient(f, [2, 1], [2, 0])\n([0, 2], [0, -2])","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"But machine learning models can have hundreds of parameters! To handle this, Flux lets you work with collections of parameters, via params. You can get the gradient of all parameters used in a program without explicitly passing them in.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"julia> x = [2, 1];\n\njulia> y = [2, 0];\n\njulia> gs = gradient(params(x, y)) do\n f(x, y)\n end\nGrads(...)\n\njulia> gs[x]\n2-element Array{Int64,1}:\n 0\n 2\n\njulia> gs[y]\n2-element Array{Int64,1}:\n 0\n -2","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Here, gradient takes a zero-argument function; no arguments are necessary because the params tell it what to differentiate.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"This will come in really handy when dealing with big, complicated models. For now, though, let's start with something simple.","category":"page"},{"location":"models/basics/#Simple-Models-1","page":"Basics","title":"Simple Models","text":"","category":"section"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Consider a simple linear regression, which tries to predict an output array y from an input x.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"W = rand(2, 5)\nb = rand(2)\n\npredict(x) = W*x .+ b\n\nfunction loss(x, y)\n ŷ = predict(x)\n sum((y .- ŷ).^2)\nend\n\nx, y = rand(5), rand(2) # Dummy data\nloss(x, y) # ~ 3","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"To improve the prediction we can take the gradients of W and b with respect to the loss and perform gradient descent.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"using Flux\n\ngs = gradient(() -> loss(x, y), params(W, b))","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Now that we have gradients, we can pull them out and update W to train the model.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"W̄ = gs[W]\n\nW .-= 0.1 .* W̄\n\nloss(x, y) # ~ 2.5","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"The loss has decreased a little, meaning that our prediction x is closer to the target y. If we have some data we can already try training the model.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"All deep learning in Flux, however complex, is a simple generalisation of this example. Of course, models can look very different – they might have millions of parameters or complex control flow. Let's see how Flux handles more complex models.","category":"page"},{"location":"models/basics/#Building-Layers-1","page":"Basics","title":"Building Layers","text":"","category":"section"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"It's common to create more complex models than the linear regression above. For example, we might want to have two linear layers with a nonlinearity like sigmoid (σ) in between them. In the above style we could write this as:","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"using Flux\n\nW1 = rand(3, 5)\nb1 = rand(3)\nlayer1(x) = W1 * x .+ b1\n\nW2 = rand(2, 3)\nb2 = rand(2)\nlayer2(x) = W2 * x .+ b2\n\nmodel(x) = layer2(σ.(layer1(x)))\n\nmodel(rand(5)) # => 2-element vector","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"This works but is fairly unwieldy, with a lot of repetition – especially as we add more layers. One way to factor this out is to create a function that returns linear layers.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"function linear(in, out)\n W = randn(out, in)\n b = randn(out)\n x -> W * x .+ b\nend\n\nlinear1 = linear(5, 3) # we can access linear1.W etc\nlinear2 = linear(3, 2)\n\nmodel(x) = linear2(σ.(linear1(x)))\n\nmodel(rand(5)) # => 2-element vector","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Another (equivalent) way is to create a struct that explicitly represents the affine layer.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"struct Affine\n W\n b\nend\n\nAffine(in::Integer, out::Integer) =\n Affine(randn(out, in), randn(out))\n\n# Overload call, so the object can be used as a function\n(m::Affine)(x) = m.W * x .+ m.b\n\na = Affine(10, 5)\n\na(rand(10)) # => 5-element vector","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Congratulations! You just built the Dense layer that comes with Flux. Flux has many interesting layers available, but they're all things you could have built yourself very easily.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"(There is one small difference with Dense – for convenience it also takes an activation function, like Dense(10, 5, σ).)","category":"page"},{"location":"models/basics/#Stacking-It-Up-1","page":"Basics","title":"Stacking It Up","text":"","category":"section"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"It's pretty common to write models that look something like:","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"layer1 = Dense(10, 5, σ)\n# ...\nmodel(x) = layer3(layer2(layer1(x)))","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"For long chains, it might be a bit more intuitive to have a list of layers, like this:","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"using Flux\n\nlayers = [Dense(10, 5, σ), Dense(5, 2), softmax]\n\nmodel(x) = foldl((x, m) -> m(x), layers, init = x)\n\nmodel(rand(10)) # => 2-element vector","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Handily, this is also provided for in Flux:","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"model2 = Chain(\n Dense(10, 5, σ),\n Dense(5, 2),\n softmax)\n\nmodel2(rand(10)) # => 2-element vector","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"This quickly starts to look like a high-level deep learning library; yet you can see how it falls out of simple abstractions, and we lose none of the power of Julia code.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"A nice property of this approach is that because \"models\" are just functions (possibly with trainable parameters), you can also see this as simple function composition.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"m = Dense(5, 2) ∘ Dense(10, 5, σ)\n\nm(rand(10))","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Likewise, Chain will happily work with any Julia function.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"m = Chain(x -> x^2, x -> x+1)\n\nm(5) # => 26","category":"page"},{"location":"models/basics/#Layer-helpers-1","page":"Basics","title":"Layer helpers","text":"","category":"section"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Flux provides a set of helpers for custom layers, which you can enable by calling","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Flux.@functor Affine","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"This enables a useful extra set of functionality for our Affine layer, such as collecting its parameters or moving it to the GPU.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"For some more helpful tricks, including parameter freezing, please checkout the advanced usage guide.","category":"page"},{"location":"models/basics/#Utility-functions-1","page":"Basics","title":"Utility functions","text":"","category":"section"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Flux provides some utility functions to help you generate models in an automated fashion.","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"outdims enables you to calculate the spatial output dimensions of layers like Conv when applied to input images of a given size. Currently limited to the following layers:","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Chain\nDense\nConv\nDiagonal\nMaxout\nConvTranspose\nDepthwiseConv\nCrossCor\nMaxPool\nMeanPool","category":"page"},{"location":"models/basics/#","page":"Basics","title":"Basics","text":"Flux.outdims","category":"page"},{"location":"models/basics/#Flux.outdims","page":"Basics","title":"Flux.outdims","text":"outdims(c::Chain, isize)\n\nCalculate the output dimensions given the input dimensions, isize.\n\nm = Chain(Conv((3, 3), 3 => 16), Conv((3, 3), 16 => 32))\noutdims(m, (10, 10)) == (6, 6)\n\n\n\n\n\noutdims(l::Dense, isize)\n\nCalculate the output dimensions given the input dimensions, isize.\n\nm = Dense(10, 5)\noutdims(m, (5, 2)) == (5,)\noutdims(m, (10,)) == (5,)\n\n\n\n\n\noutdims(l::Conv, isize::Tuple)\n\nCalculate the output dimensions given the input dimensions isize. Batch size and channel size are ignored as per NNlib.jl.\n\nm = Conv((3, 3), 3 => 16)\noutdims(m, (10, 10)) == (8, 8)\noutdims(m, (10, 10, 1, 3)) == (8, 8)\n\n\n\n\n\n","category":"function"},{"location":"data/onehot/#One-Hot-Encoding-1","page":"One-Hot Encoding","title":"One-Hot Encoding","text":"","category":"section"},{"location":"data/onehot/#","page":"One-Hot Encoding","title":"One-Hot Encoding","text":"It's common to encode categorical variables (like true, false or cat, dog) in \"one-of-k\" or \"one-hot\" form. Flux provides the onehot function to make this easy.","category":"page"},{"location":"data/onehot/#","page":"One-Hot Encoding","title":"One-Hot Encoding","text":"julia> using Flux: onehot, onecold\n\njulia> onehot(:b, [:a, :b, :c])\n3-element Flux.OneHotVector:\n false\n true\n false\n\njulia> onehot(:c, [:a, :b, :c])\n3-element Flux.OneHotVector:\n false\n false\n true","category":"page"},{"location":"data/onehot/#","page":"One-Hot Encoding","title":"One-Hot Encoding","text":"The inverse is onecold (which can take a general probability distribution, as well as just booleans).","category":"page"},{"location":"data/onehot/#","page":"One-Hot Encoding","title":"One-Hot Encoding","text":"julia> onecold(ans, [:a, :b, :c])\n:c\n\njulia> onecold([true, false, false], [:a, :b, :c])\n:a\n\njulia> onecold([0.3, 0.2, 0.5], [:a, :b, :c])\n:c","category":"page"},{"location":"data/onehot/#","page":"One-Hot Encoding","title":"One-Hot Encoding","text":"Flux.onehot\nFlux.onecold","category":"page"},{"location":"data/onehot/#Flux.onehot","page":"One-Hot Encoding","title":"Flux.onehot","text":"onehot(l, labels[, unk])\n\nCreate a OneHotVector with its l-th element true based on the possible set of labels. If unk is given, return onehot(unk, labels) if the input label l is not found in labels; otherwise it will error.\n\nExamples\n\njulia> Flux.onehot(:b, [:a, :b, :c])\n3-element Flux.OneHotVector:\n 0\n 1\n 0\n\njulia> Flux.onehot(:c, [:a, :b, :c])\n3-element Flux.OneHotVector:\n 0\n 0\n 1\n\n\n\n\n\n","category":"function"},{"location":"data/onehot/#Flux.onecold","page":"One-Hot Encoding","title":"Flux.onecold","text":"onecold(y[, labels = 1:length(y)])\n\nInverse operations of onehot.\n\nExamples\n\njulia> Flux.onecold([true, false, false], [:a, :b, :c])\n:a\n\njulia> Flux.onecold([0.3, 0.2, 0.5], [:a, :b, :c])\n:c\n\n\n\n\n\n","category":"function"},{"location":"data/onehot/#Batches-1","page":"One-Hot Encoding","title":"Batches","text":"","category":"section"},{"location":"data/onehot/#","page":"One-Hot Encoding","title":"One-Hot Encoding","text":"onehotbatch creates a batch (matrix) of one-hot vectors, and onecold treats matrices as batches.","category":"page"},{"location":"data/onehot/#","page":"One-Hot Encoding","title":"One-Hot Encoding","text":"julia> using Flux: onehotbatch\n\njulia> onehotbatch([:b, :a, :b], [:a, :b, :c])\n3×3 Flux.OneHotMatrix:\n false true false\n true false true\n false false false\n\njulia> onecold(ans, [:a, :b, :c])\n3-element Array{Symbol,1}:\n :b\n :a\n :b","category":"page"},{"location":"data/onehot/#","page":"One-Hot Encoding","title":"One-Hot Encoding","text":"Note that these operations returned OneHotVector and OneHotMatrix rather than Arrays. OneHotVectors behave like normal vectors but avoid any unnecessary cost compared to using an integer index directly. For example, multiplying a matrix with a one-hot vector simply slices out the relevant row of the matrix under the hood.","category":"page"},{"location":"data/onehot/#","page":"One-Hot Encoding","title":"One-Hot Encoding","text":"Flux.onehotbatch","category":"page"},{"location":"data/onehot/#Flux.onehotbatch","page":"One-Hot Encoding","title":"Flux.onehotbatch","text":"onehotbatch(ls, labels[, unk...])\n\nCreate a OneHotMatrix with a batch of labels based on the possible set of labels. If unk is given, return onehot(unk, labels) if one of the input labels ls is not found in labels; otherwise it will error.\n\nExamples\n\njulia> Flux.onehotbatch([:b, :a, :b], [:a, :b, :c])\n3×3 Flux.OneHotMatrix{Array{Flux.OneHotVector,1}}:\n 0 1 0\n 1 0 1\n 0 0 0\n\n\n\n\n\n","category":"function"}]
|
||
}
|