Flux.jl/v0.10.1/search_index.js
2020-01-13 13:36:03 +00:00

4 lines
72 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var documenterSearchIndex = {"docs":
[{"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/#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":"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 (tracked)","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":"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/#Make-sure-your-activation-and-loss-functions-preserve-the-type-of-their-inputs-1","page":"Performance Tips","title":"Make sure your activation and loss functions preserve the type of their inputs","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.01x + tanh(x)","category":"page"},{"location":"performance/#","page":"Performance Tips","title":"Performance Tips","text":"While one could change your activation function (e.g. to use 0.01f0x) to avoid this when ever your inputs change, the idiomatic (and safe way) 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,-rather-than-sequences-of-Vector-features-1","page":"Performance Tips","title":"Evaluate batches as Matrices of features, rather than sequences of Vector 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":"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\nm = Chain(x -> x^2, x -> x+1)\nm(5) == 26\n\nm = Chain(Dense(10, 5), Dense(5, 2))\nx = rand(10)\nm(x) == m[2](m[1](x))\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\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\nCreates 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\njulia> d = Dense(5, 2)\nDense(5, 2)\n\njulia> d(rand(5))\nTracked 2-element Array{Float64,1}:\n 0.00257447\n -0.00449443\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\nMeanPool\nDepthwiseConv\nConvTranspose\nCrossCor","category":"page"},{"location":"models/layers/#Flux.Conv","page":"Model Reference","title":"Flux.Conv","text":"Conv(size, in=>out)\nConv(size, in=>out, relu)\n\nStandard convolutional layer. size should be a tuple like (2, 2). in and out specify the number of input and output channels respectively.\n\nExample: Applying Conv layer to a 1-channel input using a 2x2 window size, giving us a 16-channel output. Output is activated with ReLU.\n\nsize = (2,2)\nin = 1\nout = 16\nConv((2, 2), 1=>16, relu)\n\nData should be stored in WHCN order (width, height, # channels, # batches). 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\nTakes the keyword arguments pad, stride and dilation.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.MaxPool","page":"Model Reference","title":"Flux.MaxPool","text":"MaxPool(k)\n\nMax pooling layer. k stands for the size of the window for each dimension of the input.\n\nTakes the keyword arguments pad and stride.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.MeanPool","page":"Model Reference","title":"Flux.MeanPool","text":"MeanPool(k)\n\nMean pooling layer. k stands for the size of the window for each dimension of the input.\n\nTakes the keyword arguments pad and stride.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.DepthwiseConv","page":"Model Reference","title":"Flux.DepthwiseConv","text":"DepthwiseConv(size, in=>out)\nDepthwiseConv(size, in=>out, relu)\n\nDepthwise convolutional layer. size 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. In other words, a 100×100 RGB image would be a 100×100×3 array, and a batch of 50 would be a 100×100×3×50 array.\n\nTakes the keyword arguments pad, stride and dilation.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.ConvTranspose","page":"Model Reference","title":"Flux.ConvTranspose","text":"ConvTranspose(size, in=>out)\nConvTranspose(size, in=>out, relu)\n\nStandard convolutional transpose layer. size 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. In other words, a 100×100 RGB image would be a 100×100×3 array, and a batch of 50 would be a 100×100×3×50 array.\n\nTakes the keyword arguments pad, stride and dilation.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.CrossCor","page":"Model Reference","title":"Flux.CrossCor","text":"CrossCor(size, in=>out)\nCrossCor(size, in=>out, relu)\n\nStandard cross convolutional layer. size should be a tuple like (2, 2). in and out specify the number of input and output channels respectively.\n\nExample: Applying CrossCor layer to a 1-channel input using a 2x2 window size, giving us a 16-channel output. Output is activated with ReLU.\n\nsize = (2,2)\nin = 1\nout = 16\nCrossCor((2, 2), 1=>16, relu)\n\nData should be stored in WHCN order (width, height, # channels, # batches). 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\nTakes the keyword arguments pad, stride and dilation.\n\n\n\n\n\n","category":"type"},{"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","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/#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\nMaxout is a neural network layer, which has a number of internal layers, which all have the same input, and the maxout returns the elementwise maximium of the internal layers' outputs.\n\nMaxout over linear dense layers satisfies the univeral approximation theorem.\n\nReference: Ian J. Goodfellow, David Warde-Farley, Mehdi Mirza, Aaron Courville, and Yoshua Bengio.\n\nMaxout networks.\n\nIn Proceedings of the 30th International Conference on International Conference on Machine Learning - Volume 28 (ICML'13), Sanjoy Dasgupta and David McAllester (Eds.), Vol. 28. JMLR.org III-1319-III-1327. https://arxiv.org/pdf/1302.4389.pdf\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.SkipConnection","page":"Model Reference","title":"Flux.SkipConnection","text":"SkipConnection(layers, connection)\n\nCreates a Skip Connection, of a layer or Chain of consecutive layers plus a shortcut connection. The connection function will combine the result of the layers with the original input, to give the final output.\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/#Activation-Functions-1","page":"Model Reference","title":"Activation Functions","text":"","category":"section"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"Non-linearities that go between layers of your model. Most of these functions are defined in NNlib but are available by default in Flux.","category":"page"},{"location":"models/layers/#","page":"Model Reference","title":"Model Reference","text":"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/layers/#","page":"Model Reference","title":"Model Reference","text":"σ\nrelu\nleakyrelu\nelu\nswish","category":"page"},{"location":"models/layers/#NNlib.σ","page":"Model Reference","title":"NNlib.σ","text":"σ(x) = 1 / (1 + exp(-x))\n\nClassic sigmoid activation function.\n\n\n\n\n\n","category":"function"},{"location":"models/layers/#NNlib.relu","page":"Model Reference","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/layers/#NNlib.leakyrelu","page":"Model Reference","title":"NNlib.leakyrelu","text":"leakyrelu(x) = max(0.01x, 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/layers/#NNlib.elu","page":"Model Reference","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/layers/#NNlib.swish","page":"Model Reference","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/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":"BatchNorm\nDropout\nAlphaDropout\nLayerNorm\nGroupNorm","category":"page"},{"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. The channels input 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\nSee Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift.\n\nExample:\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(p, dims = :)\n\nA Dropout layer. For each input, either sets that input to 0 (with probability p) or scales it by 1/(1-p). The dims argument is to specified the unbroadcasted dimensions, i.e. dims=1 does dropout along columns and dims=2 along rows. This is used as a regularisation, i.e. it reduces overfitting during training. see also dropout.\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. It is used in Self-Normalizing Neural Networks. (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf) The AlphaDropout layer ensures that mean and variance of activations remains the same as before.\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/stddev of each input before applying a per-neuron gain/bias.\n\n\n\n\n\n","category":"type"},{"location":"models/layers/#Flux.GroupNorm","page":"Model Reference","title":"Flux.GroupNorm","text":"Group Normalization. This layer can outperform Batch-Normalization and Instance-Normalization.\n\nGroupNorm(chs::Integer, G::Integer, λ = identity;\n initβ = (i) -> zeros(Float32, i), initγ = (i) -> ones(Float32, i),\n ϵ = 1f-5, momentum = 0.1f0)\n\nchs is the number of channels, the channel dimension of your input. For an array of N dimensions, the (N-1)th index is the channel dimension.\n\nG is the number of groups along which the statistics would be computed. The number of channels must be an integer multiple of the number of groups.\n\nExample:\n\nm = Chain(Conv((3,3), 1=>32, leakyrelu;pad = 1),\n GroupNorm(32,16)) # 32 channels, 16 groups (G = 16), thus 2 channels per group used\n\nLink : https://arxiv.org/pdf/1803.08494.pdf\n\n\n\n\n\n","category":"type"},{"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 Flux.train!:","category":"page"},{"location":"training/training/#","page":"Training","title":"Training","text":"Flux.train!(objective, params, data, opt)","category":"page"},{"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.","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/#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\ndata = Iterators.repeated((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":"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/#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":"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 # Tracked 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)\nTracked 5-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":"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: 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":"Descent\nMomentum\nNesterov\nRMSProp\nADAM\nAdaMax\nADAGrad\nADADelta\nAMSGrad\nNADAM\nADAMW","category":"page"},{"location":"training/optimisers/#Flux.Optimise.Descent","page":"Optimisers","title":"Flux.Optimise.Descent","text":"Descent(η)\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 (η): The amount by which the gradients are discounted before updating the weights. Defaults to 0.1.\n\nExample\n\nopt = Descent() # uses default η (0.1)\n\nopt = Descent(0.3) # use provided η\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(η, ρ)\n\nGradient descent with learning rate η and momentum ρ.\n\nParameters\n\nLearning Rate (η): Amount by which gradients are discounted before updating the weights. Defaults to 0.01.\nMomentum (ρ): Parameter that accelerates descent in the relevant direction and dampens oscillations. Defaults to 0.9.\n\nExamples\n\nopt = Momentum() # uses defaults of η = 0.01 and ρ = 0.9\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(η, ρ)\n\nGradient descent with learning rate η and Nesterov momentum ρ.\n\nParameters\n\nLearning Rate (η): Amount by which the gradients are dicsounted berfore updating the weights. Defaults to 0.001.\nNesterov Momentum (ρ): Paramters controlling the amount of nesterov momentum to be applied. Defaults to 0.9.\n\nExamples\n\nopt = Nesterov() # uses defaults η = 0.001 and ρ = 0.9\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(η, ρ)\n\nImplements the RMSProp algortihm. Often a good choice for recurrent networks. Paramters other than learning rate generally don't need tuning.\n\nParameters\n\nLearning Rate (η): Defaults to 0.001.\nRho (ρ): Defaults to 0.9.\n\nExamples\n\nopt = RMSProp() # uses default η = 0.001 and ρ = 0.9\n\nopt = RMSProp(0.002, 0.95)\n\nReferences\n\nRMSProp\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.ADAM","page":"Optimisers","title":"Flux.Optimise.ADAM","text":"ADAM(η, β::Tuple)\n\nImplements the ADAM optimiser.\n\nParamters\n\nLearning Rate (η): Defaults to 0.001.\nBeta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).\n\nExamples\n\nopt = ADAM() # uses the default η = 0.001 and β = (0.9, 0.999)\n\nopt = ADAM(0.001, (0.9, 0.8))\n\nReferences\n\nADAM optimiser.\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.AdaMax","page":"Optimisers","title":"Flux.Optimise.AdaMax","text":"AdaMax(η, β::Tuple)\n\nVariant of ADAM based on ∞-norm.\n\nParameters\n\nLearning Rate (η): Defaults to 0.001\nBeta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).\n\nExamples\n\nopt = AdaMax() # uses default η and β\n\nopt = AdaMax(0.001, (0.9, 0.995))\n\nReferences\n\nAdaMax optimiser.\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.ADAGrad","page":"Optimisers","title":"Flux.Optimise.ADAGrad","text":"ADAGrad(η)\n\nImplements AdaGrad. It has parameter specific learning rates based on how frequently it is updated.\n\nParameters\n\nLearning Rate (η): Defaults to 0.1\n\nExamples\n\nopt = ADAGrad() # uses default η = 0.1\n\nopt = ADAGrad(0.001)\n\nReferences\n\nADAGrad optimiser. Parameters don't need tuning.\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.ADADelta","page":"Optimisers","title":"Flux.Optimise.ADADelta","text":"ADADelta(ρ)\n\nVersion of ADAGrad that adapts learning rate based on a window of past gradient updates. Parameters don't need tuning.\n\nParameters\n\nRho (ρ): Factor by which gradient is decayed at each time step. Defaults to 0.9.\n\nExamples\n\nopt = ADADelta() # uses default ρ = 0.9\nopt = ADADelta(0.89)\n\nReferences\n\nADADelta optimiser.\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.AMSGrad","page":"Optimisers","title":"Flux.Optimise.AMSGrad","text":"AMSGrad(η, β::Tuple)\n\nImplements AMSGrad version of the ADAM optimiser. Parameters don't need tuning.\n\nParameters\n\nLearning Rate (η): Defaults to 0.001.\nBeta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).\n\nExamples\n\nopt = AMSGrad() # uses default η and β\nopt = AMSGrad(0.001, (0.89, 0.995))\n\nReferences\n\nAMSGrad optimiser.\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.NADAM","page":"Optimisers","title":"Flux.Optimise.NADAM","text":"NADAM(η, β::Tuple)\n\nNesterov variant of ADAM. Parameters don't need tuning.\n\nParameters\n\nLearning Rate (η): Defaults to 0.001.\nBeta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).\n\nExamples\n\nopt = NADAM() # uses default η and β\nopt = NADAM(0.002, (0.89, 0.995))\n\nReferences\n\nNADAM optimiser.\n\n\n\n\n\n","category":"type"},{"location":"training/optimisers/#Flux.Optimise.ADAMW","page":"Optimisers","title":"Flux.Optimise.ADAMW","text":"ADAMW(η, β::Tuple, decay)\n\nVariant of ADAM defined by fixing weight decay regularization.\n\nParameters\n\nLearning Rate (η): Defaults to 0.001.\nBeta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).\ndecay: Decay applied to weights during optimisation. Defaults to 0.\n\nExamples\n\nopt = ADAMW() # uses default η, β and decay\nopt = ADAMW(0.001, (0.89, 0.995), 0.1)\n\nReferences\n\nADAMW\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 optimsers 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 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 called simply as Optimiser which takes in a 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 optimser. The defaults of ExpDecay say that its learning rate will be decayed every 1000 steps. It is then applied like any optimser.","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(eta, decay, decay_step, clip)\n\nDiscount the learning rate eta by a multiplicative factor decay every decay_step till a minimum of clip.\n\nParameters\n\nLearning Rate (eta): Defaults to 0.001.\ndecay: Factor by which the learning rate is discounted. Defaults to 0.1.\ndecay_step: Schedules decay operations by setting number of steps between two decay operations. Defaults to 1000.\nclip: Minimum value of learning rate. Defaults to 1e-4.\n\nExample\n\nTo apply exponential decay to an optimiser:\n\n Optimiser(ExpDecay(..), Opt(..))\n\n opt = 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(γ)\n\nApplies inverse time decay to an optimiser, i.e., 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\n\n## Parameters\n - gamma (γ): Defaults to `0.001`\n\n## Example\n\njulia Optimiser(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)\n\nDecays the weight by wd\n\nParameters\n\nweight decay (wd): 0\n\n\n\n\n\n","category":"type"},{"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, its 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> using Flux\n\njulia> 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"}]
}